Completed
Branch Gutenberg/components-query-lim... (09ba10)
by
unknown
63:51 queued 44:50
created
core/libraries/messages/messenger/EE_Email_messenger.class.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -456,7 +456,7 @@
 block discarded – undo
456 456
      * be empty
457 457
      *
458 458
      * @since 4.3.1
459
-     * @return array
459
+     * @return string[]
460 460
      */
461 461
     private function _parse_from()
462 462
     {
Please login to merge, or discard this patch.
Indentation   +644 added lines, -644 removed lines patch added patch discarded remove patch
@@ -6,648 +6,648 @@
 block discarded – undo
6 6
 class EE_Email_messenger extends EE_messenger
7 7
 {
8 8
 
9
-    /**
10
-     * To field for email
11
-     * @var string
12
-     */
13
-    protected $_to = '';
14
-
15
-
16
-    /**
17
-     * CC field for email.
18
-     * @var string
19
-     */
20
-    protected $_cc = '';
21
-
22
-    /**
23
-     * From field for email
24
-     * @var string
25
-     */
26
-    protected $_from = '';
27
-
28
-
29
-    /**
30
-     * Subject field for email
31
-     * @var string
32
-     */
33
-    protected $_subject = '';
34
-
35
-
36
-    /**
37
-     * Content field for email
38
-     * @var string
39
-     */
40
-    protected $_content = '';
41
-
42
-
43
-    /**
44
-     * constructor
45
-     *
46
-     * @access public
47
-     */
48
-    public function __construct()
49
-    {
50
-        // set name and description properties
51
-        $this->name                = 'email';
52
-        $this->description         = sprintf(
53
-            esc_html__(
54
-                'This messenger delivers messages via email using the built-in %s function included with WordPress',
55
-                'event_espresso'
56
-            ),
57
-            '<code>wp_mail</code>'
58
-        );
59
-        $this->label               = array(
60
-            'singular' => esc_html__('email', 'event_espresso'),
61
-            'plural'   => esc_html__('emails', 'event_espresso'),
62
-        );
63
-        $this->activate_on_install = true;
64
-
65
-        // we're using defaults so let's call parent constructor that will take care of setting up all the other
66
-        // properties
67
-        parent::__construct();
68
-    }
69
-
70
-
71
-    /**
72
-     * see abstract declaration in parent class for details.
73
-     */
74
-    protected function _set_admin_pages()
75
-    {
76
-        $this->admin_registered_pages = array(
77
-            'events_edit' => true,
78
-        );
79
-    }
80
-
81
-
82
-    /**
83
-     * see abstract declaration in parent class for details
84
-     */
85
-    protected function _set_valid_shortcodes()
86
-    {
87
-        // remember by leaving the other fields not set, those fields will inherit the valid shortcodes from the
88
-        // message type.
89
-        $this->_valid_shortcodes = array(
90
-            'to'   => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
91
-            'cc' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
92
-            'from' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
93
-        );
94
-    }
95
-
96
-
97
-    /**
98
-     * see abstract declaration in parent class for details
99
-     *
100
-     * @access protected
101
-     * @return void
102
-     */
103
-    protected function _set_validator_config()
104
-    {
105
-        $valid_shortcodes = $this->get_valid_shortcodes();
106
-
107
-        $this->_validator_config = array(
108
-            'to'            => array(
109
-                'shortcodes' => $valid_shortcodes['to'],
110
-                'type'       => 'email',
111
-            ),
112
-            'cc' => array(
113
-                'shortcodes' => $valid_shortcodes['to'],
114
-                'type' => 'email',
115
-            ),
116
-            'from'          => array(
117
-                'shortcodes' => $valid_shortcodes['from'],
118
-                'type'       => 'email',
119
-            ),
120
-            'subject'       => array(
121
-                'shortcodes' => array(
122
-                    'organization',
123
-                    'primary_registration_details',
124
-                    'event_author',
125
-                    'primary_registration_details',
126
-                    'recipient_details',
127
-                ),
128
-            ),
129
-            'content'       => array(
130
-                'shortcodes' => array(
131
-                    'event_list',
132
-                    'attendee_list',
133
-                    'ticket_list',
134
-                    'organization',
135
-                    'primary_registration_details',
136
-                    'primary_registration_list',
137
-                    'event_author',
138
-                    'recipient_details',
139
-                    'recipient_list',
140
-                    'transaction',
141
-                    'messenger',
142
-                ),
143
-            ),
144
-            'attendee_list' => array(
145
-                'shortcodes' => array('attendee', 'event_list', 'ticket_list'),
146
-                'required'   => array('[ATTENDEE_LIST]'),
147
-            ),
148
-            'event_list'    => array(
149
-                'shortcodes' => array(
150
-                    'event',
151
-                    'attendee_list',
152
-                    'ticket_list',
153
-                    'venue',
154
-                    'datetime_list',
155
-                    'attendee',
156
-                    'primary_registration_details',
157
-                    'primary_registration_list',
158
-                    'event_author',
159
-                    'recipient_details',
160
-                    'recipient_list',
161
-                ),
162
-                'required'   => array('[EVENT_LIST]'),
163
-            ),
164
-            'ticket_list'   => array(
165
-                'shortcodes' => array(
166
-                    'event_list',
167
-                    'attendee_list',
168
-                    'ticket',
169
-                    'datetime_list',
170
-                    'primary_registration_details',
171
-                    'recipient_details',
172
-                ),
173
-                'required'   => array('[TICKET_LIST]'),
174
-            ),
175
-            'datetime_list' => array(
176
-                'shortcodes' => array('datetime'),
177
-                'required'   => array('[DATETIME_LIST]'),
178
-            ),
179
-        );
180
-    }
181
-
182
-
183
-    /**
184
-     * @see   parent EE_messenger class for docs
185
-     * @since 4.5.0
186
-     */
187
-    public function do_secondary_messenger_hooks($sending_messenger_name)
188
-    {
189
-        if ($sending_messenger_name = 'html') {
190
-            add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
191
-        }
192
-    }
193
-
194
-
195
-    public function add_email_css(
196
-        $variation_path,
197
-        $messenger,
198
-        $message_type,
199
-        $type,
200
-        $variation,
201
-        $file_extension,
202
-        $url,
203
-        EE_Messages_Template_Pack $template_pack
204
-    ) {
205
-        // prevent recursion on this callback.
206
-        remove_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10);
207
-        $variation = $this->get_variation($template_pack, $message_type, $url, 'main', $variation, false);
208
-
209
-        add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
210
-        return $variation;
211
-    }
212
-
213
-
214
-    /**
215
-     * See parent for details
216
-     *
217
-     * @access protected
218
-     * @return void
219
-     */
220
-    protected function _set_test_settings_fields()
221
-    {
222
-        $this->_test_settings_fields = array(
223
-            'to'      => array(
224
-                'input'      => 'text',
225
-                'label'      => esc_html__('Send a test email to', 'event_espresso'),
226
-                'type'       => 'email',
227
-                'required'   => true,
228
-                'validation' => true,
229
-                'css_class'  => 'large-text',
230
-                'format'     => '%s',
231
-                'default'    => get_bloginfo('admin_email'),
232
-            ),
233
-            'subject' => array(
234
-                'input'      => 'hidden',
235
-                'label'      => '',
236
-                'type'       => 'string',
237
-                'required'   => false,
238
-                'validation' => false,
239
-                'format'     => '%s',
240
-                'value'      => sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name')),
241
-                'default'    => '',
242
-                'css_class'  => '',
243
-            ),
244
-        );
245
-    }
246
-
247
-
248
-    /**
249
-     * _set_template_fields
250
-     * This sets up the fields that a messenger requires for the message to go out.
251
-     *
252
-     * @access  protected
253
-     * @return void
254
-     */
255
-    protected function _set_template_fields()
256
-    {
257
-        // any extra template fields that are NOT used by the messenger but will get used by a messenger field for
258
-        // shortcode replacement get added to the 'extra' key in an associated array indexed by the messenger field
259
-        // they relate to.  This is important for the Messages_admin to know what fields to display to the user.
260
-        //  Also, notice that the "values" are equal to the field type that messages admin will use to know what
261
-        // kind of field to display. The values ALSO have one index labeled "shortcode".  the values in that array
262
-        // indicate which ACTUAL SHORTCODE (i.e. [SHORTCODE]) is required in order for this extra field to be
263
-        // displayed.  If the required shortcode isn't part of the shortcodes array then the field is not needed and
264
-        // will not be displayed/parsed.
265
-        $this->_template_fields = array(
266
-            'to'      => array(
267
-                'input'      => 'text',
268
-                'label'      => esc_html_x(
269
-                    'To',
270
-                    'Label for the "To" field for email addresses',
271
-                    'event_espresso'
272
-                ),
273
-                'type'       => 'string',
274
-                'required'   => true,
275
-                'validation' => true,
276
-                'css_class'  => 'large-text',
277
-                'format'     => '%s',
278
-            ),
279
-            'cc'      => array(
280
-                'input'      => 'text',
281
-                'label'      => esc_html_x(
282
-                    'CC',
283
-                    'Label for the "Carbon Copy" field used for additional email addresses',
284
-                    'event_espresso'
285
-                ),
286
-                'type'       => 'string',
287
-                'required'   => false,
288
-                'validation' => true,
289
-                'css_class'  => 'large-text',
290
-                'format'     => '%s',
291
-            ),
292
-            'from'    => array(
293
-                'input'      => 'text',
294
-                'label'      => esc_html_x(
295
-                    'From',
296
-                    'Label for the "From" field for email addresses.',
297
-                    'event_espresso'
298
-                ),
299
-                'type'       => 'string',
300
-                'required'   => true,
301
-                'validation' => true,
302
-                'css_class'  => 'large-text',
303
-                'format'     => '%s',
304
-            ),
305
-            'subject' => array(
306
-                'input'      => 'text',
307
-                'label'      => esc_html_x(
308
-                    'Subject',
309
-                    'Label for the "Subject" field (short description of contents) for emails.',
310
-                    'event_espresso'
311
-                ),
312
-                'type'       => 'string',
313
-                'required'   => true,
314
-                'validation' => true,
315
-                'css_class'  => 'large-text',
316
-                'format'     => '%s',
317
-            ),
318
-            'content' => '',
319
-            // left empty b/c it is in the "extra array" but messenger still needs needs to know this is a field.
320
-            'extra'   => array(
321
-                'content' => array(
322
-                    'main'          => array(
323
-                        'input'      => 'wp_editor',
324
-                        'label'      => esc_html__('Main Content', 'event_espresso'),
325
-                        'type'       => 'string',
326
-                        'required'   => true,
327
-                        'validation' => true,
328
-                        'format'     => '%s',
329
-                        'rows'       => '15',
330
-                    ),
331
-                    'event_list'    => array(
332
-                        'input'               => 'wp_editor',
333
-                        'label'               => '[EVENT_LIST]',
334
-                        'type'                => 'string',
335
-                        'required'            => true,
336
-                        'validation'          => true,
337
-                        'format'              => '%s',
338
-                        'rows'                => '15',
339
-                        'shortcodes_required' => array('[EVENT_LIST]'),
340
-                    ),
341
-                    'attendee_list' => array(
342
-                        'input'               => 'textarea',
343
-                        'label'               => '[ATTENDEE_LIST]',
344
-                        'type'                => 'string',
345
-                        'required'            => true,
346
-                        'validation'          => true,
347
-                        'format'              => '%s',
348
-                        'css_class'           => 'large-text',
349
-                        'rows'                => '5',
350
-                        'shortcodes_required' => array('[ATTENDEE_LIST]'),
351
-                    ),
352
-                    'ticket_list'   => array(
353
-                        'input'               => 'textarea',
354
-                        'label'               => '[TICKET_LIST]',
355
-                        'type'                => 'string',
356
-                        'required'            => true,
357
-                        'validation'          => true,
358
-                        'format'              => '%s',
359
-                        'css_class'           => 'large-text',
360
-                        'rows'                => '10',
361
-                        'shortcodes_required' => array('[TICKET_LIST]'),
362
-                    ),
363
-                    'datetime_list' => array(
364
-                        'input'               => 'textarea',
365
-                        'label'               => '[DATETIME_LIST]',
366
-                        'type'                => 'string',
367
-                        'required'            => true,
368
-                        'validation'          => true,
369
-                        'format'              => '%s',
370
-                        'css_class'           => 'large-text',
371
-                        'rows'                => '10',
372
-                        'shortcodes_required' => array('[DATETIME_LIST]'),
373
-                    ),
374
-                ),
375
-            ),
376
-        );
377
-    }
378
-
379
-
380
-    /**
381
-     * See definition of this class in parent
382
-     */
383
-    protected function _set_default_message_types()
384
-    {
385
-        $this->_default_message_types = array(
386
-            'payment',
387
-            'payment_refund',
388
-            'registration',
389
-            'not_approved_registration',
390
-            'pending_approval',
391
-        );
392
-    }
393
-
394
-
395
-    /**
396
-     * @see   definition of this class in parent
397
-     * @since 4.5.0
398
-     */
399
-    protected function _set_valid_message_types()
400
-    {
401
-        $this->_valid_message_types = array(
402
-            'payment',
403
-            'registration',
404
-            'not_approved_registration',
405
-            'declined_registration',
406
-            'cancelled_registration',
407
-            'pending_approval',
408
-            'registration_summary',
409
-            'payment_reminder',
410
-            'payment_declined',
411
-            'payment_refund',
412
-        );
413
-    }
414
-
415
-
416
-    /**
417
-     * setting up admin_settings_fields for messenger.
418
-     */
419
-    protected function _set_admin_settings_fields()
420
-    {
421
-    }
422
-
423
-    /**
424
-     * We just deliver the messages don't kill us!!
425
-     *
426
-     * @return bool|WP_Error true if message delivered, false if it didn't deliver OR bubble up any error object if
427
-     *              present.
428
-     * @throws EE_Error
429
-     * @throws \TijsVerkoyen\CssToInlineStyles\Exception
430
-     */
431
-    protected function _send_message()
432
-    {
433
-        $success = wp_mail(
434
-            $this->_to,
435
-            // some old values for subject may be expecting HTML entities to be decoded in the subject
436
-            // and subjects aren't interpreted as HTML, so there should be no HTML in them
437
-            wp_strip_all_tags(wp_specialchars_decode($this->_subject, ENT_QUOTES)),
438
-            $this->_body(),
439
-            $this->_headers()
440
-        );
441
-        if (! $success) {
442
-            EE_Error::add_error(
443
-                sprintf(
444
-                    esc_html__(
445
-                        'The email did not send successfully.%3$sThe WordPress wp_mail function is used for sending mails but does not give any useful information when an email fails to send.%3$sIt is possible the "to" address (%1$s) or "from" address (%2$s) is invalid.%3$s',
446
-                        'event_espresso'
447
-                    ),
448
-                    $this->_to,
449
-                    $this->_from,
450
-                    '<br />'
451
-                ),
452
-                __FILE__,
453
-                __FUNCTION__,
454
-                __LINE__
455
-            );
456
-        }
457
-        return $success;
458
-    }
459
-
460
-
461
-    /**
462
-     * see parent for definition
463
-     *
464
-     * @return string html body of the message content and the related css.
465
-     * @throws EE_Error
466
-     * @throws \TijsVerkoyen\CssToInlineStyles\Exception
467
-     */
468
-    protected function _preview()
469
-    {
470
-        return $this->_body(true);
471
-    }
472
-
473
-
474
-    /**
475
-     * Setup headers for email
476
-     *
477
-     * @access protected
478
-     * @return string formatted header for email
479
-     */
480
-    protected function _headers()
481
-    {
482
-        $this->_ensure_has_from_email_address();
483
-        $from    = $this->_from;
484
-        $headers = array(
485
-            'From:' . $from,
486
-            'Reply-To:' . $from,
487
-            'Content-Type:text/html; charset=utf-8',
488
-        );
489
-
490
-        /**
491
-         * Second condition added as a result of https://events.codebasehq.com/projects/event-espresso/tickets/11416 to
492
-         * cover back compat where there may be users who have saved cc values in their db for the newsletter message
493
-         * type which they are no longer able to change.
494
-         */
495
-        if (! empty($this->_cc) && ! $this->_incoming_message_type instanceof EE_Newsletter_message_type) {
496
-            $headers[] = 'cc: ' . $this->_cc;
497
-        }
498
-
499
-        // but wait!  Header's for the from is NOT reliable because some plugins don't respect From: as set in the
500
-        // header.
501
-        add_filter('wp_mail_from', array($this, 'set_from_address'), 100);
502
-        add_filter('wp_mail_from_name', array($this, 'set_from_name'), 100);
503
-        return apply_filters('FHEE__EE_Email_messenger___headers', $headers, $this->_incoming_message_type, $this);
504
-    }
505
-
506
-
507
-    /**
508
-     * This simply ensures that the from address is not empty.  If it is, then we use whatever is set as the site email
509
-     * address for the from address to avoid problems with sending emails.
510
-     */
511
-    protected function _ensure_has_from_email_address()
512
-    {
513
-        if (empty($this->_from)) {
514
-            $this->_from = get_bloginfo('admin_email');
515
-        }
516
-    }
517
-
518
-
519
-    /**
520
-     * This simply parses whatever is set as the $_from address and determines if it is in the format {name} <{email}>
521
-     * or just {email} and returns an array with the "from_name" and "from_email" as the values. Note from_name *MAY*
522
-     * be empty
523
-     *
524
-     * @since 4.3.1
525
-     * @return array
526
-     */
527
-    private function _parse_from()
528
-    {
529
-        if (strpos($this->_from, '<') !== false) {
530
-            $from_name = substr($this->_from, 0, strpos($this->_from, '<') - 1);
531
-            $from_name = str_replace('"', '', $from_name);
532
-            $from_name = trim($from_name);
533
-
534
-            $from_email = substr($this->_from, strpos($this->_from, '<') + 1);
535
-            $from_email = str_replace('>', '', $from_email);
536
-            $from_email = trim($from_email);
537
-        } elseif (trim($this->_from) !== '') {
538
-            $from_name  = '';
539
-            $from_email = trim($this->_from);
540
-        } else {
541
-            $from_name = $from_email = '';
542
-        }
543
-        return array($from_name, $from_email);
544
-    }
545
-
546
-
547
-    /**
548
-     * Callback for the wp_mail_from filter.
549
-     *
550
-     * @since 4.3.1
551
-     * @param string $from_email What the original from_email is.
552
-     * @return string
553
-     */
554
-    public function set_from_address($from_email)
555
-    {
556
-        $parsed_from = $this->_parse_from();
557
-        // includes fallback if the parsing failed.
558
-        $from_email = is_array($parsed_from) && ! empty($parsed_from[1])
559
-            ? $parsed_from[1]
560
-            : get_bloginfo('admin_email');
561
-        return $from_email;
562
-    }
563
-
564
-
565
-    /**
566
-     * Callback fro the wp_mail_from_name filter.
567
-     *
568
-     * @since 4.3.1
569
-     * @param string $from_name The original from_name.
570
-     * @return string
571
-     */
572
-    public function set_from_name($from_name)
573
-    {
574
-        $parsed_from = $this->_parse_from();
575
-        if (is_array($parsed_from) && ! empty($parsed_from[0])) {
576
-            $from_name = $parsed_from[0];
577
-        }
578
-
579
-        // if from name is "WordPress" let's sub in the site name instead (more friendly!)
580
-        // but realize the default name is HTML entity-encoded
581
-        $from_name = $from_name == 'WordPress' ? wp_specialchars_decode(get_bloginfo(), ENT_QUOTES) : $from_name;
582
-
583
-        return $from_name;
584
-    }
585
-
586
-
587
-    /**
588
-     * setup body for email
589
-     *
590
-     * @param bool $preview will determine whether this is preview template or not.
591
-     * @return string formatted body for email.
592
-     * @throws EE_Error
593
-     * @throws \TijsVerkoyen\CssToInlineStyles\Exception
594
-     */
595
-    protected function _body($preview = false)
596
-    {
597
-        // setup template args!
598
-        $this->_template_args = array(
599
-            'subject'   => $this->_subject,
600
-            'from'      => $this->_from,
601
-            'main_body' => wpautop($this->_content),
602
-        );
603
-        $body                 = $this->_get_main_template($preview);
604
-
605
-        /**
606
-         * This filter allows one to bypass the CSSToInlineStyles tool and leave the body untouched.
607
-         *
608
-         * @type    bool $preview Indicates whether a preview is being generated or not.
609
-         * @return  bool    true  indicates to use the inliner, false bypasses it.
610
-         */
611
-        if (apply_filters('FHEE__EE_Email_messenger__apply_CSSInliner ', true, $preview)) {
612
-            // require CssToInlineStyles library and its dependencies via composer autoloader
613
-            require_once EE_THIRD_PARTY . 'cssinliner/vendor/autoload.php';
614
-
615
-            // now if this isn't a preview, let's setup the body so it has inline styles
616
-            if (! $preview || ($preview && defined('DOING_AJAX'))) {
617
-                $style = file_get_contents(
618
-                    $this->get_variation(
619
-                        $this->_tmp_pack,
620
-                        $this->_incoming_message_type->name,
621
-                        false,
622
-                        'main',
623
-                        $this->_variation
624
-                    ),
625
-                    true
626
-                );
627
-                $CSS   = new TijsVerkoyen\CssToInlineStyles\CssToInlineStyles($body, $style);
628
-                // for some reason the library has a bracket and new line at the beginning.  This takes care of that.
629
-                $body  = ltrim($CSS->convert(true), ">\n");
630
-                // see https://events.codebasehq.com/projects/event-espresso/tickets/8609
631
-                $body  = ltrim($body, "<?");
632
-            }
633
-        }
634
-        return $body;
635
-    }
636
-
637
-
638
-    /**
639
-     * This just returns any existing test settings that might be saved in the database
640
-     *
641
-     * @access public
642
-     * @return array
643
-     */
644
-    public function get_existing_test_settings()
645
-    {
646
-        $settings = parent::get_existing_test_settings();
647
-        // override subject if present because we always want it to be fresh.
648
-        if (is_array($settings) && ! empty($settings['subject'])) {
649
-            $settings['subject'] = sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name'));
650
-        }
651
-        return $settings;
652
-    }
9
+	/**
10
+	 * To field for email
11
+	 * @var string
12
+	 */
13
+	protected $_to = '';
14
+
15
+
16
+	/**
17
+	 * CC field for email.
18
+	 * @var string
19
+	 */
20
+	protected $_cc = '';
21
+
22
+	/**
23
+	 * From field for email
24
+	 * @var string
25
+	 */
26
+	protected $_from = '';
27
+
28
+
29
+	/**
30
+	 * Subject field for email
31
+	 * @var string
32
+	 */
33
+	protected $_subject = '';
34
+
35
+
36
+	/**
37
+	 * Content field for email
38
+	 * @var string
39
+	 */
40
+	protected $_content = '';
41
+
42
+
43
+	/**
44
+	 * constructor
45
+	 *
46
+	 * @access public
47
+	 */
48
+	public function __construct()
49
+	{
50
+		// set name and description properties
51
+		$this->name                = 'email';
52
+		$this->description         = sprintf(
53
+			esc_html__(
54
+				'This messenger delivers messages via email using the built-in %s function included with WordPress',
55
+				'event_espresso'
56
+			),
57
+			'<code>wp_mail</code>'
58
+		);
59
+		$this->label               = array(
60
+			'singular' => esc_html__('email', 'event_espresso'),
61
+			'plural'   => esc_html__('emails', 'event_espresso'),
62
+		);
63
+		$this->activate_on_install = true;
64
+
65
+		// we're using defaults so let's call parent constructor that will take care of setting up all the other
66
+		// properties
67
+		parent::__construct();
68
+	}
69
+
70
+
71
+	/**
72
+	 * see abstract declaration in parent class for details.
73
+	 */
74
+	protected function _set_admin_pages()
75
+	{
76
+		$this->admin_registered_pages = array(
77
+			'events_edit' => true,
78
+		);
79
+	}
80
+
81
+
82
+	/**
83
+	 * see abstract declaration in parent class for details
84
+	 */
85
+	protected function _set_valid_shortcodes()
86
+	{
87
+		// remember by leaving the other fields not set, those fields will inherit the valid shortcodes from the
88
+		// message type.
89
+		$this->_valid_shortcodes = array(
90
+			'to'   => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
91
+			'cc' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
92
+			'from' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
93
+		);
94
+	}
95
+
96
+
97
+	/**
98
+	 * see abstract declaration in parent class for details
99
+	 *
100
+	 * @access protected
101
+	 * @return void
102
+	 */
103
+	protected function _set_validator_config()
104
+	{
105
+		$valid_shortcodes = $this->get_valid_shortcodes();
106
+
107
+		$this->_validator_config = array(
108
+			'to'            => array(
109
+				'shortcodes' => $valid_shortcodes['to'],
110
+				'type'       => 'email',
111
+			),
112
+			'cc' => array(
113
+				'shortcodes' => $valid_shortcodes['to'],
114
+				'type' => 'email',
115
+			),
116
+			'from'          => array(
117
+				'shortcodes' => $valid_shortcodes['from'],
118
+				'type'       => 'email',
119
+			),
120
+			'subject'       => array(
121
+				'shortcodes' => array(
122
+					'organization',
123
+					'primary_registration_details',
124
+					'event_author',
125
+					'primary_registration_details',
126
+					'recipient_details',
127
+				),
128
+			),
129
+			'content'       => array(
130
+				'shortcodes' => array(
131
+					'event_list',
132
+					'attendee_list',
133
+					'ticket_list',
134
+					'organization',
135
+					'primary_registration_details',
136
+					'primary_registration_list',
137
+					'event_author',
138
+					'recipient_details',
139
+					'recipient_list',
140
+					'transaction',
141
+					'messenger',
142
+				),
143
+			),
144
+			'attendee_list' => array(
145
+				'shortcodes' => array('attendee', 'event_list', 'ticket_list'),
146
+				'required'   => array('[ATTENDEE_LIST]'),
147
+			),
148
+			'event_list'    => array(
149
+				'shortcodes' => array(
150
+					'event',
151
+					'attendee_list',
152
+					'ticket_list',
153
+					'venue',
154
+					'datetime_list',
155
+					'attendee',
156
+					'primary_registration_details',
157
+					'primary_registration_list',
158
+					'event_author',
159
+					'recipient_details',
160
+					'recipient_list',
161
+				),
162
+				'required'   => array('[EVENT_LIST]'),
163
+			),
164
+			'ticket_list'   => array(
165
+				'shortcodes' => array(
166
+					'event_list',
167
+					'attendee_list',
168
+					'ticket',
169
+					'datetime_list',
170
+					'primary_registration_details',
171
+					'recipient_details',
172
+				),
173
+				'required'   => array('[TICKET_LIST]'),
174
+			),
175
+			'datetime_list' => array(
176
+				'shortcodes' => array('datetime'),
177
+				'required'   => array('[DATETIME_LIST]'),
178
+			),
179
+		);
180
+	}
181
+
182
+
183
+	/**
184
+	 * @see   parent EE_messenger class for docs
185
+	 * @since 4.5.0
186
+	 */
187
+	public function do_secondary_messenger_hooks($sending_messenger_name)
188
+	{
189
+		if ($sending_messenger_name = 'html') {
190
+			add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
191
+		}
192
+	}
193
+
194
+
195
+	public function add_email_css(
196
+		$variation_path,
197
+		$messenger,
198
+		$message_type,
199
+		$type,
200
+		$variation,
201
+		$file_extension,
202
+		$url,
203
+		EE_Messages_Template_Pack $template_pack
204
+	) {
205
+		// prevent recursion on this callback.
206
+		remove_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10);
207
+		$variation = $this->get_variation($template_pack, $message_type, $url, 'main', $variation, false);
208
+
209
+		add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
210
+		return $variation;
211
+	}
212
+
213
+
214
+	/**
215
+	 * See parent for details
216
+	 *
217
+	 * @access protected
218
+	 * @return void
219
+	 */
220
+	protected function _set_test_settings_fields()
221
+	{
222
+		$this->_test_settings_fields = array(
223
+			'to'      => array(
224
+				'input'      => 'text',
225
+				'label'      => esc_html__('Send a test email to', 'event_espresso'),
226
+				'type'       => 'email',
227
+				'required'   => true,
228
+				'validation' => true,
229
+				'css_class'  => 'large-text',
230
+				'format'     => '%s',
231
+				'default'    => get_bloginfo('admin_email'),
232
+			),
233
+			'subject' => array(
234
+				'input'      => 'hidden',
235
+				'label'      => '',
236
+				'type'       => 'string',
237
+				'required'   => false,
238
+				'validation' => false,
239
+				'format'     => '%s',
240
+				'value'      => sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name')),
241
+				'default'    => '',
242
+				'css_class'  => '',
243
+			),
244
+		);
245
+	}
246
+
247
+
248
+	/**
249
+	 * _set_template_fields
250
+	 * This sets up the fields that a messenger requires for the message to go out.
251
+	 *
252
+	 * @access  protected
253
+	 * @return void
254
+	 */
255
+	protected function _set_template_fields()
256
+	{
257
+		// any extra template fields that are NOT used by the messenger but will get used by a messenger field for
258
+		// shortcode replacement get added to the 'extra' key in an associated array indexed by the messenger field
259
+		// they relate to.  This is important for the Messages_admin to know what fields to display to the user.
260
+		//  Also, notice that the "values" are equal to the field type that messages admin will use to know what
261
+		// kind of field to display. The values ALSO have one index labeled "shortcode".  the values in that array
262
+		// indicate which ACTUAL SHORTCODE (i.e. [SHORTCODE]) is required in order for this extra field to be
263
+		// displayed.  If the required shortcode isn't part of the shortcodes array then the field is not needed and
264
+		// will not be displayed/parsed.
265
+		$this->_template_fields = array(
266
+			'to'      => array(
267
+				'input'      => 'text',
268
+				'label'      => esc_html_x(
269
+					'To',
270
+					'Label for the "To" field for email addresses',
271
+					'event_espresso'
272
+				),
273
+				'type'       => 'string',
274
+				'required'   => true,
275
+				'validation' => true,
276
+				'css_class'  => 'large-text',
277
+				'format'     => '%s',
278
+			),
279
+			'cc'      => array(
280
+				'input'      => 'text',
281
+				'label'      => esc_html_x(
282
+					'CC',
283
+					'Label for the "Carbon Copy" field used for additional email addresses',
284
+					'event_espresso'
285
+				),
286
+				'type'       => 'string',
287
+				'required'   => false,
288
+				'validation' => true,
289
+				'css_class'  => 'large-text',
290
+				'format'     => '%s',
291
+			),
292
+			'from'    => array(
293
+				'input'      => 'text',
294
+				'label'      => esc_html_x(
295
+					'From',
296
+					'Label for the "From" field for email addresses.',
297
+					'event_espresso'
298
+				),
299
+				'type'       => 'string',
300
+				'required'   => true,
301
+				'validation' => true,
302
+				'css_class'  => 'large-text',
303
+				'format'     => '%s',
304
+			),
305
+			'subject' => array(
306
+				'input'      => 'text',
307
+				'label'      => esc_html_x(
308
+					'Subject',
309
+					'Label for the "Subject" field (short description of contents) for emails.',
310
+					'event_espresso'
311
+				),
312
+				'type'       => 'string',
313
+				'required'   => true,
314
+				'validation' => true,
315
+				'css_class'  => 'large-text',
316
+				'format'     => '%s',
317
+			),
318
+			'content' => '',
319
+			// left empty b/c it is in the "extra array" but messenger still needs needs to know this is a field.
320
+			'extra'   => array(
321
+				'content' => array(
322
+					'main'          => array(
323
+						'input'      => 'wp_editor',
324
+						'label'      => esc_html__('Main Content', 'event_espresso'),
325
+						'type'       => 'string',
326
+						'required'   => true,
327
+						'validation' => true,
328
+						'format'     => '%s',
329
+						'rows'       => '15',
330
+					),
331
+					'event_list'    => array(
332
+						'input'               => 'wp_editor',
333
+						'label'               => '[EVENT_LIST]',
334
+						'type'                => 'string',
335
+						'required'            => true,
336
+						'validation'          => true,
337
+						'format'              => '%s',
338
+						'rows'                => '15',
339
+						'shortcodes_required' => array('[EVENT_LIST]'),
340
+					),
341
+					'attendee_list' => array(
342
+						'input'               => 'textarea',
343
+						'label'               => '[ATTENDEE_LIST]',
344
+						'type'                => 'string',
345
+						'required'            => true,
346
+						'validation'          => true,
347
+						'format'              => '%s',
348
+						'css_class'           => 'large-text',
349
+						'rows'                => '5',
350
+						'shortcodes_required' => array('[ATTENDEE_LIST]'),
351
+					),
352
+					'ticket_list'   => array(
353
+						'input'               => 'textarea',
354
+						'label'               => '[TICKET_LIST]',
355
+						'type'                => 'string',
356
+						'required'            => true,
357
+						'validation'          => true,
358
+						'format'              => '%s',
359
+						'css_class'           => 'large-text',
360
+						'rows'                => '10',
361
+						'shortcodes_required' => array('[TICKET_LIST]'),
362
+					),
363
+					'datetime_list' => array(
364
+						'input'               => 'textarea',
365
+						'label'               => '[DATETIME_LIST]',
366
+						'type'                => 'string',
367
+						'required'            => true,
368
+						'validation'          => true,
369
+						'format'              => '%s',
370
+						'css_class'           => 'large-text',
371
+						'rows'                => '10',
372
+						'shortcodes_required' => array('[DATETIME_LIST]'),
373
+					),
374
+				),
375
+			),
376
+		);
377
+	}
378
+
379
+
380
+	/**
381
+	 * See definition of this class in parent
382
+	 */
383
+	protected function _set_default_message_types()
384
+	{
385
+		$this->_default_message_types = array(
386
+			'payment',
387
+			'payment_refund',
388
+			'registration',
389
+			'not_approved_registration',
390
+			'pending_approval',
391
+		);
392
+	}
393
+
394
+
395
+	/**
396
+	 * @see   definition of this class in parent
397
+	 * @since 4.5.0
398
+	 */
399
+	protected function _set_valid_message_types()
400
+	{
401
+		$this->_valid_message_types = array(
402
+			'payment',
403
+			'registration',
404
+			'not_approved_registration',
405
+			'declined_registration',
406
+			'cancelled_registration',
407
+			'pending_approval',
408
+			'registration_summary',
409
+			'payment_reminder',
410
+			'payment_declined',
411
+			'payment_refund',
412
+		);
413
+	}
414
+
415
+
416
+	/**
417
+	 * setting up admin_settings_fields for messenger.
418
+	 */
419
+	protected function _set_admin_settings_fields()
420
+	{
421
+	}
422
+
423
+	/**
424
+	 * We just deliver the messages don't kill us!!
425
+	 *
426
+	 * @return bool|WP_Error true if message delivered, false if it didn't deliver OR bubble up any error object if
427
+	 *              present.
428
+	 * @throws EE_Error
429
+	 * @throws \TijsVerkoyen\CssToInlineStyles\Exception
430
+	 */
431
+	protected function _send_message()
432
+	{
433
+		$success = wp_mail(
434
+			$this->_to,
435
+			// some old values for subject may be expecting HTML entities to be decoded in the subject
436
+			// and subjects aren't interpreted as HTML, so there should be no HTML in them
437
+			wp_strip_all_tags(wp_specialchars_decode($this->_subject, ENT_QUOTES)),
438
+			$this->_body(),
439
+			$this->_headers()
440
+		);
441
+		if (! $success) {
442
+			EE_Error::add_error(
443
+				sprintf(
444
+					esc_html__(
445
+						'The email did not send successfully.%3$sThe WordPress wp_mail function is used for sending mails but does not give any useful information when an email fails to send.%3$sIt is possible the "to" address (%1$s) or "from" address (%2$s) is invalid.%3$s',
446
+						'event_espresso'
447
+					),
448
+					$this->_to,
449
+					$this->_from,
450
+					'<br />'
451
+				),
452
+				__FILE__,
453
+				__FUNCTION__,
454
+				__LINE__
455
+			);
456
+		}
457
+		return $success;
458
+	}
459
+
460
+
461
+	/**
462
+	 * see parent for definition
463
+	 *
464
+	 * @return string html body of the message content and the related css.
465
+	 * @throws EE_Error
466
+	 * @throws \TijsVerkoyen\CssToInlineStyles\Exception
467
+	 */
468
+	protected function _preview()
469
+	{
470
+		return $this->_body(true);
471
+	}
472
+
473
+
474
+	/**
475
+	 * Setup headers for email
476
+	 *
477
+	 * @access protected
478
+	 * @return string formatted header for email
479
+	 */
480
+	protected function _headers()
481
+	{
482
+		$this->_ensure_has_from_email_address();
483
+		$from    = $this->_from;
484
+		$headers = array(
485
+			'From:' . $from,
486
+			'Reply-To:' . $from,
487
+			'Content-Type:text/html; charset=utf-8',
488
+		);
489
+
490
+		/**
491
+		 * Second condition added as a result of https://events.codebasehq.com/projects/event-espresso/tickets/11416 to
492
+		 * cover back compat where there may be users who have saved cc values in their db for the newsletter message
493
+		 * type which they are no longer able to change.
494
+		 */
495
+		if (! empty($this->_cc) && ! $this->_incoming_message_type instanceof EE_Newsletter_message_type) {
496
+			$headers[] = 'cc: ' . $this->_cc;
497
+		}
498
+
499
+		// but wait!  Header's for the from is NOT reliable because some plugins don't respect From: as set in the
500
+		// header.
501
+		add_filter('wp_mail_from', array($this, 'set_from_address'), 100);
502
+		add_filter('wp_mail_from_name', array($this, 'set_from_name'), 100);
503
+		return apply_filters('FHEE__EE_Email_messenger___headers', $headers, $this->_incoming_message_type, $this);
504
+	}
505
+
506
+
507
+	/**
508
+	 * This simply ensures that the from address is not empty.  If it is, then we use whatever is set as the site email
509
+	 * address for the from address to avoid problems with sending emails.
510
+	 */
511
+	protected function _ensure_has_from_email_address()
512
+	{
513
+		if (empty($this->_from)) {
514
+			$this->_from = get_bloginfo('admin_email');
515
+		}
516
+	}
517
+
518
+
519
+	/**
520
+	 * This simply parses whatever is set as the $_from address and determines if it is in the format {name} <{email}>
521
+	 * or just {email} and returns an array with the "from_name" and "from_email" as the values. Note from_name *MAY*
522
+	 * be empty
523
+	 *
524
+	 * @since 4.3.1
525
+	 * @return array
526
+	 */
527
+	private function _parse_from()
528
+	{
529
+		if (strpos($this->_from, '<') !== false) {
530
+			$from_name = substr($this->_from, 0, strpos($this->_from, '<') - 1);
531
+			$from_name = str_replace('"', '', $from_name);
532
+			$from_name = trim($from_name);
533
+
534
+			$from_email = substr($this->_from, strpos($this->_from, '<') + 1);
535
+			$from_email = str_replace('>', '', $from_email);
536
+			$from_email = trim($from_email);
537
+		} elseif (trim($this->_from) !== '') {
538
+			$from_name  = '';
539
+			$from_email = trim($this->_from);
540
+		} else {
541
+			$from_name = $from_email = '';
542
+		}
543
+		return array($from_name, $from_email);
544
+	}
545
+
546
+
547
+	/**
548
+	 * Callback for the wp_mail_from filter.
549
+	 *
550
+	 * @since 4.3.1
551
+	 * @param string $from_email What the original from_email is.
552
+	 * @return string
553
+	 */
554
+	public function set_from_address($from_email)
555
+	{
556
+		$parsed_from = $this->_parse_from();
557
+		// includes fallback if the parsing failed.
558
+		$from_email = is_array($parsed_from) && ! empty($parsed_from[1])
559
+			? $parsed_from[1]
560
+			: get_bloginfo('admin_email');
561
+		return $from_email;
562
+	}
563
+
564
+
565
+	/**
566
+	 * Callback fro the wp_mail_from_name filter.
567
+	 *
568
+	 * @since 4.3.1
569
+	 * @param string $from_name The original from_name.
570
+	 * @return string
571
+	 */
572
+	public function set_from_name($from_name)
573
+	{
574
+		$parsed_from = $this->_parse_from();
575
+		if (is_array($parsed_from) && ! empty($parsed_from[0])) {
576
+			$from_name = $parsed_from[0];
577
+		}
578
+
579
+		// if from name is "WordPress" let's sub in the site name instead (more friendly!)
580
+		// but realize the default name is HTML entity-encoded
581
+		$from_name = $from_name == 'WordPress' ? wp_specialchars_decode(get_bloginfo(), ENT_QUOTES) : $from_name;
582
+
583
+		return $from_name;
584
+	}
585
+
586
+
587
+	/**
588
+	 * setup body for email
589
+	 *
590
+	 * @param bool $preview will determine whether this is preview template or not.
591
+	 * @return string formatted body for email.
592
+	 * @throws EE_Error
593
+	 * @throws \TijsVerkoyen\CssToInlineStyles\Exception
594
+	 */
595
+	protected function _body($preview = false)
596
+	{
597
+		// setup template args!
598
+		$this->_template_args = array(
599
+			'subject'   => $this->_subject,
600
+			'from'      => $this->_from,
601
+			'main_body' => wpautop($this->_content),
602
+		);
603
+		$body                 = $this->_get_main_template($preview);
604
+
605
+		/**
606
+		 * This filter allows one to bypass the CSSToInlineStyles tool and leave the body untouched.
607
+		 *
608
+		 * @type    bool $preview Indicates whether a preview is being generated or not.
609
+		 * @return  bool    true  indicates to use the inliner, false bypasses it.
610
+		 */
611
+		if (apply_filters('FHEE__EE_Email_messenger__apply_CSSInliner ', true, $preview)) {
612
+			// require CssToInlineStyles library and its dependencies via composer autoloader
613
+			require_once EE_THIRD_PARTY . 'cssinliner/vendor/autoload.php';
614
+
615
+			// now if this isn't a preview, let's setup the body so it has inline styles
616
+			if (! $preview || ($preview && defined('DOING_AJAX'))) {
617
+				$style = file_get_contents(
618
+					$this->get_variation(
619
+						$this->_tmp_pack,
620
+						$this->_incoming_message_type->name,
621
+						false,
622
+						'main',
623
+						$this->_variation
624
+					),
625
+					true
626
+				);
627
+				$CSS   = new TijsVerkoyen\CssToInlineStyles\CssToInlineStyles($body, $style);
628
+				// for some reason the library has a bracket and new line at the beginning.  This takes care of that.
629
+				$body  = ltrim($CSS->convert(true), ">\n");
630
+				// see https://events.codebasehq.com/projects/event-espresso/tickets/8609
631
+				$body  = ltrim($body, "<?");
632
+			}
633
+		}
634
+		return $body;
635
+	}
636
+
637
+
638
+	/**
639
+	 * This just returns any existing test settings that might be saved in the database
640
+	 *
641
+	 * @access public
642
+	 * @return array
643
+	 */
644
+	public function get_existing_test_settings()
645
+	{
646
+		$settings = parent::get_existing_test_settings();
647
+		// override subject if present because we always want it to be fresh.
648
+		if (is_array($settings) && ! empty($settings['subject'])) {
649
+			$settings['subject'] = sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name'));
650
+		}
651
+		return $settings;
652
+	}
653 653
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
             ),
57 57
             '<code>wp_mail</code>'
58 58
         );
59
-        $this->label               = array(
59
+        $this->label = array(
60 60
             'singular' => esc_html__('email', 'event_espresso'),
61 61
             'plural'   => esc_html__('emails', 'event_espresso'),
62 62
         );
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
             $this->_body(),
439 439
             $this->_headers()
440 440
         );
441
-        if (! $success) {
441
+        if ( ! $success) {
442 442
             EE_Error::add_error(
443 443
                 sprintf(
444 444
                     esc_html__(
@@ -482,8 +482,8 @@  discard block
 block discarded – undo
482 482
         $this->_ensure_has_from_email_address();
483 483
         $from    = $this->_from;
484 484
         $headers = array(
485
-            'From:' . $from,
486
-            'Reply-To:' . $from,
485
+            'From:'.$from,
486
+            'Reply-To:'.$from,
487 487
             'Content-Type:text/html; charset=utf-8',
488 488
         );
489 489
 
@@ -492,8 +492,8 @@  discard block
 block discarded – undo
492 492
          * cover back compat where there may be users who have saved cc values in their db for the newsletter message
493 493
          * type which they are no longer able to change.
494 494
          */
495
-        if (! empty($this->_cc) && ! $this->_incoming_message_type instanceof EE_Newsletter_message_type) {
496
-            $headers[] = 'cc: ' . $this->_cc;
495
+        if ( ! empty($this->_cc) && ! $this->_incoming_message_type instanceof EE_Newsletter_message_type) {
496
+            $headers[] = 'cc: '.$this->_cc;
497 497
         }
498 498
 
499 499
         // but wait!  Header's for the from is NOT reliable because some plugins don't respect From: as set in the
@@ -600,7 +600,7 @@  discard block
 block discarded – undo
600 600
             'from'      => $this->_from,
601 601
             'main_body' => wpautop($this->_content),
602 602
         );
603
-        $body                 = $this->_get_main_template($preview);
603
+        $body = $this->_get_main_template($preview);
604 604
 
605 605
         /**
606 606
          * This filter allows one to bypass the CSSToInlineStyles tool and leave the body untouched.
@@ -610,10 +610,10 @@  discard block
 block discarded – undo
610 610
          */
611 611
         if (apply_filters('FHEE__EE_Email_messenger__apply_CSSInliner ', true, $preview)) {
612 612
             // require CssToInlineStyles library and its dependencies via composer autoloader
613
-            require_once EE_THIRD_PARTY . 'cssinliner/vendor/autoload.php';
613
+            require_once EE_THIRD_PARTY.'cssinliner/vendor/autoload.php';
614 614
 
615 615
             // now if this isn't a preview, let's setup the body so it has inline styles
616
-            if (! $preview || ($preview && defined('DOING_AJAX'))) {
616
+            if ( ! $preview || ($preview && defined('DOING_AJAX'))) {
617 617
                 $style = file_get_contents(
618 618
                     $this->get_variation(
619 619
                         $this->_tmp_pack,
Please login to merge, or discard this patch.
core/domain/services/event/EventSpacesCalculator.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -164,7 +164,7 @@
 block discarded – undo
164 164
 
165 165
 
166 166
     /**
167
-     * @param $ticket
167
+     * @param \EE_Base_Class $ticket
168 168
      * @throws DomainException
169 169
      * @throws EE_Error
170 170
      * @throws UnexpectedEntityException
Please login to merge, or discard this patch.
Indentation   +698 added lines, -698 removed lines patch added patch discarded remove patch
@@ -26,702 +26,702 @@
 block discarded – undo
26 26
 class EventSpacesCalculator
27 27
 {
28 28
 
29
-    /**
30
-     * @var EE_Event $event
31
-     */
32
-    private $event;
33
-
34
-    /**
35
-     * @var array $datetime_query_params
36
-     */
37
-    private $datetime_query_params;
38
-
39
-    /**
40
-     * @var EE_Ticket[] $active_tickets
41
-     */
42
-    private $active_tickets = array();
43
-
44
-    /**
45
-     * @var EE_Datetime[] $datetimes
46
-     */
47
-    private $datetimes = array();
48
-
49
-    /**
50
-     * Array of Ticket IDs grouped by Datetime
51
-     *
52
-     * @var array $datetimes
53
-     */
54
-    private $datetime_tickets = array();
55
-
56
-    /**
57
-     * Max spaces for each Datetime (reg limit - previous sold)
58
-     *
59
-     * @var array $datetime_spaces
60
-     */
61
-    private $datetime_spaces = array();
62
-
63
-    /**
64
-     * Array of Datetime IDs grouped by Ticket
65
-     *
66
-     * @var array[] $ticket_datetimes
67
-     */
68
-    private $ticket_datetimes = array();
69
-
70
-    /**
71
-     * maximum ticket quantities for each ticket (adjusted for reg limit)
72
-     *
73
-     * @var array $ticket_quantities
74
-     */
75
-    private $ticket_quantities = array();
76
-
77
-    /**
78
-     * total quantity of sold and reserved for each ticket
79
-     *
80
-     * @var array $tickets_sold
81
-     */
82
-    private $tickets_sold = array();
83
-
84
-    /**
85
-     * total spaces available across all datetimes
86
-     *
87
-     * @var array $total_spaces
88
-     */
89
-    private $total_spaces = array();
90
-
91
-    /**
92
-     * @var boolean $debug
93
-     */
94
-    private $debug = false; // true false
95
-
96
-    /**
97
-     * @var null|int $spaces_remaining
98
-     */
99
-    private $spaces_remaining;
100
-
101
-    /**
102
-     * @var null|int $total_spaces_available
103
-     */
104
-    private $total_spaces_available;
105
-
106
-
107
-    /**
108
-     * EventSpacesCalculator constructor.
109
-     *
110
-     * @param EE_Event $event
111
-     * @param array    $datetime_query_params
112
-     * @throws EE_Error
113
-     */
114
-    public function __construct(EE_Event $event, array $datetime_query_params = array())
115
-    {
116
-        $this->event = $event;
117
-        $this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
118
-        $this->setHooks();
119
-    }
120
-
121
-
122
-    /**
123
-     * @return void
124
-     */
125
-    private function setHooks()
126
-    {
127
-        add_action('AHEE__EE_Ticket__increase_sold', array($this, 'clearResults'));
128
-        add_action('AHEE__EE_Ticket__decrease_sold', array($this, 'clearResults'));
129
-        add_action('AHEE__EE_Datetime__increase_sold', array($this, 'clearResults'));
130
-        add_action('AHEE__EE_Datetime__decrease_sold', array($this, 'clearResults'));
131
-        add_action('AHEE__EE_Ticket__increase_reserved', array($this, 'clearResults'));
132
-        add_action('AHEE__EE_Ticket__decrease_reserved', array($this, 'clearResults'));
133
-        add_action('AHEE__EE_Datetime__increase_reserved', array($this, 'clearResults'));
134
-        add_action('AHEE__EE_Datetime__decrease_reserved', array($this, 'clearResults'));
135
-    }
136
-
137
-
138
-    /**
139
-     * @return void
140
-     */
141
-    public function clearResults()
142
-    {
143
-        $this->spaces_remaining = null;
144
-        $this->total_spaces_available = null;
145
-    }
146
-
147
-
148
-    /**
149
-     * @return EE_Ticket[]
150
-     * @throws EE_Error
151
-     * @throws InvalidDataTypeException
152
-     * @throws InvalidInterfaceException
153
-     * @throws InvalidArgumentException
154
-     */
155
-    public function getActiveTickets()
156
-    {
157
-        if (empty($this->active_tickets)) {
158
-            $this->active_tickets = $this->event->tickets(
159
-                array(
160
-                    array('TKT_deleted' => false),
161
-                    'order_by' => array('TKT_qty' => 'ASC'),
162
-                )
163
-            );
164
-        }
165
-        return $this->active_tickets;
166
-    }
167
-
168
-
169
-    /**
170
-     * @param EE_Ticket[] $active_tickets
171
-     * @throws EE_Error
172
-     * @throws DomainException
173
-     * @throws UnexpectedEntityException
174
-     */
175
-    public function setActiveTickets(array $active_tickets = array())
176
-    {
177
-        if (! empty($active_tickets)) {
178
-            foreach ($active_tickets as $active_ticket) {
179
-                $this->validateTicket($active_ticket);
180
-            }
181
-            // sort incoming array by ticket quantity (asc)
182
-            usort(
183
-                $active_tickets,
184
-                function (EE_Ticket $a, EE_Ticket $b) {
185
-                    if ($a->qty() === $b->qty()) {
186
-                        return 0;
187
-                    }
188
-                    return ($a->qty() < $b->qty())
189
-                        ? -1
190
-                        : 1;
191
-                }
192
-            );
193
-        }
194
-        $this->active_tickets = $active_tickets;
195
-    }
196
-
197
-
198
-    /**
199
-     * @param $ticket
200
-     * @throws DomainException
201
-     * @throws EE_Error
202
-     * @throws UnexpectedEntityException
203
-     */
204
-    private function validateTicket($ticket)
205
-    {
206
-        if (! $ticket instanceof EE_Ticket) {
207
-            throw new DomainException(
208
-                esc_html__(
209
-                    'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
210
-                    'event_espresso'
211
-                )
212
-            );
213
-        }
214
-        if ($ticket->get_event_ID() !== $this->event->ID()) {
215
-            throw new DomainException(
216
-                sprintf(
217
-                    esc_html__(
218
-                        'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
219
-                        'event_espresso'
220
-                    ),
221
-                    $ticket->get_event_ID(),
222
-                    $this->event->ID()
223
-                )
224
-            );
225
-        }
226
-    }
227
-
228
-
229
-    /**
230
-     * @return EE_Datetime[]
231
-     */
232
-    public function getDatetimes()
233
-    {
234
-        return $this->datetimes;
235
-    }
236
-
237
-
238
-    /**
239
-     * @param EE_Datetime $datetime
240
-     * @throws EE_Error
241
-     * @throws DomainException
242
-     */
243
-    public function setDatetime(EE_Datetime $datetime)
244
-    {
245
-        if ($datetime->event()->ID() !== $this->event->ID()) {
246
-            throw new DomainException(
247
-                sprintf(
248
-                    esc_html__(
249
-                        'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
250
-                        'event_espresso'
251
-                    ),
252
-                    $datetime->event()->ID(),
253
-                    $this->event->ID()
254
-                )
255
-            );
256
-        }
257
-        $this->datetimes[ $datetime->ID() ] = $datetime;
258
-    }
259
-
260
-
261
-    /**
262
-     * calculate spaces remaining based on "saleable" tickets
263
-     *
264
-     * @return float|int
265
-     * @throws EE_Error
266
-     * @throws DomainException
267
-     * @throws UnexpectedEntityException
268
-     * @throws InvalidDataTypeException
269
-     * @throws InvalidInterfaceException
270
-     * @throws InvalidArgumentException
271
-     */
272
-    public function spacesRemaining()
273
-    {
274
-        if ($this->spaces_remaining === null) {
275
-            $this->initialize();
276
-            $this->spaces_remaining = $this->calculate();
277
-        }
278
-        return $this->spaces_remaining;
279
-    }
280
-
281
-
282
-    /**
283
-     * calculates total available spaces for an event with no regard for sold tickets
284
-     *
285
-     * @return int|float
286
-     * @throws EE_Error
287
-     * @throws DomainException
288
-     * @throws UnexpectedEntityException
289
-     * @throws InvalidDataTypeException
290
-     * @throws InvalidInterfaceException
291
-     * @throws InvalidArgumentException
292
-     */
293
-    public function totalSpacesAvailable()
294
-    {
295
-        if ($this->total_spaces_available === null) {
296
-            $this->initialize();
297
-            $this->total_spaces_available = $this->calculate(false);
298
-        }
299
-        return $this->total_spaces_available;
300
-    }
301
-
302
-
303
-    /**
304
-     * Loops through the active tickets for the event
305
-     * and builds a series of data arrays that will be used for calculating
306
-     * the total maximum available spaces, as well as the spaces remaining.
307
-     * Because ticket quantities affect datetime spaces and vice versa,
308
-     * we need to be constantly updating these data arrays as things change,
309
-     * which is the entire reason for their existence.
310
-     *
311
-     * @throws EE_Error
312
-     * @throws DomainException
313
-     * @throws UnexpectedEntityException
314
-     * @throws InvalidDataTypeException
315
-     * @throws InvalidInterfaceException
316
-     * @throws InvalidArgumentException
317
-     */
318
-    private function initialize()
319
-    {
320
-        if ($this->debug) {
321
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
322
-        }
323
-        $this->datetime_tickets = array();
324
-        $this->datetime_spaces = array();
325
-        $this->ticket_datetimes = array();
326
-        $this->ticket_quantities = array();
327
-        $this->tickets_sold = array();
328
-        $this->total_spaces = array();
329
-        $active_tickets = $this->getActiveTickets();
330
-        if (! empty($active_tickets)) {
331
-            foreach ($active_tickets as $ticket) {
332
-                $this->validateTicket($ticket);
333
-                // we need to index our data arrays using strings for the purpose of sorting,
334
-                // but we also need them to be unique, so  we'll just prepend a letter T to the ID
335
-                $ticket_identifier = "T{$ticket->ID()}";
336
-                // to start, we'll just consider the raw qty to be the maximum availability for this ticket,
337
-                // unless the ticket is past its "sell until" date, in which case the qty will be 0
338
-                $max_tickets = $ticket->is_expired() ? 0 : $ticket->qty();
339
-                // but we'll adjust that after looping over each datetime for the ticket and checking reg limits
340
-                $ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
341
-                foreach ($ticket_datetimes as $datetime) {
342
-                    // save all datetimes
343
-                    $this->setDatetime($datetime);
344
-                    $datetime_identifier = "D{$datetime->ID()}";
345
-                    $reg_limit = $datetime->reg_limit();
346
-                    // ticket quantity can not exceed datetime reg limit
347
-                    $max_tickets = min($max_tickets, $reg_limit);
348
-                    // as described earlier, because we need to be able to constantly adjust numbers for things,
349
-                    // we are going to move all of our data into the following arrays:
350
-                    // datetime spaces initially represents the reg limit for each datetime,
351
-                    // but this will get adjusted as tickets are accounted for
352
-                    $this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
353
-                    // just an array of ticket IDs grouped by datetime
354
-                    $this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
355
-                    // and an array of datetime IDs grouped by ticket
356
-                    $this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
357
-                }
358
-                // total quantity of sold and reserved for each ticket
359
-                $this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
360
-                // and the maximum ticket quantities for each ticket (adjusted for reg limit)
361
-                $this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
362
-            }
363
-        }
364
-        // sort datetime spaces by reg limit, but maintain our string indexes
365
-        asort($this->datetime_spaces, SORT_NUMERIC);
366
-        // datetime tickets need to be sorted in the SAME order as the above array...
367
-        // so we'll just use array_merge() to take the structure of datetime_spaces
368
-        // but overwrite all of the data with that from datetime_tickets
369
-        $this->datetime_tickets = array_merge(
370
-            $this->datetime_spaces,
371
-            $this->datetime_tickets
372
-        );
373
-        if ($this->debug) {
374
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
375
-            \EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
376
-            \EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
377
-        }
378
-    }
379
-
380
-
381
-    /**
382
-     * performs calculations on initialized data
383
-     *
384
-     * @param bool $consider_sold
385
-     * @return int|float
386
-     */
387
-    private function calculate($consider_sold = true)
388
-    {
389
-        if ($this->debug) {
390
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
391
-            \EEH_Debug_Tools::printr($consider_sold, '$consider_sold', __FILE__, __LINE__);
392
-        }
393
-        if ($consider_sold) {
394
-            // subtract amounts sold from all ticket quantities and datetime spaces
395
-            $this->adjustTicketQuantitiesDueToSales();
396
-        }
397
-        foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
398
-            $this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
399
-        }
400
-        // total spaces available is just the sum of the spaces available for each datetime
401
-        $spaces_remaining = array_sum($this->total_spaces);
402
-        if ($this->debug) {
403
-            \EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
404
-            \EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
405
-            \EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
406
-        }
407
-        return $spaces_remaining;
408
-    }
409
-
410
-
411
-    /**
412
-     * subtracts amount of  tickets sold from ticket quantities and datetime spaces
413
-     */
414
-    private function adjustTicketQuantitiesDueToSales()
415
-    {
416
-        if ($this->debug) {
417
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
418
-        }
419
-        foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
420
-            if (isset($this->ticket_quantities[ $ticket_identifier ])) {
421
-                $this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
422
-                // don't let values go below zero
423
-                $this->ticket_quantities[ $ticket_identifier ] = max(
424
-                    $this->ticket_quantities[ $ticket_identifier ],
425
-                    0
426
-                );
427
-                if ($this->debug) {
428
-                    \EEH_Debug_Tools::printr(
429
-                        "{$tickets_sold} sales for ticket {$ticket_identifier} ",
430
-                        'subtracting',
431
-                        __FILE__,
432
-                        __LINE__
433
-                    );
434
-                }
435
-            }
436
-            if (isset($this->ticket_datetimes[ $ticket_identifier ])
437
-                && is_array($this->ticket_datetimes[ $ticket_identifier ])
438
-            ) {
439
-                foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
440
-                    if (isset($this->ticket_quantities[ $ticket_identifier ])) {
441
-                        $this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
442
-                        // don't let values go below zero
443
-                        $this->datetime_spaces[ $ticket_datetime ] = max(
444
-                            $this->datetime_spaces[ $ticket_datetime ],
445
-                            0
446
-                        );
447
-                        if ($this->debug) {
448
-                            \EEH_Debug_Tools::printr(
449
-                                "{$tickets_sold} sales for datetime {$ticket_datetime} ",
450
-                                'subtracting',
451
-                                __FILE__,
452
-                                __LINE__
453
-                            );
454
-                        }
455
-                    }
456
-                }
457
-            }
458
-        }
459
-    }
460
-
461
-
462
-    /**
463
-     * @param string $datetime_identifier
464
-     * @param array  $tickets
465
-     */
466
-    private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
467
-    {
468
-        // make sure a reg limit is set for the datetime
469
-        $reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
470
-            ? $this->datetime_spaces[ $datetime_identifier ]
471
-            : 0;
472
-        // and bail if it is not
473
-        if (! $reg_limit) {
474
-            if ($this->debug) {
475
-                \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__);
476
-            }
477
-            return;
478
-        }
479
-        if ($this->debug) {
480
-            \EEH_Debug_Tools::printr($datetime_identifier, '* $datetime_identifier', __FILE__, __LINE__, 1);
481
-            \EEH_Debug_Tools::printr(
482
-                "{$reg_limit}",
483
-                'REG LIMIT',
484
-                __FILE__,
485
-                __LINE__
486
-            );
487
-        }
488
-        // number of allocated spaces always starts at zero
489
-        $spaces_allocated = 0;
490
-        $this->total_spaces[ $datetime_identifier ] = 0;
491
-        foreach ($tickets as $ticket_identifier) {
492
-            $spaces_allocated = $this->calculateAvailableSpacesForTicket(
493
-                $datetime_identifier,
494
-                $reg_limit,
495
-                $ticket_identifier,
496
-                $spaces_allocated
497
-            );
498
-        }
499
-        // spaces can't be negative
500
-        $spaces_allocated = max($spaces_allocated, 0);
501
-        if ($spaces_allocated) {
502
-            // track any non-zero values
503
-            $this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
504
-            if ($this->debug) {
505
-                \EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
506
-            }
507
-        } else {
508
-            if ($this->debug) {
509
-                \EEH_Debug_Tools::printr(' ', ' . NO TICKETS AVAILABLE FOR DATETIME', __FILE__, __LINE__);
510
-            }
511
-        }
512
-        if ($this->debug) {
513
-            \EEH_Debug_Tools::printr(
514
-                $this->total_spaces[ $datetime_identifier ],
515
-                '$total_spaces',
516
-                __FILE__,
517
-                __LINE__
518
-            );
519
-            \EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
520
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
521
-        }
522
-    }
523
-
524
-
525
-    /**
526
-     * @param string $datetime_identifier
527
-     * @param int    $reg_limit
528
-     * @param string $ticket_identifier
529
-     * @param int    $spaces_allocated
530
-     * @return int
531
-     */
532
-    private function calculateAvailableSpacesForTicket(
533
-        $datetime_identifier,
534
-        $reg_limit,
535
-        $ticket_identifier,
536
-        $spaces_allocated
537
-    ) {
538
-        // make sure ticket quantity is set
539
-        $ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
540
-            ? $this->ticket_quantities[ $ticket_identifier ]
541
-            : 0;
542
-        if ($this->debug) {
543
-            \EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
544
-            \EEH_Debug_Tools::printr(
545
-                "{$ticket_quantity}",
546
-                "ticket $ticket_identifier quantity: ",
547
-                __FILE__,
548
-                __LINE__,
549
-                2
550
-            );
551
-        }
552
-        if ($ticket_quantity) {
553
-            if ($this->debug) {
554
-                \EEH_Debug_Tools::printr(
555
-                    ($spaces_allocated <= $reg_limit)
556
-                        ? 'true'
557
-                        : 'false',
558
-                    ' . spaces_allocated <= reg_limit = ',
559
-                    __FILE__,
560
-                    __LINE__
561
-                );
562
-            }
563
-            // if the datetime is NOT at full capacity yet
564
-            if ($spaces_allocated <= $reg_limit) {
565
-                // then the maximum ticket quantity we can allocate is the lowest value of either:
566
-                //  the number of remaining spaces for the datetime, which is the limit - spaces already taken
567
-                //  or the maximum ticket quantity
568
-                $ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
569
-                // adjust the available quantity in our tracking array
570
-                $this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
571
-                // and increment spaces allocated for this datetime
572
-                $spaces_allocated += $ticket_quantity;
573
-                $at_capacity = $spaces_allocated >= $reg_limit;
574
-                if ($this->debug) {
575
-                    \EEH_Debug_Tools::printr(
576
-                        "{$ticket_quantity} {$ticket_identifier} tickets",
577
-                        ' > > allocate ',
578
-                        __FILE__,
579
-                        __LINE__,
580
-                        3
581
-                    );
582
-                    if ($at_capacity) {
583
-                        \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__, 3);
584
-                    }
585
-                }
586
-                // now adjust all other datetimes that allow access to this ticket
587
-                $this->adjustDatetimes(
588
-                    $datetime_identifier,
589
-                    $ticket_identifier,
590
-                    $ticket_quantity,
591
-                    $at_capacity
592
-                );
593
-            }
594
-        }
595
-        return $spaces_allocated;
596
-    }
597
-
598
-
599
-    /**
600
-     * subtracts ticket amounts from all datetime reg limits
601
-     * that allow access to the ticket specified,
602
-     * because that ticket could be used
603
-     * to attend any of the datetimes it has access to
604
-     *
605
-     * @param string $datetime_identifier
606
-     * @param string $ticket_identifier
607
-     * @param bool   $at_capacity
608
-     * @param int    $ticket_quantity
609
-     */
610
-    private function adjustDatetimes(
611
-        $datetime_identifier,
612
-        $ticket_identifier,
613
-        $ticket_quantity,
614
-        $at_capacity
615
-    ) {
616
-        /** @var array $datetime_tickets */
617
-        foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
618
-            if ($datetime_ID !== $datetime_identifier || ! is_array($datetime_tickets)) {
619
-                continue;
620
-            }
621
-            $adjusted = $this->adjustDatetimeSpaces(
622
-                $datetime_ID,
623
-                $ticket_identifier,
624
-                $ticket_quantity
625
-            );
626
-            // skip to next ticket if nothing changed
627
-            if (! ($adjusted || $at_capacity)) {
628
-                continue;
629
-            }
630
-            // then all of it's tickets are now unavailable
631
-            foreach ($datetime_tickets as $datetime_ticket) {
632
-                if (($ticket_identifier === $datetime_ticket || $at_capacity)
633
-                    && isset($this->ticket_quantities[ $datetime_ticket ])
634
-                    && $this->ticket_quantities[ $datetime_ticket ] > 0
635
-                ) {
636
-                    if ($this->debug) {
637
-                        \EEH_Debug_Tools::printr(
638
-                            $datetime_ticket,
639
-                            ' . . . adjust ticket quantities for',
640
-                            __FILE__,
641
-                            __LINE__
642
-                        );
643
-                    }
644
-                    // if this datetime is at full capacity, set any tracked available quantities to zero
645
-                    // otherwise just subtract the ticket quantity
646
-                    $new_quantity = $at_capacity
647
-                        ? 0
648
-                        : $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
649
-                    // don't let ticket quantity go below zero
650
-                    $this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
651
-                    if ($this->debug) {
652
-                        \EEH_Debug_Tools::printr(
653
-                            $at_capacity
654
-                                ? "0 because Datetime {$datetime_identifier} is at capacity"
655
-                                : "{$this->ticket_quantities[ $datetime_ticket ]}",
656
-                            " . . . . {$datetime_ticket} quantity set to ",
657
-                            __FILE__,
658
-                            __LINE__
659
-                        );
660
-                    }
661
-                }
662
-                // but we also need to adjust spaces for any other datetimes this ticket has access to
663
-                if ($datetime_ticket === $ticket_identifier) {
664
-                    if (isset($this->ticket_datetimes[ $datetime_ticket ])
665
-                        && is_array($this->ticket_datetimes[ $datetime_ticket ])
666
-                    ) {
667
-                        if ($this->debug) {
668
-                            \EEH_Debug_Tools::printr(
669
-                                $datetime_ticket,
670
-                                ' . . adjust other Datetimes for',
671
-                                __FILE__,
672
-                                __LINE__
673
-                            );
674
-                        }
675
-                        foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
676
-                            // don't adjust the current datetime twice
677
-                            if ($datetime !== $datetime_identifier) {
678
-                                $this->adjustDatetimeSpaces(
679
-                                    $datetime,
680
-                                    $datetime_ticket,
681
-                                    $ticket_quantity
682
-                                );
683
-                            }
684
-                        }
685
-                    }
686
-                }
687
-            }
688
-        }
689
-    }
690
-
691
-    private function adjustDatetimeSpaces($datetime_identifier, $ticket_identifier, $ticket_quantity = 0)
692
-    {
693
-        // does datetime have spaces available?
694
-        // and does the supplied ticket have access to this datetime ?
695
-        if ($this->datetime_spaces[ $datetime_identifier ] > 0
696
-            && isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
697
-            && in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
698
-        ) {
699
-            if ($this->debug) {
700
-                \EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
701
-                \EEH_Debug_Tools::printr(
702
-                    "{$this->datetime_spaces[ $datetime_identifier ]}",
703
-                    " . . current  {$datetime_identifier} spaces available",
704
-                    __FILE__,
705
-                    __LINE__
706
-                );
707
-            }
708
-            // then decrement the available spaces for the datetime
709
-            $this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
710
-            // but don't let quantities go below zero
711
-            $this->datetime_spaces[ $datetime_identifier ] = max(
712
-                $this->datetime_spaces[ $datetime_identifier ],
713
-                0
714
-            );
715
-            if ($this->debug) {
716
-                \EEH_Debug_Tools::printr(
717
-                    "{$ticket_quantity}",
718
-                    " . . . {$datetime_identifier} capacity reduced by",
719
-                    __FILE__,
720
-                    __LINE__
721
-                );
722
-            }
723
-            return true;
724
-        }
725
-        return false;
726
-    }
29
+	/**
30
+	 * @var EE_Event $event
31
+	 */
32
+	private $event;
33
+
34
+	/**
35
+	 * @var array $datetime_query_params
36
+	 */
37
+	private $datetime_query_params;
38
+
39
+	/**
40
+	 * @var EE_Ticket[] $active_tickets
41
+	 */
42
+	private $active_tickets = array();
43
+
44
+	/**
45
+	 * @var EE_Datetime[] $datetimes
46
+	 */
47
+	private $datetimes = array();
48
+
49
+	/**
50
+	 * Array of Ticket IDs grouped by Datetime
51
+	 *
52
+	 * @var array $datetimes
53
+	 */
54
+	private $datetime_tickets = array();
55
+
56
+	/**
57
+	 * Max spaces for each Datetime (reg limit - previous sold)
58
+	 *
59
+	 * @var array $datetime_spaces
60
+	 */
61
+	private $datetime_spaces = array();
62
+
63
+	/**
64
+	 * Array of Datetime IDs grouped by Ticket
65
+	 *
66
+	 * @var array[] $ticket_datetimes
67
+	 */
68
+	private $ticket_datetimes = array();
69
+
70
+	/**
71
+	 * maximum ticket quantities for each ticket (adjusted for reg limit)
72
+	 *
73
+	 * @var array $ticket_quantities
74
+	 */
75
+	private $ticket_quantities = array();
76
+
77
+	/**
78
+	 * total quantity of sold and reserved for each ticket
79
+	 *
80
+	 * @var array $tickets_sold
81
+	 */
82
+	private $tickets_sold = array();
83
+
84
+	/**
85
+	 * total spaces available across all datetimes
86
+	 *
87
+	 * @var array $total_spaces
88
+	 */
89
+	private $total_spaces = array();
90
+
91
+	/**
92
+	 * @var boolean $debug
93
+	 */
94
+	private $debug = false; // true false
95
+
96
+	/**
97
+	 * @var null|int $spaces_remaining
98
+	 */
99
+	private $spaces_remaining;
100
+
101
+	/**
102
+	 * @var null|int $total_spaces_available
103
+	 */
104
+	private $total_spaces_available;
105
+
106
+
107
+	/**
108
+	 * EventSpacesCalculator constructor.
109
+	 *
110
+	 * @param EE_Event $event
111
+	 * @param array    $datetime_query_params
112
+	 * @throws EE_Error
113
+	 */
114
+	public function __construct(EE_Event $event, array $datetime_query_params = array())
115
+	{
116
+		$this->event = $event;
117
+		$this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
118
+		$this->setHooks();
119
+	}
120
+
121
+
122
+	/**
123
+	 * @return void
124
+	 */
125
+	private function setHooks()
126
+	{
127
+		add_action('AHEE__EE_Ticket__increase_sold', array($this, 'clearResults'));
128
+		add_action('AHEE__EE_Ticket__decrease_sold', array($this, 'clearResults'));
129
+		add_action('AHEE__EE_Datetime__increase_sold', array($this, 'clearResults'));
130
+		add_action('AHEE__EE_Datetime__decrease_sold', array($this, 'clearResults'));
131
+		add_action('AHEE__EE_Ticket__increase_reserved', array($this, 'clearResults'));
132
+		add_action('AHEE__EE_Ticket__decrease_reserved', array($this, 'clearResults'));
133
+		add_action('AHEE__EE_Datetime__increase_reserved', array($this, 'clearResults'));
134
+		add_action('AHEE__EE_Datetime__decrease_reserved', array($this, 'clearResults'));
135
+	}
136
+
137
+
138
+	/**
139
+	 * @return void
140
+	 */
141
+	public function clearResults()
142
+	{
143
+		$this->spaces_remaining = null;
144
+		$this->total_spaces_available = null;
145
+	}
146
+
147
+
148
+	/**
149
+	 * @return EE_Ticket[]
150
+	 * @throws EE_Error
151
+	 * @throws InvalidDataTypeException
152
+	 * @throws InvalidInterfaceException
153
+	 * @throws InvalidArgumentException
154
+	 */
155
+	public function getActiveTickets()
156
+	{
157
+		if (empty($this->active_tickets)) {
158
+			$this->active_tickets = $this->event->tickets(
159
+				array(
160
+					array('TKT_deleted' => false),
161
+					'order_by' => array('TKT_qty' => 'ASC'),
162
+				)
163
+			);
164
+		}
165
+		return $this->active_tickets;
166
+	}
167
+
168
+
169
+	/**
170
+	 * @param EE_Ticket[] $active_tickets
171
+	 * @throws EE_Error
172
+	 * @throws DomainException
173
+	 * @throws UnexpectedEntityException
174
+	 */
175
+	public function setActiveTickets(array $active_tickets = array())
176
+	{
177
+		if (! empty($active_tickets)) {
178
+			foreach ($active_tickets as $active_ticket) {
179
+				$this->validateTicket($active_ticket);
180
+			}
181
+			// sort incoming array by ticket quantity (asc)
182
+			usort(
183
+				$active_tickets,
184
+				function (EE_Ticket $a, EE_Ticket $b) {
185
+					if ($a->qty() === $b->qty()) {
186
+						return 0;
187
+					}
188
+					return ($a->qty() < $b->qty())
189
+						? -1
190
+						: 1;
191
+				}
192
+			);
193
+		}
194
+		$this->active_tickets = $active_tickets;
195
+	}
196
+
197
+
198
+	/**
199
+	 * @param $ticket
200
+	 * @throws DomainException
201
+	 * @throws EE_Error
202
+	 * @throws UnexpectedEntityException
203
+	 */
204
+	private function validateTicket($ticket)
205
+	{
206
+		if (! $ticket instanceof EE_Ticket) {
207
+			throw new DomainException(
208
+				esc_html__(
209
+					'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
210
+					'event_espresso'
211
+				)
212
+			);
213
+		}
214
+		if ($ticket->get_event_ID() !== $this->event->ID()) {
215
+			throw new DomainException(
216
+				sprintf(
217
+					esc_html__(
218
+						'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
219
+						'event_espresso'
220
+					),
221
+					$ticket->get_event_ID(),
222
+					$this->event->ID()
223
+				)
224
+			);
225
+		}
226
+	}
227
+
228
+
229
+	/**
230
+	 * @return EE_Datetime[]
231
+	 */
232
+	public function getDatetimes()
233
+	{
234
+		return $this->datetimes;
235
+	}
236
+
237
+
238
+	/**
239
+	 * @param EE_Datetime $datetime
240
+	 * @throws EE_Error
241
+	 * @throws DomainException
242
+	 */
243
+	public function setDatetime(EE_Datetime $datetime)
244
+	{
245
+		if ($datetime->event()->ID() !== $this->event->ID()) {
246
+			throw new DomainException(
247
+				sprintf(
248
+					esc_html__(
249
+						'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
250
+						'event_espresso'
251
+					),
252
+					$datetime->event()->ID(),
253
+					$this->event->ID()
254
+				)
255
+			);
256
+		}
257
+		$this->datetimes[ $datetime->ID() ] = $datetime;
258
+	}
259
+
260
+
261
+	/**
262
+	 * calculate spaces remaining based on "saleable" tickets
263
+	 *
264
+	 * @return float|int
265
+	 * @throws EE_Error
266
+	 * @throws DomainException
267
+	 * @throws UnexpectedEntityException
268
+	 * @throws InvalidDataTypeException
269
+	 * @throws InvalidInterfaceException
270
+	 * @throws InvalidArgumentException
271
+	 */
272
+	public function spacesRemaining()
273
+	{
274
+		if ($this->spaces_remaining === null) {
275
+			$this->initialize();
276
+			$this->spaces_remaining = $this->calculate();
277
+		}
278
+		return $this->spaces_remaining;
279
+	}
280
+
281
+
282
+	/**
283
+	 * calculates total available spaces for an event with no regard for sold tickets
284
+	 *
285
+	 * @return int|float
286
+	 * @throws EE_Error
287
+	 * @throws DomainException
288
+	 * @throws UnexpectedEntityException
289
+	 * @throws InvalidDataTypeException
290
+	 * @throws InvalidInterfaceException
291
+	 * @throws InvalidArgumentException
292
+	 */
293
+	public function totalSpacesAvailable()
294
+	{
295
+		if ($this->total_spaces_available === null) {
296
+			$this->initialize();
297
+			$this->total_spaces_available = $this->calculate(false);
298
+		}
299
+		return $this->total_spaces_available;
300
+	}
301
+
302
+
303
+	/**
304
+	 * Loops through the active tickets for the event
305
+	 * and builds a series of data arrays that will be used for calculating
306
+	 * the total maximum available spaces, as well as the spaces remaining.
307
+	 * Because ticket quantities affect datetime spaces and vice versa,
308
+	 * we need to be constantly updating these data arrays as things change,
309
+	 * which is the entire reason for their existence.
310
+	 *
311
+	 * @throws EE_Error
312
+	 * @throws DomainException
313
+	 * @throws UnexpectedEntityException
314
+	 * @throws InvalidDataTypeException
315
+	 * @throws InvalidInterfaceException
316
+	 * @throws InvalidArgumentException
317
+	 */
318
+	private function initialize()
319
+	{
320
+		if ($this->debug) {
321
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
322
+		}
323
+		$this->datetime_tickets = array();
324
+		$this->datetime_spaces = array();
325
+		$this->ticket_datetimes = array();
326
+		$this->ticket_quantities = array();
327
+		$this->tickets_sold = array();
328
+		$this->total_spaces = array();
329
+		$active_tickets = $this->getActiveTickets();
330
+		if (! empty($active_tickets)) {
331
+			foreach ($active_tickets as $ticket) {
332
+				$this->validateTicket($ticket);
333
+				// we need to index our data arrays using strings for the purpose of sorting,
334
+				// but we also need them to be unique, so  we'll just prepend a letter T to the ID
335
+				$ticket_identifier = "T{$ticket->ID()}";
336
+				// to start, we'll just consider the raw qty to be the maximum availability for this ticket,
337
+				// unless the ticket is past its "sell until" date, in which case the qty will be 0
338
+				$max_tickets = $ticket->is_expired() ? 0 : $ticket->qty();
339
+				// but we'll adjust that after looping over each datetime for the ticket and checking reg limits
340
+				$ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
341
+				foreach ($ticket_datetimes as $datetime) {
342
+					// save all datetimes
343
+					$this->setDatetime($datetime);
344
+					$datetime_identifier = "D{$datetime->ID()}";
345
+					$reg_limit = $datetime->reg_limit();
346
+					// ticket quantity can not exceed datetime reg limit
347
+					$max_tickets = min($max_tickets, $reg_limit);
348
+					// as described earlier, because we need to be able to constantly adjust numbers for things,
349
+					// we are going to move all of our data into the following arrays:
350
+					// datetime spaces initially represents the reg limit for each datetime,
351
+					// but this will get adjusted as tickets are accounted for
352
+					$this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
353
+					// just an array of ticket IDs grouped by datetime
354
+					$this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
355
+					// and an array of datetime IDs grouped by ticket
356
+					$this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
357
+				}
358
+				// total quantity of sold and reserved for each ticket
359
+				$this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
360
+				// and the maximum ticket quantities for each ticket (adjusted for reg limit)
361
+				$this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
362
+			}
363
+		}
364
+		// sort datetime spaces by reg limit, but maintain our string indexes
365
+		asort($this->datetime_spaces, SORT_NUMERIC);
366
+		// datetime tickets need to be sorted in the SAME order as the above array...
367
+		// so we'll just use array_merge() to take the structure of datetime_spaces
368
+		// but overwrite all of the data with that from datetime_tickets
369
+		$this->datetime_tickets = array_merge(
370
+			$this->datetime_spaces,
371
+			$this->datetime_tickets
372
+		);
373
+		if ($this->debug) {
374
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
375
+			\EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
376
+			\EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
377
+		}
378
+	}
379
+
380
+
381
+	/**
382
+	 * performs calculations on initialized data
383
+	 *
384
+	 * @param bool $consider_sold
385
+	 * @return int|float
386
+	 */
387
+	private function calculate($consider_sold = true)
388
+	{
389
+		if ($this->debug) {
390
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
391
+			\EEH_Debug_Tools::printr($consider_sold, '$consider_sold', __FILE__, __LINE__);
392
+		}
393
+		if ($consider_sold) {
394
+			// subtract amounts sold from all ticket quantities and datetime spaces
395
+			$this->adjustTicketQuantitiesDueToSales();
396
+		}
397
+		foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
398
+			$this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
399
+		}
400
+		// total spaces available is just the sum of the spaces available for each datetime
401
+		$spaces_remaining = array_sum($this->total_spaces);
402
+		if ($this->debug) {
403
+			\EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
404
+			\EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
405
+			\EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
406
+		}
407
+		return $spaces_remaining;
408
+	}
409
+
410
+
411
+	/**
412
+	 * subtracts amount of  tickets sold from ticket quantities and datetime spaces
413
+	 */
414
+	private function adjustTicketQuantitiesDueToSales()
415
+	{
416
+		if ($this->debug) {
417
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
418
+		}
419
+		foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
420
+			if (isset($this->ticket_quantities[ $ticket_identifier ])) {
421
+				$this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
422
+				// don't let values go below zero
423
+				$this->ticket_quantities[ $ticket_identifier ] = max(
424
+					$this->ticket_quantities[ $ticket_identifier ],
425
+					0
426
+				);
427
+				if ($this->debug) {
428
+					\EEH_Debug_Tools::printr(
429
+						"{$tickets_sold} sales for ticket {$ticket_identifier} ",
430
+						'subtracting',
431
+						__FILE__,
432
+						__LINE__
433
+					);
434
+				}
435
+			}
436
+			if (isset($this->ticket_datetimes[ $ticket_identifier ])
437
+				&& is_array($this->ticket_datetimes[ $ticket_identifier ])
438
+			) {
439
+				foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
440
+					if (isset($this->ticket_quantities[ $ticket_identifier ])) {
441
+						$this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
442
+						// don't let values go below zero
443
+						$this->datetime_spaces[ $ticket_datetime ] = max(
444
+							$this->datetime_spaces[ $ticket_datetime ],
445
+							0
446
+						);
447
+						if ($this->debug) {
448
+							\EEH_Debug_Tools::printr(
449
+								"{$tickets_sold} sales for datetime {$ticket_datetime} ",
450
+								'subtracting',
451
+								__FILE__,
452
+								__LINE__
453
+							);
454
+						}
455
+					}
456
+				}
457
+			}
458
+		}
459
+	}
460
+
461
+
462
+	/**
463
+	 * @param string $datetime_identifier
464
+	 * @param array  $tickets
465
+	 */
466
+	private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
467
+	{
468
+		// make sure a reg limit is set for the datetime
469
+		$reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
470
+			? $this->datetime_spaces[ $datetime_identifier ]
471
+			: 0;
472
+		// and bail if it is not
473
+		if (! $reg_limit) {
474
+			if ($this->debug) {
475
+				\EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__);
476
+			}
477
+			return;
478
+		}
479
+		if ($this->debug) {
480
+			\EEH_Debug_Tools::printr($datetime_identifier, '* $datetime_identifier', __FILE__, __LINE__, 1);
481
+			\EEH_Debug_Tools::printr(
482
+				"{$reg_limit}",
483
+				'REG LIMIT',
484
+				__FILE__,
485
+				__LINE__
486
+			);
487
+		}
488
+		// number of allocated spaces always starts at zero
489
+		$spaces_allocated = 0;
490
+		$this->total_spaces[ $datetime_identifier ] = 0;
491
+		foreach ($tickets as $ticket_identifier) {
492
+			$spaces_allocated = $this->calculateAvailableSpacesForTicket(
493
+				$datetime_identifier,
494
+				$reg_limit,
495
+				$ticket_identifier,
496
+				$spaces_allocated
497
+			);
498
+		}
499
+		// spaces can't be negative
500
+		$spaces_allocated = max($spaces_allocated, 0);
501
+		if ($spaces_allocated) {
502
+			// track any non-zero values
503
+			$this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
504
+			if ($this->debug) {
505
+				\EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
506
+			}
507
+		} else {
508
+			if ($this->debug) {
509
+				\EEH_Debug_Tools::printr(' ', ' . NO TICKETS AVAILABLE FOR DATETIME', __FILE__, __LINE__);
510
+			}
511
+		}
512
+		if ($this->debug) {
513
+			\EEH_Debug_Tools::printr(
514
+				$this->total_spaces[ $datetime_identifier ],
515
+				'$total_spaces',
516
+				__FILE__,
517
+				__LINE__
518
+			);
519
+			\EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
520
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
521
+		}
522
+	}
523
+
524
+
525
+	/**
526
+	 * @param string $datetime_identifier
527
+	 * @param int    $reg_limit
528
+	 * @param string $ticket_identifier
529
+	 * @param int    $spaces_allocated
530
+	 * @return int
531
+	 */
532
+	private function calculateAvailableSpacesForTicket(
533
+		$datetime_identifier,
534
+		$reg_limit,
535
+		$ticket_identifier,
536
+		$spaces_allocated
537
+	) {
538
+		// make sure ticket quantity is set
539
+		$ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
540
+			? $this->ticket_quantities[ $ticket_identifier ]
541
+			: 0;
542
+		if ($this->debug) {
543
+			\EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
544
+			\EEH_Debug_Tools::printr(
545
+				"{$ticket_quantity}",
546
+				"ticket $ticket_identifier quantity: ",
547
+				__FILE__,
548
+				__LINE__,
549
+				2
550
+			);
551
+		}
552
+		if ($ticket_quantity) {
553
+			if ($this->debug) {
554
+				\EEH_Debug_Tools::printr(
555
+					($spaces_allocated <= $reg_limit)
556
+						? 'true'
557
+						: 'false',
558
+					' . spaces_allocated <= reg_limit = ',
559
+					__FILE__,
560
+					__LINE__
561
+				);
562
+			}
563
+			// if the datetime is NOT at full capacity yet
564
+			if ($spaces_allocated <= $reg_limit) {
565
+				// then the maximum ticket quantity we can allocate is the lowest value of either:
566
+				//  the number of remaining spaces for the datetime, which is the limit - spaces already taken
567
+				//  or the maximum ticket quantity
568
+				$ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
569
+				// adjust the available quantity in our tracking array
570
+				$this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
571
+				// and increment spaces allocated for this datetime
572
+				$spaces_allocated += $ticket_quantity;
573
+				$at_capacity = $spaces_allocated >= $reg_limit;
574
+				if ($this->debug) {
575
+					\EEH_Debug_Tools::printr(
576
+						"{$ticket_quantity} {$ticket_identifier} tickets",
577
+						' > > allocate ',
578
+						__FILE__,
579
+						__LINE__,
580
+						3
581
+					);
582
+					if ($at_capacity) {
583
+						\EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__, 3);
584
+					}
585
+				}
586
+				// now adjust all other datetimes that allow access to this ticket
587
+				$this->adjustDatetimes(
588
+					$datetime_identifier,
589
+					$ticket_identifier,
590
+					$ticket_quantity,
591
+					$at_capacity
592
+				);
593
+			}
594
+		}
595
+		return $spaces_allocated;
596
+	}
597
+
598
+
599
+	/**
600
+	 * subtracts ticket amounts from all datetime reg limits
601
+	 * that allow access to the ticket specified,
602
+	 * because that ticket could be used
603
+	 * to attend any of the datetimes it has access to
604
+	 *
605
+	 * @param string $datetime_identifier
606
+	 * @param string $ticket_identifier
607
+	 * @param bool   $at_capacity
608
+	 * @param int    $ticket_quantity
609
+	 */
610
+	private function adjustDatetimes(
611
+		$datetime_identifier,
612
+		$ticket_identifier,
613
+		$ticket_quantity,
614
+		$at_capacity
615
+	) {
616
+		/** @var array $datetime_tickets */
617
+		foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
618
+			if ($datetime_ID !== $datetime_identifier || ! is_array($datetime_tickets)) {
619
+				continue;
620
+			}
621
+			$adjusted = $this->adjustDatetimeSpaces(
622
+				$datetime_ID,
623
+				$ticket_identifier,
624
+				$ticket_quantity
625
+			);
626
+			// skip to next ticket if nothing changed
627
+			if (! ($adjusted || $at_capacity)) {
628
+				continue;
629
+			}
630
+			// then all of it's tickets are now unavailable
631
+			foreach ($datetime_tickets as $datetime_ticket) {
632
+				if (($ticket_identifier === $datetime_ticket || $at_capacity)
633
+					&& isset($this->ticket_quantities[ $datetime_ticket ])
634
+					&& $this->ticket_quantities[ $datetime_ticket ] > 0
635
+				) {
636
+					if ($this->debug) {
637
+						\EEH_Debug_Tools::printr(
638
+							$datetime_ticket,
639
+							' . . . adjust ticket quantities for',
640
+							__FILE__,
641
+							__LINE__
642
+						);
643
+					}
644
+					// if this datetime is at full capacity, set any tracked available quantities to zero
645
+					// otherwise just subtract the ticket quantity
646
+					$new_quantity = $at_capacity
647
+						? 0
648
+						: $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
649
+					// don't let ticket quantity go below zero
650
+					$this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
651
+					if ($this->debug) {
652
+						\EEH_Debug_Tools::printr(
653
+							$at_capacity
654
+								? "0 because Datetime {$datetime_identifier} is at capacity"
655
+								: "{$this->ticket_quantities[ $datetime_ticket ]}",
656
+							" . . . . {$datetime_ticket} quantity set to ",
657
+							__FILE__,
658
+							__LINE__
659
+						);
660
+					}
661
+				}
662
+				// but we also need to adjust spaces for any other datetimes this ticket has access to
663
+				if ($datetime_ticket === $ticket_identifier) {
664
+					if (isset($this->ticket_datetimes[ $datetime_ticket ])
665
+						&& is_array($this->ticket_datetimes[ $datetime_ticket ])
666
+					) {
667
+						if ($this->debug) {
668
+							\EEH_Debug_Tools::printr(
669
+								$datetime_ticket,
670
+								' . . adjust other Datetimes for',
671
+								__FILE__,
672
+								__LINE__
673
+							);
674
+						}
675
+						foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
676
+							// don't adjust the current datetime twice
677
+							if ($datetime !== $datetime_identifier) {
678
+								$this->adjustDatetimeSpaces(
679
+									$datetime,
680
+									$datetime_ticket,
681
+									$ticket_quantity
682
+								);
683
+							}
684
+						}
685
+					}
686
+				}
687
+			}
688
+		}
689
+	}
690
+
691
+	private function adjustDatetimeSpaces($datetime_identifier, $ticket_identifier, $ticket_quantity = 0)
692
+	{
693
+		// does datetime have spaces available?
694
+		// and does the supplied ticket have access to this datetime ?
695
+		if ($this->datetime_spaces[ $datetime_identifier ] > 0
696
+			&& isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
697
+			&& in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
698
+		) {
699
+			if ($this->debug) {
700
+				\EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
701
+				\EEH_Debug_Tools::printr(
702
+					"{$this->datetime_spaces[ $datetime_identifier ]}",
703
+					" . . current  {$datetime_identifier} spaces available",
704
+					__FILE__,
705
+					__LINE__
706
+				);
707
+			}
708
+			// then decrement the available spaces for the datetime
709
+			$this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
710
+			// but don't let quantities go below zero
711
+			$this->datetime_spaces[ $datetime_identifier ] = max(
712
+				$this->datetime_spaces[ $datetime_identifier ],
713
+				0
714
+			);
715
+			if ($this->debug) {
716
+				\EEH_Debug_Tools::printr(
717
+					"{$ticket_quantity}",
718
+					" . . . {$datetime_identifier} capacity reduced by",
719
+					__FILE__,
720
+					__LINE__
721
+				);
722
+			}
723
+			return true;
724
+		}
725
+		return false;
726
+	}
727 727
 }
Please login to merge, or discard this patch.
Spacing   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -174,14 +174,14 @@  discard block
 block discarded – undo
174 174
      */
175 175
     public function setActiveTickets(array $active_tickets = array())
176 176
     {
177
-        if (! empty($active_tickets)) {
177
+        if ( ! empty($active_tickets)) {
178 178
             foreach ($active_tickets as $active_ticket) {
179 179
                 $this->validateTicket($active_ticket);
180 180
             }
181 181
             // sort incoming array by ticket quantity (asc)
182 182
             usort(
183 183
                 $active_tickets,
184
-                function (EE_Ticket $a, EE_Ticket $b) {
184
+                function(EE_Ticket $a, EE_Ticket $b) {
185 185
                     if ($a->qty() === $b->qty()) {
186 186
                         return 0;
187 187
                     }
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
      */
204 204
     private function validateTicket($ticket)
205 205
     {
206
-        if (! $ticket instanceof EE_Ticket) {
206
+        if ( ! $ticket instanceof EE_Ticket) {
207 207
             throw new DomainException(
208 208
                 esc_html__(
209 209
                     'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
                 )
255 255
             );
256 256
         }
257
-        $this->datetimes[ $datetime->ID() ] = $datetime;
257
+        $this->datetimes[$datetime->ID()] = $datetime;
258 258
     }
259 259
 
260 260
 
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
         $this->tickets_sold = array();
328 328
         $this->total_spaces = array();
329 329
         $active_tickets = $this->getActiveTickets();
330
-        if (! empty($active_tickets)) {
330
+        if ( ! empty($active_tickets)) {
331 331
             foreach ($active_tickets as $ticket) {
332 332
                 $this->validateTicket($ticket);
333 333
                 // we need to index our data arrays using strings for the purpose of sorting,
@@ -349,16 +349,16 @@  discard block
 block discarded – undo
349 349
                     // we are going to move all of our data into the following arrays:
350 350
                     // datetime spaces initially represents the reg limit for each datetime,
351 351
                     // but this will get adjusted as tickets are accounted for
352
-                    $this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
352
+                    $this->datetime_spaces[$datetime_identifier] = $reg_limit;
353 353
                     // just an array of ticket IDs grouped by datetime
354
-                    $this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
354
+                    $this->datetime_tickets[$datetime_identifier][] = $ticket_identifier;
355 355
                     // and an array of datetime IDs grouped by ticket
356
-                    $this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
356
+                    $this->ticket_datetimes[$ticket_identifier][] = $datetime_identifier;
357 357
                 }
358 358
                 // total quantity of sold and reserved for each ticket
359
-                $this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
359
+                $this->tickets_sold[$ticket_identifier] = $ticket->sold() + $ticket->reserved();
360 360
                 // and the maximum ticket quantities for each ticket (adjusted for reg limit)
361
-                $this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
361
+                $this->ticket_quantities[$ticket_identifier] = $max_tickets;
362 362
             }
363 363
         }
364 364
         // sort datetime spaces by reg limit, but maintain our string indexes
@@ -417,11 +417,11 @@  discard block
 block discarded – undo
417 417
             \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
418 418
         }
419 419
         foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
420
-            if (isset($this->ticket_quantities[ $ticket_identifier ])) {
421
-                $this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
420
+            if (isset($this->ticket_quantities[$ticket_identifier])) {
421
+                $this->ticket_quantities[$ticket_identifier] -= $tickets_sold;
422 422
                 // don't let values go below zero
423
-                $this->ticket_quantities[ $ticket_identifier ] = max(
424
-                    $this->ticket_quantities[ $ticket_identifier ],
423
+                $this->ticket_quantities[$ticket_identifier] = max(
424
+                    $this->ticket_quantities[$ticket_identifier],
425 425
                     0
426 426
                 );
427 427
                 if ($this->debug) {
@@ -433,15 +433,15 @@  discard block
 block discarded – undo
433 433
                     );
434 434
                 }
435 435
             }
436
-            if (isset($this->ticket_datetimes[ $ticket_identifier ])
437
-                && is_array($this->ticket_datetimes[ $ticket_identifier ])
436
+            if (isset($this->ticket_datetimes[$ticket_identifier])
437
+                && is_array($this->ticket_datetimes[$ticket_identifier])
438 438
             ) {
439
-                foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
440
-                    if (isset($this->ticket_quantities[ $ticket_identifier ])) {
441
-                        $this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
439
+                foreach ($this->ticket_datetimes[$ticket_identifier] as $ticket_datetime) {
440
+                    if (isset($this->ticket_quantities[$ticket_identifier])) {
441
+                        $this->datetime_spaces[$ticket_datetime] -= $tickets_sold;
442 442
                         // don't let values go below zero
443
-                        $this->datetime_spaces[ $ticket_datetime ] = max(
444
-                            $this->datetime_spaces[ $ticket_datetime ],
443
+                        $this->datetime_spaces[$ticket_datetime] = max(
444
+                            $this->datetime_spaces[$ticket_datetime],
445 445
                             0
446 446
                         );
447 447
                         if ($this->debug) {
@@ -466,11 +466,11 @@  discard block
 block discarded – undo
466 466
     private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
467 467
     {
468 468
         // make sure a reg limit is set for the datetime
469
-        $reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
470
-            ? $this->datetime_spaces[ $datetime_identifier ]
469
+        $reg_limit = isset($this->datetime_spaces[$datetime_identifier])
470
+            ? $this->datetime_spaces[$datetime_identifier]
471 471
             : 0;
472 472
         // and bail if it is not
473
-        if (! $reg_limit) {
473
+        if ( ! $reg_limit) {
474 474
             if ($this->debug) {
475 475
                 \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__);
476 476
             }
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
         }
488 488
         // number of allocated spaces always starts at zero
489 489
         $spaces_allocated = 0;
490
-        $this->total_spaces[ $datetime_identifier ] = 0;
490
+        $this->total_spaces[$datetime_identifier] = 0;
491 491
         foreach ($tickets as $ticket_identifier) {
492 492
             $spaces_allocated = $this->calculateAvailableSpacesForTicket(
493 493
                 $datetime_identifier,
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
         $spaces_allocated = max($spaces_allocated, 0);
501 501
         if ($spaces_allocated) {
502 502
             // track any non-zero values
503
-            $this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
503
+            $this->total_spaces[$datetime_identifier] += $spaces_allocated;
504 504
             if ($this->debug) {
505 505
                 \EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
506 506
             }
@@ -511,7 +511,7 @@  discard block
 block discarded – undo
511 511
         }
512 512
         if ($this->debug) {
513 513
             \EEH_Debug_Tools::printr(
514
-                $this->total_spaces[ $datetime_identifier ],
514
+                $this->total_spaces[$datetime_identifier],
515 515
                 '$total_spaces',
516 516
                 __FILE__,
517 517
                 __LINE__
@@ -536,8 +536,8 @@  discard block
 block discarded – undo
536 536
         $spaces_allocated
537 537
     ) {
538 538
         // make sure ticket quantity is set
539
-        $ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
540
-            ? $this->ticket_quantities[ $ticket_identifier ]
539
+        $ticket_quantity = isset($this->ticket_quantities[$ticket_identifier])
540
+            ? $this->ticket_quantities[$ticket_identifier]
541 541
             : 0;
542 542
         if ($this->debug) {
543 543
             \EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
                 //  or the maximum ticket quantity
568 568
                 $ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
569 569
                 // adjust the available quantity in our tracking array
570
-                $this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
570
+                $this->ticket_quantities[$ticket_identifier] -= $ticket_quantity;
571 571
                 // and increment spaces allocated for this datetime
572 572
                 $spaces_allocated += $ticket_quantity;
573 573
                 $at_capacity = $spaces_allocated >= $reg_limit;
@@ -624,14 +624,14 @@  discard block
 block discarded – undo
624 624
                 $ticket_quantity
625 625
             );
626 626
             // skip to next ticket if nothing changed
627
-            if (! ($adjusted || $at_capacity)) {
627
+            if ( ! ($adjusted || $at_capacity)) {
628 628
                 continue;
629 629
             }
630 630
             // then all of it's tickets are now unavailable
631 631
             foreach ($datetime_tickets as $datetime_ticket) {
632 632
                 if (($ticket_identifier === $datetime_ticket || $at_capacity)
633
-                    && isset($this->ticket_quantities[ $datetime_ticket ])
634
-                    && $this->ticket_quantities[ $datetime_ticket ] > 0
633
+                    && isset($this->ticket_quantities[$datetime_ticket])
634
+                    && $this->ticket_quantities[$datetime_ticket] > 0
635 635
                 ) {
636 636
                     if ($this->debug) {
637 637
                         \EEH_Debug_Tools::printr(
@@ -645,14 +645,14 @@  discard block
 block discarded – undo
645 645
                     // otherwise just subtract the ticket quantity
646 646
                     $new_quantity = $at_capacity
647 647
                         ? 0
648
-                        : $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
648
+                        : $this->ticket_quantities[$datetime_ticket] - $ticket_quantity;
649 649
                     // don't let ticket quantity go below zero
650
-                    $this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
650
+                    $this->ticket_quantities[$datetime_ticket] = max($new_quantity, 0);
651 651
                     if ($this->debug) {
652 652
                         \EEH_Debug_Tools::printr(
653 653
                             $at_capacity
654 654
                                 ? "0 because Datetime {$datetime_identifier} is at capacity"
655
-                                : "{$this->ticket_quantities[ $datetime_ticket ]}",
655
+                                : "{$this->ticket_quantities[$datetime_ticket]}",
656 656
                             " . . . . {$datetime_ticket} quantity set to ",
657 657
                             __FILE__,
658 658
                             __LINE__
@@ -661,8 +661,8 @@  discard block
 block discarded – undo
661 661
                 }
662 662
                 // but we also need to adjust spaces for any other datetimes this ticket has access to
663 663
                 if ($datetime_ticket === $ticket_identifier) {
664
-                    if (isset($this->ticket_datetimes[ $datetime_ticket ])
665
-                        && is_array($this->ticket_datetimes[ $datetime_ticket ])
664
+                    if (isset($this->ticket_datetimes[$datetime_ticket])
665
+                        && is_array($this->ticket_datetimes[$datetime_ticket])
666 666
                     ) {
667 667
                         if ($this->debug) {
668 668
                             \EEH_Debug_Tools::printr(
@@ -672,7 +672,7 @@  discard block
 block discarded – undo
672 672
                                 __LINE__
673 673
                             );
674 674
                         }
675
-                        foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
675
+                        foreach ($this->ticket_datetimes[$datetime_ticket] as $datetime) {
676 676
                             // don't adjust the current datetime twice
677 677
                             if ($datetime !== $datetime_identifier) {
678 678
                                 $this->adjustDatetimeSpaces(
@@ -692,24 +692,24 @@  discard block
 block discarded – undo
692 692
     {
693 693
         // does datetime have spaces available?
694 694
         // and does the supplied ticket have access to this datetime ?
695
-        if ($this->datetime_spaces[ $datetime_identifier ] > 0
696
-            && isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
697
-            && in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
695
+        if ($this->datetime_spaces[$datetime_identifier] > 0
696
+            && isset($this->datetime_spaces[$datetime_identifier], $this->datetime_tickets[$datetime_identifier])
697
+            && in_array($ticket_identifier, $this->datetime_tickets[$datetime_identifier], true)
698 698
         ) {
699 699
             if ($this->debug) {
700 700
                 \EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
701 701
                 \EEH_Debug_Tools::printr(
702
-                    "{$this->datetime_spaces[ $datetime_identifier ]}",
702
+                    "{$this->datetime_spaces[$datetime_identifier]}",
703 703
                     " . . current  {$datetime_identifier} spaces available",
704 704
                     __FILE__,
705 705
                     __LINE__
706 706
                 );
707 707
             }
708 708
             // then decrement the available spaces for the datetime
709
-            $this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
709
+            $this->datetime_spaces[$datetime_identifier] -= $ticket_quantity;
710 710
             // but don't let quantities go below zero
711
-            $this->datetime_spaces[ $datetime_identifier ] = max(
712
-                $this->datetime_spaces[ $datetime_identifier ],
711
+            $this->datetime_spaces[$datetime_identifier] = max(
712
+                $this->datetime_spaces[$datetime_identifier],
713 713
                 0
714 714
             );
715 715
             if ($this->debug) {
Please login to merge, or discard this patch.
form_sections/strategies/display/EE_Number_Input_Display_Strategy.php 2 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -64,6 +64,9 @@
 block discarded – undo
64 64
     }
65 65
 
66 66
 
67
+    /**
68
+     * @param string $argument_label
69
+     */
67 70
     private function throwValidationException($argument_label, $argument_value)
68 71
     {
69 72
         throw new InvalidArgumentException(
Please login to merge, or discard this patch.
Indentation   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -11,109 +11,109 @@
 block discarded – undo
11 11
 class EE_Number_Input_Display_Strategy extends EE_Display_Strategy_Base
12 12
 {
13 13
 
14
-    /**
15
-     * minimum value for number field
16
-     *
17
-     * @var int|null $min
18
-     */
19
-    protected $min;
14
+	/**
15
+	 * minimum value for number field
16
+	 *
17
+	 * @var int|null $min
18
+	 */
19
+	protected $min;
20 20
 
21
-    /**
22
-     * maximum value for number field
23
-     *
24
-     * @var int|null $max
25
-     */
26
-    protected $max;
21
+	/**
22
+	 * maximum value for number field
23
+	 *
24
+	 * @var int|null $max
25
+	 */
26
+	protected $max;
27 27
 
28 28
 
29
-    /**
30
-     * This is used to set the "step" attribute for the html5 number input.
31
-     * Controls the increments on the input when incrementing or decrementing the value.
32
-     * Note:  Although the step attribute allows for the string "any" to be used, Firefox and Chrome will interpret that
33
-     * to increment by 1.  So although "any" is accepted as a value, it is converted to 1.
34
-     * @var float
35
-     */
36
-    protected $step;
29
+	/**
30
+	 * This is used to set the "step" attribute for the html5 number input.
31
+	 * Controls the increments on the input when incrementing or decrementing the value.
32
+	 * Note:  Although the step attribute allows for the string "any" to be used, Firefox and Chrome will interpret that
33
+	 * to increment by 1.  So although "any" is accepted as a value, it is converted to 1.
34
+	 * @var float
35
+	 */
36
+	protected $step;
37 37
 
38 38
 
39
-    /**
40
-     * EE_Number_Input_Display_Strategy constructor.
41
-     * Null is the default value for the incoming arguments because 0 is a valid value.  So we use null
42
-     * to indicate NOT setting this attribute.
43
-     *
44
-     * @param int|null $min
45
-     * @param int|null $max
46
-     * @param int|null $step
47
-     * @throws InvalidArgumentException
48
-     */
49
-    public function __construct($min = null, $max = null, $step = null)
50
-    {
51
-        $this->min = is_numeric($min) || $min === null
52
-            ? $min
53
-            : $this->throwValidationException('min', $min);
54
-        $this->max = is_numeric($max) || $max === null
55
-            ? $max
56
-            : $this->throwValidationException('max', $max);
57
-        $step = $step === 'any' ? 1 : $step;
58
-        $this->step = is_numeric($step) || $step === null
59
-            ? $step
60
-            : $this->throwValidationException('step', $step);
61
-    }
39
+	/**
40
+	 * EE_Number_Input_Display_Strategy constructor.
41
+	 * Null is the default value for the incoming arguments because 0 is a valid value.  So we use null
42
+	 * to indicate NOT setting this attribute.
43
+	 *
44
+	 * @param int|null $min
45
+	 * @param int|null $max
46
+	 * @param int|null $step
47
+	 * @throws InvalidArgumentException
48
+	 */
49
+	public function __construct($min = null, $max = null, $step = null)
50
+	{
51
+		$this->min = is_numeric($min) || $min === null
52
+			? $min
53
+			: $this->throwValidationException('min', $min);
54
+		$this->max = is_numeric($max) || $max === null
55
+			? $max
56
+			: $this->throwValidationException('max', $max);
57
+		$step = $step === 'any' ? 1 : $step;
58
+		$this->step = is_numeric($step) || $step === null
59
+			? $step
60
+			: $this->throwValidationException('step', $step);
61
+	}
62 62
 
63 63
 
64
-    private function throwValidationException($argument_label, $argument_value)
65
-    {
66
-        throw new InvalidArgumentException(
67
-            sprintf(
68
-                esc_html__(
69
-                    'The %1$s parameter value for %2$s must be numeric or null, %3$s was passed into the constructor.',
70
-                    'event_espresso'
71
-                ),
72
-                $argument_label,
73
-                __CLASS__,
74
-                $argument_value
75
-            )
76
-        );
77
-    }
64
+	private function throwValidationException($argument_label, $argument_value)
65
+	{
66
+		throw new InvalidArgumentException(
67
+			sprintf(
68
+				esc_html__(
69
+					'The %1$s parameter value for %2$s must be numeric or null, %3$s was passed into the constructor.',
70
+					'event_espresso'
71
+				),
72
+				$argument_label,
73
+				__CLASS__,
74
+				$argument_value
75
+			)
76
+		);
77
+	}
78 78
 
79 79
 
80 80
 
81
-    /**
82
-     * @return string of html to display the field
83
-     */
84
-    public function display()
85
-    {
86
-        $input = $this->_opening_tag('input');
87
-        $input .= $this->_attributes_string(
88
-            array_merge(
89
-                $this->_standard_attributes_array(),
90
-                $this->getNumberInputAttributes()
91
-            )
92
-        );
93
-        $input .= $this->_close_tag();
94
-        return $input;
95
-    }
81
+	/**
82
+	 * @return string of html to display the field
83
+	 */
84
+	public function display()
85
+	{
86
+		$input = $this->_opening_tag('input');
87
+		$input .= $this->_attributes_string(
88
+			array_merge(
89
+				$this->_standard_attributes_array(),
90
+				$this->getNumberInputAttributes()
91
+			)
92
+		);
93
+		$input .= $this->_close_tag();
94
+		return $input;
95
+	}
96 96
 
97 97
 
98
-    /**
99
-     * Return the attributes specific to this display strategy
100
-     * @return array
101
-     */
102
-    private function getNumberInputAttributes()
103
-    {
104
-        $attributes = array(
105
-            'type' => 'number',
106
-            'value' => $this->_input->raw_value_in_form()
107
-        );
108
-        if ($this->min !== null) {
109
-            $attributes['min'] = $this->min;
110
-        }
111
-        if ($this->max !== null) {
112
-            $attributes['max'] = $this->max;
113
-        }
114
-        if ($this->step !== null) {
115
-            $attributes['step'] = $this->step;
116
-        }
117
-        return $attributes;
118
-    }
98
+	/**
99
+	 * Return the attributes specific to this display strategy
100
+	 * @return array
101
+	 */
102
+	private function getNumberInputAttributes()
103
+	{
104
+		$attributes = array(
105
+			'type' => 'number',
106
+			'value' => $this->_input->raw_value_in_form()
107
+		);
108
+		if ($this->min !== null) {
109
+			$attributes['min'] = $this->min;
110
+		}
111
+		if ($this->max !== null) {
112
+			$attributes['max'] = $this->max;
113
+		}
114
+		if ($this->step !== null) {
115
+			$attributes['step'] = $this->step;
116
+		}
117
+		return $attributes;
118
+	}
119 119
 }
Please login to merge, or discard this patch.
core/libraries/form_sections/inputs/EE_Float_Input.input.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -11,33 +11,33 @@
 block discarded – undo
11 11
 class EE_Float_Input extends EE_Form_Input_Base
12 12
 {
13 13
 
14
-    /**
15
-     * @param array $input_settings
16
-     * @throws InvalidArgumentException
17
-     */
18
-    public function __construct($input_settings = array())
19
-    {
20
-        $this->_set_display_strategy(
21
-            new EE_Number_Input_Display_Strategy(
22
-                isset($input_settings['min_value'])
23
-                    ? $input_settings['min_value']
24
-                    : null,
25
-                isset($input_settings['max_value'])
26
-                    ? $input_settings['max_value']
27
-                    : null,
28
-                isset($input_settings['step_value'])
29
-                    ? $input_settings['step_value']
30
-                    : null
31
-            )
32
-        );
33
-        $this->_set_normalization_strategy(new EE_Float_Normalization());
34
-        $this->_add_validation_strategy(
35
-            new EE_Float_Validation_Strategy(
36
-                isset($input_settings['validation_error_message'])
37
-                    ? $input_settings['validation_error_message']
38
-                    : null
39
-            )
40
-        );
41
-        parent::__construct($input_settings);
42
-    }
14
+	/**
15
+	 * @param array $input_settings
16
+	 * @throws InvalidArgumentException
17
+	 */
18
+	public function __construct($input_settings = array())
19
+	{
20
+		$this->_set_display_strategy(
21
+			new EE_Number_Input_Display_Strategy(
22
+				isset($input_settings['min_value'])
23
+					? $input_settings['min_value']
24
+					: null,
25
+				isset($input_settings['max_value'])
26
+					? $input_settings['max_value']
27
+					: null,
28
+				isset($input_settings['step_value'])
29
+					? $input_settings['step_value']
30
+					: null
31
+			)
32
+		);
33
+		$this->_set_normalization_strategy(new EE_Float_Normalization());
34
+		$this->_add_validation_strategy(
35
+			new EE_Float_Validation_Strategy(
36
+				isset($input_settings['validation_error_message'])
37
+					? $input_settings['validation_error_message']
38
+					: null
39
+			)
40
+		);
41
+		parent::__construct($input_settings);
42
+	}
43 43
 }
Please login to merge, or discard this patch.
admin_pages/events/Events_Admin_List_Table.class.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -152,7 +152,7 @@
 block discarded – undo
152 152
 
153 153
     /**
154 154
      * @param EE_Event $item
155
-     * @return mixed|string
155
+     * @return string
156 156
      * @throws EE_Error
157 157
      */
158 158
     public function column_id(EE_Event $item)
Please login to merge, or discard this patch.
Indentation   +500 added lines, -500 removed lines patch added patch discarded remove patch
@@ -15,504 +15,504 @@
 block discarded – undo
15 15
 class Events_Admin_List_Table extends EE_Admin_List_Table
16 16
 {
17 17
 
18
-    /**
19
-     * @var EE_Datetime
20
-     */
21
-    private $_dtt;
22
-
23
-
24
-    /**
25
-     * Initial setup of data properties for the list table.
26
-     */
27
-    protected function _setup_data()
28
-    {
29
-        $this->_data = $this->_admin_page->get_events($this->_per_page, $this->_current_page);
30
-        $this->_all_data_count = $this->_admin_page->get_events(0, 0, true);
31
-    }
32
-
33
-
34
-    /**
35
-     * Set up of additional properties for the list table.
36
-     */
37
-    protected function _set_properties()
38
-    {
39
-        $this->_wp_list_args = array(
40
-            'singular' => esc_html__('event', 'event_espresso'),
41
-            'plural'   => esc_html__('events', 'event_espresso'),
42
-            'ajax'     => true, // for now
43
-            'screen'   => $this->_admin_page->get_current_screen()->id,
44
-        );
45
-        $this->_columns = array(
46
-            'cb'              => '<input type="checkbox" />',
47
-            'id'              => esc_html__('ID', 'event_espresso'),
48
-            'name'            => esc_html__('Name', 'event_espresso'),
49
-            'author'          => esc_html__('Author', 'event_espresso'),
50
-            'venue'           => esc_html__('Venue', 'event_espresso'),
51
-            'start_date_time' => esc_html__('Event Start', 'event_espresso'),
52
-            'reg_begins'      => esc_html__('On Sale', 'event_espresso'),
53
-            'attendees'       => '<span class="dashicons dashicons-groups ee-icon-color-ee-green ee-icon-size-20">'
54
-                                 . '<span class="screen-reader-text">'
55
-                                 . esc_html__('Approved Registrations', 'event_espresso')
56
-                                 . '</span>'
57
-                                 . '</span>',
58
-            // 'tkts_sold' => esc_html__('Tickets Sold', 'event_espresso'),
59
-            'actions'         => esc_html__('Actions', 'event_espresso'),
60
-        );
61
-        $this->_sortable_columns = array(
62
-            'id'              => array('EVT_ID' => true),
63
-            'name'            => array('EVT_name' => false),
64
-            'author'          => array('EVT_wp_user' => false),
65
-            'venue'           => array('Venue.VNU_name' => false),
66
-            'start_date_time' => array('Datetime.DTT_EVT_start' => false),
67
-            'reg_begins'      => array('Datetime.Ticket.TKT_start_date' => false),
68
-        );
69
-        $this->_primary_column = 'id';
70
-        $this->_hidden_columns = array('author');
71
-    }
72
-
73
-
74
-    /**
75
-     * @return array
76
-     */
77
-    protected function _get_table_filters()
78
-    {
79
-        return array(); // no filters with decaf
80
-    }
81
-
82
-
83
-    /**
84
-     * Setup of views properties.
85
-     *
86
-     * @throws InvalidDataTypeException
87
-     * @throws InvalidInterfaceException
88
-     * @throws InvalidArgumentException
89
-     */
90
-    protected function _add_view_counts()
91
-    {
92
-        $this->_views['all']['count'] = $this->_admin_page->total_events();
93
-        $this->_views['draft']['count'] = $this->_admin_page->total_events_draft();
94
-        if (EE_Registry::instance()->CAP->current_user_can(
95
-            'ee_delete_events',
96
-            'espresso_events_trash_events'
97
-        )) {
98
-            $this->_views['trash']['count'] = $this->_admin_page->total_trashed_events();
99
-        }
100
-    }
101
-
102
-
103
-    /**
104
-     * @param EE_Event $item
105
-     * @return string
106
-     * @throws EE_Error
107
-     */
108
-    protected function _get_row_class($item)
109
-    {
110
-        $class = parent::_get_row_class($item);
111
-        // add status class
112
-        $class .= $item instanceof EE_Event
113
-            ? ' ee-status-strip event-status-' . $item->get_active_status()
114
-            : '';
115
-        if ($this->_has_checkbox_column) {
116
-            $class .= ' has-checkbox-column';
117
-        }
118
-        return $class;
119
-    }
120
-
121
-
122
-    /**
123
-     * @param EE_Event $item
124
-     * @return string
125
-     * @throws EE_Error
126
-     */
127
-    public function column_status(EE_Event $item)
128
-    {
129
-        return '<span class="ee-status-strip ee-status-strip-td event-status-'
130
-               . $item->get_active_status()
131
-               . '"></span>';
132
-    }
133
-
134
-
135
-    /**
136
-     * @param  EE_Event $item
137
-     * @return string
138
-     * @throws EE_Error
139
-     */
140
-    public function column_cb($item)
141
-    {
142
-        if (! $item instanceof EE_Event) {
143
-            return '';
144
-        }
145
-        $this->_dtt = $item->primary_datetime(); // set this for use in other columns
146
-        // does event have any attached registrations?
147
-        $regs = $item->count_related('Registration');
148
-        return $regs > 0 && $this->_view === 'trash'
149
-            ? '<span class="ee-lock-icon"></span>'
150
-            : sprintf(
151
-                '<input type="checkbox" name="EVT_IDs[]" value="%s" />',
152
-                $item->ID()
153
-            );
154
-    }
155
-
156
-
157
-    /**
158
-     * @param EE_Event $item
159
-     * @return mixed|string
160
-     * @throws EE_Error
161
-     */
162
-    public function column_id(EE_Event $item)
163
-    {
164
-        $content = $item->ID();
165
-        $content .= '  <span class="show-on-mobile-view-only">' . $item->name() . '</span>';
166
-        return $content;
167
-    }
168
-
169
-
170
-    /**
171
-     * @param EE_Event $item
172
-     * @return string
173
-     * @throws EE_Error
174
-     * @throws InvalidArgumentException
175
-     * @throws InvalidDataTypeException
176
-     * @throws InvalidInterfaceException
177
-     */
178
-    public function column_name(EE_Event $item)
179
-    {
180
-        $edit_query_args = array(
181
-            'action' => 'edit',
182
-            'post'   => $item->ID(),
183
-        );
184
-        $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
185
-        $actions = $this->_column_name_action_setup($item);
186
-        $status = ''; // $item->status() !== 'publish' ? ' (' . $item->status() . ')' : '';
187
-        $content = '<strong><a class="row-title" href="'
188
-                   . $edit_link . '">'
189
-                   . $item->name()
190
-                   . '</a></strong>'
191
-                   . $status;
192
-        $content .= '<br><span class="ee-status-text-small">'
193
-                    . EEH_Template::pretty_status(
194
-                        $item->get_active_status(),
195
-                        false,
196
-                        'sentence'
197
-                    )
198
-                    . '</span>';
199
-        $content .= $this->row_actions($actions);
200
-        return $content;
201
-    }
202
-
203
-
204
-    /**
205
-     * Just a method for setting up the actions for the name column
206
-     *
207
-     * @param EE_Event $item
208
-     * @return array array of actions
209
-     * @throws EE_Error
210
-     * @throws InvalidArgumentException
211
-     * @throws InvalidDataTypeException
212
-     * @throws InvalidInterfaceException
213
-     */
214
-    protected function _column_name_action_setup(EE_Event $item)
215
-    {
216
-        // todo: remove when attendees is active
217
-        if (! defined('REG_ADMIN_URL')) {
218
-            define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
219
-        }
220
-        $actions = array();
221
-        $restore_event_link = '';
222
-        $delete_event_link = '';
223
-        $trash_event_link = '';
224
-        if (EE_Registry::instance()->CAP->current_user_can(
225
-            'ee_edit_event',
226
-            'espresso_events_edit',
227
-            $item->ID()
228
-        )) {
229
-            $edit_query_args = array(
230
-                'action' => 'edit',
231
-                'post'   => $item->ID(),
232
-            );
233
-            $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
234
-            $actions['edit'] = '<a href="' . $edit_link . '"'
235
-                               . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
236
-                               . esc_html__('Edit', 'event_espresso')
237
-                               . '</a>';
238
-        }
239
-        if (EE_Registry::instance()->CAP->current_user_can(
240
-            'ee_read_registrations',
241
-            'espresso_registrations_view_registration'
242
-        )
243
-            && EE_Registry::instance()->CAP->current_user_can(
244
-                'ee_read_event',
245
-                'espresso_registrations_view_registration',
246
-                $item->ID()
247
-            )
248
-        ) {
249
-            $attendees_query_args = array(
250
-                'action'   => 'default',
251
-                'event_id' => $item->ID(),
252
-            );
253
-            $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
254
-            $actions['attendees'] = '<a href="' . $attendees_link . '"'
255
-                                    . ' title="' . esc_attr__('View Registrations', 'event_espresso') . '">'
256
-                                    . esc_html__('Registrations', 'event_espresso')
257
-                                    . '</a>';
258
-        }
259
-        if (EE_Registry::instance()->CAP->current_user_can(
260
-            'ee_delete_event',
261
-            'espresso_events_trash_event',
262
-            $item->ID()
263
-        )) {
264
-            $trash_event_query_args = array(
265
-                'action' => 'trash_event',
266
-                'EVT_ID' => $item->ID(),
267
-            );
268
-            $trash_event_link = EE_Admin_Page::add_query_args_and_nonce(
269
-                $trash_event_query_args,
270
-                EVENTS_ADMIN_URL
271
-            );
272
-        }
273
-        if (EE_Registry::instance()->CAP->current_user_can(
274
-            'ee_delete_event',
275
-            'espresso_events_restore_event',
276
-            $item->ID()
277
-        )) {
278
-            $restore_event_query_args = array(
279
-                'action' => 'restore_event',
280
-                'EVT_ID' => $item->ID(),
281
-            );
282
-            $restore_event_link = EE_Admin_Page::add_query_args_and_nonce(
283
-                $restore_event_query_args,
284
-                EVENTS_ADMIN_URL
285
-            );
286
-        }
287
-        if (EE_Registry::instance()->CAP->current_user_can(
288
-            'ee_delete_event',
289
-            'espresso_events_delete_event',
290
-            $item->ID()
291
-        )) {
292
-            $delete_event_query_args = array(
293
-                'action' => 'delete_event',
294
-                'EVT_ID' => $item->ID(),
295
-            );
296
-            $delete_event_link = EE_Admin_Page::add_query_args_and_nonce(
297
-                $delete_event_query_args,
298
-                EVENTS_ADMIN_URL
299
-            );
300
-        }
301
-        $view_link = get_permalink($item->ID());
302
-        $actions['view'] = '<a href="' . $view_link . '"'
303
-                           . ' title="' . esc_attr__('View Event', 'event_espresso') . '">'
304
-                           . esc_html__('View', 'event_espresso')
305
-                           . '</a>';
306
-        if ($item->get('status') === 'trash') {
307
-            if (EE_Registry::instance()->CAP->current_user_can(
308
-                'ee_delete_event',
309
-                'espresso_events_restore_event',
310
-                $item->ID()
311
-            )) {
312
-                $actions['restore_from_trash'] = '<a href="' . $restore_event_link . '"'
313
-                                                 . ' title="' . esc_attr__('Restore from Trash', 'event_espresso')
314
-                                                 . '">'
315
-                                                 . esc_html__('Restore from Trash', 'event_espresso')
316
-                                                 . '</a>';
317
-            }
318
-            if ($item->count_related('Registration') === 0
319
-                && EE_Registry::instance()->CAP->current_user_can(
320
-                    'ee_delete_event',
321
-                    'espresso_events_delete_event',
322
-                    $item->ID()
323
-                )
324
-            ) {
325
-                $actions['delete'] = '<a href="' . $delete_event_link . '"'
326
-                                     . ' title="' . esc_attr__('Delete Permanently', 'event_espresso') . '">'
327
-                                     . esc_html__('Delete Permanently', 'event_espresso')
328
-                                     . '</a>';
329
-            }
330
-        } else {
331
-            if (EE_Registry::instance()->CAP->current_user_can(
332
-                'ee_delete_event',
333
-                'espresso_events_trash_event',
334
-                $item->ID()
335
-            )) {
336
-                $actions['move to trash'] = '<a href="' . $trash_event_link . '"'
337
-                                            . ' title="' . esc_attr__('Trash Event', 'event_espresso') . '">'
338
-                                            . esc_html__('Trash', 'event_espresso')
339
-                                            . '</a>';
340
-            }
341
-        }
342
-        return $actions;
343
-    }
344
-
345
-
346
-    /**
347
-     * @param EE_Event $item
348
-     * @return string
349
-     * @throws EE_Error
350
-     */
351
-    public function column_author(EE_Event $item)
352
-    {
353
-        // user author info
354
-        $event_author = get_userdata($item->wp_user());
355
-        $gravatar = get_avatar($item->wp_user(), '15');
356
-        // filter link
357
-        $query_args = array(
358
-            'action'      => 'default',
359
-            'EVT_wp_user' => $item->wp_user(),
360
-        );
361
-        $filter_url = EE_Admin_Page::add_query_args_and_nonce($query_args, EVENTS_ADMIN_URL);
362
-        return $gravatar . '  <a href="' . $filter_url . '"'
363
-               . ' title="' . esc_attr__('Click to filter events by this author.', 'event_espresso') . '">'
364
-               . $event_author->display_name
365
-               . '</a>';
366
-    }
367
-
368
-
369
-    /**
370
-     * @param EE_Event $item
371
-     * @return string
372
-     * @throws EE_Error
373
-     */
374
-    public function column_venue(EE_Event $item)
375
-    {
376
-        $venue = $item->get_first_related('Venue');
377
-        return ! empty($venue)
378
-            ? $venue->name()
379
-            : '';
380
-    }
381
-
382
-
383
-    /**
384
-     * @param EE_Event $item
385
-     * @return string
386
-     * @throws EE_Error
387
-     */
388
-    public function column_start_date_time(EE_Event $item)
389
-    {
390
-        return $this->_dtt instanceof EE_Datetime
391
-            ? $this->_dtt->get_i18n_datetime('DTT_EVT_start')
392
-            : esc_html__('No Date was saved for this Event', 'event_espresso');
393
-    }
394
-
395
-
396
-    /**
397
-     * @param EE_Event $item
398
-     * @return string
399
-     * @throws EE_Error
400
-     */
401
-    public function column_reg_begins(EE_Event $item)
402
-    {
403
-        $reg_start = $item->get_ticket_with_earliest_start_time();
404
-        return $reg_start instanceof EE_Ticket
405
-            ? $reg_start->get_i18n_datetime('TKT_start_date')
406
-            : esc_html__('No Tickets have been setup for this Event', 'event_espresso');
407
-    }
408
-
409
-
410
-    /**
411
-     * @param EE_Event $item
412
-     * @return int|string
413
-     * @throws EE_Error
414
-     * @throws InvalidArgumentException
415
-     * @throws InvalidDataTypeException
416
-     * @throws InvalidInterfaceException
417
-     */
418
-    public function column_attendees(EE_Event $item)
419
-    {
420
-        $attendees_query_args = array(
421
-            'action'   => 'default',
422
-            'event_id' => $item->ID(),
423
-        );
424
-        $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
425
-        $registered_attendees = EEM_Registration::instance()->get_event_registration_count($item->ID());
426
-        return EE_Registry::instance()->CAP->current_user_can(
427
-            'ee_read_event',
428
-            'espresso_registrations_view_registration',
429
-            $item->ID()
430
-        )
431
-               && EE_Registry::instance()->CAP->current_user_can(
432
-                   'ee_read_registrations',
433
-                   'espresso_registrations_view_registration'
434
-               )
435
-            ? '<a href="' . $attendees_link . '">' . $registered_attendees . '</a>'
436
-            : $registered_attendees;
437
-    }
438
-
439
-
440
-    /**
441
-     * @param EE_Event $item
442
-     * @return float
443
-     * @throws EE_Error
444
-     * @throws InvalidArgumentException
445
-     * @throws InvalidDataTypeException
446
-     * @throws InvalidInterfaceException
447
-     */
448
-    public function column_tkts_sold(EE_Event $item)
449
-    {
450
-        return EEM_Ticket::instance()->sum(array(array('Datetime.EVT_ID' => $item->ID())), 'TKT_sold');
451
-    }
452
-
453
-
454
-    /**
455
-     * @param EE_Event $item
456
-     * @return string
457
-     * @throws EE_Error
458
-     * @throws InvalidArgumentException
459
-     * @throws InvalidDataTypeException
460
-     * @throws InvalidInterfaceException
461
-     */
462
-    public function column_actions(EE_Event $item)
463
-    {
464
-        // todo: remove when attendees is active
465
-        if (! defined('REG_ADMIN_URL')) {
466
-            define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
467
-        }
468
-        $action_links = array();
469
-        $view_link = get_permalink($item->ID());
470
-        $action_links[] = '<a href="' . $view_link . '"'
471
-                          . ' title="' . esc_attr__('View Event', 'event_espresso') . '" target="_blank">';
472
-        $action_links[] = '<div class="dashicons dashicons-search"></div></a>';
473
-        if (EE_Registry::instance()->CAP->current_user_can(
474
-            'ee_edit_event',
475
-            'espresso_events_edit',
476
-            $item->ID()
477
-        )) {
478
-            $edit_query_args = array(
479
-                'action' => 'edit',
480
-                'post'   => $item->ID(),
481
-            );
482
-            $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
483
-            $action_links[] = '<a href="' . $edit_link . '"'
484
-                              . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
485
-                              . '<div class="ee-icon ee-icon-calendar-edit"></div>'
486
-                              . '</a>';
487
-        }
488
-        if (EE_Registry::instance()->CAP->current_user_can(
489
-            'ee_read_registrations',
490
-            'espresso_registrations_view_registration'
491
-        ) && EE_Registry::instance()->CAP->current_user_can(
492
-            'ee_read_event',
493
-            'espresso_registrations_view_registration',
494
-            $item->ID()
495
-        )
496
-        ) {
497
-            $attendees_query_args = array(
498
-                'action'   => 'default',
499
-                'event_id' => $item->ID(),
500
-            );
501
-            $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
502
-            $action_links[] = '<a href="' . $attendees_link . '"'
503
-                              . ' title="' . esc_attr__('View Registrants', 'event_espresso') . '">'
504
-                              . '<div class="dashicons dashicons-groups"></div>'
505
-                              . '</a>';
506
-        }
507
-        $action_links = apply_filters(
508
-            'FHEE__Events_Admin_List_Table__column_actions__action_links',
509
-            $action_links,
510
-            $item
511
-        );
512
-        return $this->_action_string(
513
-            implode("\n\t", $action_links),
514
-            $item,
515
-            'div'
516
-        );
517
-    }
18
+	/**
19
+	 * @var EE_Datetime
20
+	 */
21
+	private $_dtt;
22
+
23
+
24
+	/**
25
+	 * Initial setup of data properties for the list table.
26
+	 */
27
+	protected function _setup_data()
28
+	{
29
+		$this->_data = $this->_admin_page->get_events($this->_per_page, $this->_current_page);
30
+		$this->_all_data_count = $this->_admin_page->get_events(0, 0, true);
31
+	}
32
+
33
+
34
+	/**
35
+	 * Set up of additional properties for the list table.
36
+	 */
37
+	protected function _set_properties()
38
+	{
39
+		$this->_wp_list_args = array(
40
+			'singular' => esc_html__('event', 'event_espresso'),
41
+			'plural'   => esc_html__('events', 'event_espresso'),
42
+			'ajax'     => true, // for now
43
+			'screen'   => $this->_admin_page->get_current_screen()->id,
44
+		);
45
+		$this->_columns = array(
46
+			'cb'              => '<input type="checkbox" />',
47
+			'id'              => esc_html__('ID', 'event_espresso'),
48
+			'name'            => esc_html__('Name', 'event_espresso'),
49
+			'author'          => esc_html__('Author', 'event_espresso'),
50
+			'venue'           => esc_html__('Venue', 'event_espresso'),
51
+			'start_date_time' => esc_html__('Event Start', 'event_espresso'),
52
+			'reg_begins'      => esc_html__('On Sale', 'event_espresso'),
53
+			'attendees'       => '<span class="dashicons dashicons-groups ee-icon-color-ee-green ee-icon-size-20">'
54
+								 . '<span class="screen-reader-text">'
55
+								 . esc_html__('Approved Registrations', 'event_espresso')
56
+								 . '</span>'
57
+								 . '</span>',
58
+			// 'tkts_sold' => esc_html__('Tickets Sold', 'event_espresso'),
59
+			'actions'         => esc_html__('Actions', 'event_espresso'),
60
+		);
61
+		$this->_sortable_columns = array(
62
+			'id'              => array('EVT_ID' => true),
63
+			'name'            => array('EVT_name' => false),
64
+			'author'          => array('EVT_wp_user' => false),
65
+			'venue'           => array('Venue.VNU_name' => false),
66
+			'start_date_time' => array('Datetime.DTT_EVT_start' => false),
67
+			'reg_begins'      => array('Datetime.Ticket.TKT_start_date' => false),
68
+		);
69
+		$this->_primary_column = 'id';
70
+		$this->_hidden_columns = array('author');
71
+	}
72
+
73
+
74
+	/**
75
+	 * @return array
76
+	 */
77
+	protected function _get_table_filters()
78
+	{
79
+		return array(); // no filters with decaf
80
+	}
81
+
82
+
83
+	/**
84
+	 * Setup of views properties.
85
+	 *
86
+	 * @throws InvalidDataTypeException
87
+	 * @throws InvalidInterfaceException
88
+	 * @throws InvalidArgumentException
89
+	 */
90
+	protected function _add_view_counts()
91
+	{
92
+		$this->_views['all']['count'] = $this->_admin_page->total_events();
93
+		$this->_views['draft']['count'] = $this->_admin_page->total_events_draft();
94
+		if (EE_Registry::instance()->CAP->current_user_can(
95
+			'ee_delete_events',
96
+			'espresso_events_trash_events'
97
+		)) {
98
+			$this->_views['trash']['count'] = $this->_admin_page->total_trashed_events();
99
+		}
100
+	}
101
+
102
+
103
+	/**
104
+	 * @param EE_Event $item
105
+	 * @return string
106
+	 * @throws EE_Error
107
+	 */
108
+	protected function _get_row_class($item)
109
+	{
110
+		$class = parent::_get_row_class($item);
111
+		// add status class
112
+		$class .= $item instanceof EE_Event
113
+			? ' ee-status-strip event-status-' . $item->get_active_status()
114
+			: '';
115
+		if ($this->_has_checkbox_column) {
116
+			$class .= ' has-checkbox-column';
117
+		}
118
+		return $class;
119
+	}
120
+
121
+
122
+	/**
123
+	 * @param EE_Event $item
124
+	 * @return string
125
+	 * @throws EE_Error
126
+	 */
127
+	public function column_status(EE_Event $item)
128
+	{
129
+		return '<span class="ee-status-strip ee-status-strip-td event-status-'
130
+			   . $item->get_active_status()
131
+			   . '"></span>';
132
+	}
133
+
134
+
135
+	/**
136
+	 * @param  EE_Event $item
137
+	 * @return string
138
+	 * @throws EE_Error
139
+	 */
140
+	public function column_cb($item)
141
+	{
142
+		if (! $item instanceof EE_Event) {
143
+			return '';
144
+		}
145
+		$this->_dtt = $item->primary_datetime(); // set this for use in other columns
146
+		// does event have any attached registrations?
147
+		$regs = $item->count_related('Registration');
148
+		return $regs > 0 && $this->_view === 'trash'
149
+			? '<span class="ee-lock-icon"></span>'
150
+			: sprintf(
151
+				'<input type="checkbox" name="EVT_IDs[]" value="%s" />',
152
+				$item->ID()
153
+			);
154
+	}
155
+
156
+
157
+	/**
158
+	 * @param EE_Event $item
159
+	 * @return mixed|string
160
+	 * @throws EE_Error
161
+	 */
162
+	public function column_id(EE_Event $item)
163
+	{
164
+		$content = $item->ID();
165
+		$content .= '  <span class="show-on-mobile-view-only">' . $item->name() . '</span>';
166
+		return $content;
167
+	}
168
+
169
+
170
+	/**
171
+	 * @param EE_Event $item
172
+	 * @return string
173
+	 * @throws EE_Error
174
+	 * @throws InvalidArgumentException
175
+	 * @throws InvalidDataTypeException
176
+	 * @throws InvalidInterfaceException
177
+	 */
178
+	public function column_name(EE_Event $item)
179
+	{
180
+		$edit_query_args = array(
181
+			'action' => 'edit',
182
+			'post'   => $item->ID(),
183
+		);
184
+		$edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
185
+		$actions = $this->_column_name_action_setup($item);
186
+		$status = ''; // $item->status() !== 'publish' ? ' (' . $item->status() . ')' : '';
187
+		$content = '<strong><a class="row-title" href="'
188
+				   . $edit_link . '">'
189
+				   . $item->name()
190
+				   . '</a></strong>'
191
+				   . $status;
192
+		$content .= '<br><span class="ee-status-text-small">'
193
+					. EEH_Template::pretty_status(
194
+						$item->get_active_status(),
195
+						false,
196
+						'sentence'
197
+					)
198
+					. '</span>';
199
+		$content .= $this->row_actions($actions);
200
+		return $content;
201
+	}
202
+
203
+
204
+	/**
205
+	 * Just a method for setting up the actions for the name column
206
+	 *
207
+	 * @param EE_Event $item
208
+	 * @return array array of actions
209
+	 * @throws EE_Error
210
+	 * @throws InvalidArgumentException
211
+	 * @throws InvalidDataTypeException
212
+	 * @throws InvalidInterfaceException
213
+	 */
214
+	protected function _column_name_action_setup(EE_Event $item)
215
+	{
216
+		// todo: remove when attendees is active
217
+		if (! defined('REG_ADMIN_URL')) {
218
+			define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
219
+		}
220
+		$actions = array();
221
+		$restore_event_link = '';
222
+		$delete_event_link = '';
223
+		$trash_event_link = '';
224
+		if (EE_Registry::instance()->CAP->current_user_can(
225
+			'ee_edit_event',
226
+			'espresso_events_edit',
227
+			$item->ID()
228
+		)) {
229
+			$edit_query_args = array(
230
+				'action' => 'edit',
231
+				'post'   => $item->ID(),
232
+			);
233
+			$edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
234
+			$actions['edit'] = '<a href="' . $edit_link . '"'
235
+							   . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
236
+							   . esc_html__('Edit', 'event_espresso')
237
+							   . '</a>';
238
+		}
239
+		if (EE_Registry::instance()->CAP->current_user_can(
240
+			'ee_read_registrations',
241
+			'espresso_registrations_view_registration'
242
+		)
243
+			&& EE_Registry::instance()->CAP->current_user_can(
244
+				'ee_read_event',
245
+				'espresso_registrations_view_registration',
246
+				$item->ID()
247
+			)
248
+		) {
249
+			$attendees_query_args = array(
250
+				'action'   => 'default',
251
+				'event_id' => $item->ID(),
252
+			);
253
+			$attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
254
+			$actions['attendees'] = '<a href="' . $attendees_link . '"'
255
+									. ' title="' . esc_attr__('View Registrations', 'event_espresso') . '">'
256
+									. esc_html__('Registrations', 'event_espresso')
257
+									. '</a>';
258
+		}
259
+		if (EE_Registry::instance()->CAP->current_user_can(
260
+			'ee_delete_event',
261
+			'espresso_events_trash_event',
262
+			$item->ID()
263
+		)) {
264
+			$trash_event_query_args = array(
265
+				'action' => 'trash_event',
266
+				'EVT_ID' => $item->ID(),
267
+			);
268
+			$trash_event_link = EE_Admin_Page::add_query_args_and_nonce(
269
+				$trash_event_query_args,
270
+				EVENTS_ADMIN_URL
271
+			);
272
+		}
273
+		if (EE_Registry::instance()->CAP->current_user_can(
274
+			'ee_delete_event',
275
+			'espresso_events_restore_event',
276
+			$item->ID()
277
+		)) {
278
+			$restore_event_query_args = array(
279
+				'action' => 'restore_event',
280
+				'EVT_ID' => $item->ID(),
281
+			);
282
+			$restore_event_link = EE_Admin_Page::add_query_args_and_nonce(
283
+				$restore_event_query_args,
284
+				EVENTS_ADMIN_URL
285
+			);
286
+		}
287
+		if (EE_Registry::instance()->CAP->current_user_can(
288
+			'ee_delete_event',
289
+			'espresso_events_delete_event',
290
+			$item->ID()
291
+		)) {
292
+			$delete_event_query_args = array(
293
+				'action' => 'delete_event',
294
+				'EVT_ID' => $item->ID(),
295
+			);
296
+			$delete_event_link = EE_Admin_Page::add_query_args_and_nonce(
297
+				$delete_event_query_args,
298
+				EVENTS_ADMIN_URL
299
+			);
300
+		}
301
+		$view_link = get_permalink($item->ID());
302
+		$actions['view'] = '<a href="' . $view_link . '"'
303
+						   . ' title="' . esc_attr__('View Event', 'event_espresso') . '">'
304
+						   . esc_html__('View', 'event_espresso')
305
+						   . '</a>';
306
+		if ($item->get('status') === 'trash') {
307
+			if (EE_Registry::instance()->CAP->current_user_can(
308
+				'ee_delete_event',
309
+				'espresso_events_restore_event',
310
+				$item->ID()
311
+			)) {
312
+				$actions['restore_from_trash'] = '<a href="' . $restore_event_link . '"'
313
+												 . ' title="' . esc_attr__('Restore from Trash', 'event_espresso')
314
+												 . '">'
315
+												 . esc_html__('Restore from Trash', 'event_espresso')
316
+												 . '</a>';
317
+			}
318
+			if ($item->count_related('Registration') === 0
319
+				&& EE_Registry::instance()->CAP->current_user_can(
320
+					'ee_delete_event',
321
+					'espresso_events_delete_event',
322
+					$item->ID()
323
+				)
324
+			) {
325
+				$actions['delete'] = '<a href="' . $delete_event_link . '"'
326
+									 . ' title="' . esc_attr__('Delete Permanently', 'event_espresso') . '">'
327
+									 . esc_html__('Delete Permanently', 'event_espresso')
328
+									 . '</a>';
329
+			}
330
+		} else {
331
+			if (EE_Registry::instance()->CAP->current_user_can(
332
+				'ee_delete_event',
333
+				'espresso_events_trash_event',
334
+				$item->ID()
335
+			)) {
336
+				$actions['move to trash'] = '<a href="' . $trash_event_link . '"'
337
+											. ' title="' . esc_attr__('Trash Event', 'event_espresso') . '">'
338
+											. esc_html__('Trash', 'event_espresso')
339
+											. '</a>';
340
+			}
341
+		}
342
+		return $actions;
343
+	}
344
+
345
+
346
+	/**
347
+	 * @param EE_Event $item
348
+	 * @return string
349
+	 * @throws EE_Error
350
+	 */
351
+	public function column_author(EE_Event $item)
352
+	{
353
+		// user author info
354
+		$event_author = get_userdata($item->wp_user());
355
+		$gravatar = get_avatar($item->wp_user(), '15');
356
+		// filter link
357
+		$query_args = array(
358
+			'action'      => 'default',
359
+			'EVT_wp_user' => $item->wp_user(),
360
+		);
361
+		$filter_url = EE_Admin_Page::add_query_args_and_nonce($query_args, EVENTS_ADMIN_URL);
362
+		return $gravatar . '  <a href="' . $filter_url . '"'
363
+			   . ' title="' . esc_attr__('Click to filter events by this author.', 'event_espresso') . '">'
364
+			   . $event_author->display_name
365
+			   . '</a>';
366
+	}
367
+
368
+
369
+	/**
370
+	 * @param EE_Event $item
371
+	 * @return string
372
+	 * @throws EE_Error
373
+	 */
374
+	public function column_venue(EE_Event $item)
375
+	{
376
+		$venue = $item->get_first_related('Venue');
377
+		return ! empty($venue)
378
+			? $venue->name()
379
+			: '';
380
+	}
381
+
382
+
383
+	/**
384
+	 * @param EE_Event $item
385
+	 * @return string
386
+	 * @throws EE_Error
387
+	 */
388
+	public function column_start_date_time(EE_Event $item)
389
+	{
390
+		return $this->_dtt instanceof EE_Datetime
391
+			? $this->_dtt->get_i18n_datetime('DTT_EVT_start')
392
+			: esc_html__('No Date was saved for this Event', 'event_espresso');
393
+	}
394
+
395
+
396
+	/**
397
+	 * @param EE_Event $item
398
+	 * @return string
399
+	 * @throws EE_Error
400
+	 */
401
+	public function column_reg_begins(EE_Event $item)
402
+	{
403
+		$reg_start = $item->get_ticket_with_earliest_start_time();
404
+		return $reg_start instanceof EE_Ticket
405
+			? $reg_start->get_i18n_datetime('TKT_start_date')
406
+			: esc_html__('No Tickets have been setup for this Event', 'event_espresso');
407
+	}
408
+
409
+
410
+	/**
411
+	 * @param EE_Event $item
412
+	 * @return int|string
413
+	 * @throws EE_Error
414
+	 * @throws InvalidArgumentException
415
+	 * @throws InvalidDataTypeException
416
+	 * @throws InvalidInterfaceException
417
+	 */
418
+	public function column_attendees(EE_Event $item)
419
+	{
420
+		$attendees_query_args = array(
421
+			'action'   => 'default',
422
+			'event_id' => $item->ID(),
423
+		);
424
+		$attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
425
+		$registered_attendees = EEM_Registration::instance()->get_event_registration_count($item->ID());
426
+		return EE_Registry::instance()->CAP->current_user_can(
427
+			'ee_read_event',
428
+			'espresso_registrations_view_registration',
429
+			$item->ID()
430
+		)
431
+			   && EE_Registry::instance()->CAP->current_user_can(
432
+				   'ee_read_registrations',
433
+				   'espresso_registrations_view_registration'
434
+			   )
435
+			? '<a href="' . $attendees_link . '">' . $registered_attendees . '</a>'
436
+			: $registered_attendees;
437
+	}
438
+
439
+
440
+	/**
441
+	 * @param EE_Event $item
442
+	 * @return float
443
+	 * @throws EE_Error
444
+	 * @throws InvalidArgumentException
445
+	 * @throws InvalidDataTypeException
446
+	 * @throws InvalidInterfaceException
447
+	 */
448
+	public function column_tkts_sold(EE_Event $item)
449
+	{
450
+		return EEM_Ticket::instance()->sum(array(array('Datetime.EVT_ID' => $item->ID())), 'TKT_sold');
451
+	}
452
+
453
+
454
+	/**
455
+	 * @param EE_Event $item
456
+	 * @return string
457
+	 * @throws EE_Error
458
+	 * @throws InvalidArgumentException
459
+	 * @throws InvalidDataTypeException
460
+	 * @throws InvalidInterfaceException
461
+	 */
462
+	public function column_actions(EE_Event $item)
463
+	{
464
+		// todo: remove when attendees is active
465
+		if (! defined('REG_ADMIN_URL')) {
466
+			define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
467
+		}
468
+		$action_links = array();
469
+		$view_link = get_permalink($item->ID());
470
+		$action_links[] = '<a href="' . $view_link . '"'
471
+						  . ' title="' . esc_attr__('View Event', 'event_espresso') . '" target="_blank">';
472
+		$action_links[] = '<div class="dashicons dashicons-search"></div></a>';
473
+		if (EE_Registry::instance()->CAP->current_user_can(
474
+			'ee_edit_event',
475
+			'espresso_events_edit',
476
+			$item->ID()
477
+		)) {
478
+			$edit_query_args = array(
479
+				'action' => 'edit',
480
+				'post'   => $item->ID(),
481
+			);
482
+			$edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
483
+			$action_links[] = '<a href="' . $edit_link . '"'
484
+							  . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
485
+							  . '<div class="ee-icon ee-icon-calendar-edit"></div>'
486
+							  . '</a>';
487
+		}
488
+		if (EE_Registry::instance()->CAP->current_user_can(
489
+			'ee_read_registrations',
490
+			'espresso_registrations_view_registration'
491
+		) && EE_Registry::instance()->CAP->current_user_can(
492
+			'ee_read_event',
493
+			'espresso_registrations_view_registration',
494
+			$item->ID()
495
+		)
496
+		) {
497
+			$attendees_query_args = array(
498
+				'action'   => 'default',
499
+				'event_id' => $item->ID(),
500
+			);
501
+			$attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
502
+			$action_links[] = '<a href="' . $attendees_link . '"'
503
+							  . ' title="' . esc_attr__('View Registrants', 'event_espresso') . '">'
504
+							  . '<div class="dashicons dashicons-groups"></div>'
505
+							  . '</a>';
506
+		}
507
+		$action_links = apply_filters(
508
+			'FHEE__Events_Admin_List_Table__column_actions__action_links',
509
+			$action_links,
510
+			$item
511
+		);
512
+		return $this->_action_string(
513
+			implode("\n\t", $action_links),
514
+			$item,
515
+			'div'
516
+		);
517
+	}
518 518
 }
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
         $class = parent::_get_row_class($item);
111 111
         // add status class
112 112
         $class .= $item instanceof EE_Event
113
-            ? ' ee-status-strip event-status-' . $item->get_active_status()
113
+            ? ' ee-status-strip event-status-'.$item->get_active_status()
114 114
             : '';
115 115
         if ($this->_has_checkbox_column) {
116 116
             $class .= ' has-checkbox-column';
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
      */
140 140
     public function column_cb($item)
141 141
     {
142
-        if (! $item instanceof EE_Event) {
142
+        if ( ! $item instanceof EE_Event) {
143 143
             return '';
144 144
         }
145 145
         $this->_dtt = $item->primary_datetime(); // set this for use in other columns
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
     public function column_id(EE_Event $item)
163 163
     {
164 164
         $content = $item->ID();
165
-        $content .= '  <span class="show-on-mobile-view-only">' . $item->name() . '</span>';
165
+        $content .= '  <span class="show-on-mobile-view-only">'.$item->name().'</span>';
166 166
         return $content;
167 167
     }
168 168
 
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
         $actions = $this->_column_name_action_setup($item);
186 186
         $status = ''; // $item->status() !== 'publish' ? ' (' . $item->status() . ')' : '';
187 187
         $content = '<strong><a class="row-title" href="'
188
-                   . $edit_link . '">'
188
+                   . $edit_link.'">'
189 189
                    . $item->name()
190 190
                    . '</a></strong>'
191 191
                    . $status;
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
     protected function _column_name_action_setup(EE_Event $item)
215 215
     {
216 216
         // todo: remove when attendees is active
217
-        if (! defined('REG_ADMIN_URL')) {
217
+        if ( ! defined('REG_ADMIN_URL')) {
218 218
             define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
219 219
         }
220 220
         $actions = array();
@@ -231,8 +231,8 @@  discard block
 block discarded – undo
231 231
                 'post'   => $item->ID(),
232 232
             );
233 233
             $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
234
-            $actions['edit'] = '<a href="' . $edit_link . '"'
235
-                               . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
234
+            $actions['edit'] = '<a href="'.$edit_link.'"'
235
+                               . ' title="'.esc_attr__('Edit Event', 'event_espresso').'">'
236 236
                                . esc_html__('Edit', 'event_espresso')
237 237
                                . '</a>';
238 238
         }
@@ -251,8 +251,8 @@  discard block
 block discarded – undo
251 251
                 'event_id' => $item->ID(),
252 252
             );
253 253
             $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
254
-            $actions['attendees'] = '<a href="' . $attendees_link . '"'
255
-                                    . ' title="' . esc_attr__('View Registrations', 'event_espresso') . '">'
254
+            $actions['attendees'] = '<a href="'.$attendees_link.'"'
255
+                                    . ' title="'.esc_attr__('View Registrations', 'event_espresso').'">'
256 256
                                     . esc_html__('Registrations', 'event_espresso')
257 257
                                     . '</a>';
258 258
         }
@@ -299,8 +299,8 @@  discard block
 block discarded – undo
299 299
             );
300 300
         }
301 301
         $view_link = get_permalink($item->ID());
302
-        $actions['view'] = '<a href="' . $view_link . '"'
303
-                           . ' title="' . esc_attr__('View Event', 'event_espresso') . '">'
302
+        $actions['view'] = '<a href="'.$view_link.'"'
303
+                           . ' title="'.esc_attr__('View Event', 'event_espresso').'">'
304 304
                            . esc_html__('View', 'event_espresso')
305 305
                            . '</a>';
306 306
         if ($item->get('status') === 'trash') {
@@ -309,8 +309,8 @@  discard block
 block discarded – undo
309 309
                 'espresso_events_restore_event',
310 310
                 $item->ID()
311 311
             )) {
312
-                $actions['restore_from_trash'] = '<a href="' . $restore_event_link . '"'
313
-                                                 . ' title="' . esc_attr__('Restore from Trash', 'event_espresso')
312
+                $actions['restore_from_trash'] = '<a href="'.$restore_event_link.'"'
313
+                                                 . ' title="'.esc_attr__('Restore from Trash', 'event_espresso')
314 314
                                                  . '">'
315 315
                                                  . esc_html__('Restore from Trash', 'event_espresso')
316 316
                                                  . '</a>';
@@ -322,8 +322,8 @@  discard block
 block discarded – undo
322 322
                     $item->ID()
323 323
                 )
324 324
             ) {
325
-                $actions['delete'] = '<a href="' . $delete_event_link . '"'
326
-                                     . ' title="' . esc_attr__('Delete Permanently', 'event_espresso') . '">'
325
+                $actions['delete'] = '<a href="'.$delete_event_link.'"'
326
+                                     . ' title="'.esc_attr__('Delete Permanently', 'event_espresso').'">'
327 327
                                      . esc_html__('Delete Permanently', 'event_espresso')
328 328
                                      . '</a>';
329 329
             }
@@ -333,8 +333,8 @@  discard block
 block discarded – undo
333 333
                 'espresso_events_trash_event',
334 334
                 $item->ID()
335 335
             )) {
336
-                $actions['move to trash'] = '<a href="' . $trash_event_link . '"'
337
-                                            . ' title="' . esc_attr__('Trash Event', 'event_espresso') . '">'
336
+                $actions['move to trash'] = '<a href="'.$trash_event_link.'"'
337
+                                            . ' title="'.esc_attr__('Trash Event', 'event_espresso').'">'
338 338
                                             . esc_html__('Trash', 'event_espresso')
339 339
                                             . '</a>';
340 340
             }
@@ -359,8 +359,8 @@  discard block
 block discarded – undo
359 359
             'EVT_wp_user' => $item->wp_user(),
360 360
         );
361 361
         $filter_url = EE_Admin_Page::add_query_args_and_nonce($query_args, EVENTS_ADMIN_URL);
362
-        return $gravatar . '  <a href="' . $filter_url . '"'
363
-               . ' title="' . esc_attr__('Click to filter events by this author.', 'event_espresso') . '">'
362
+        return $gravatar.'  <a href="'.$filter_url.'"'
363
+               . ' title="'.esc_attr__('Click to filter events by this author.', 'event_espresso').'">'
364 364
                . $event_author->display_name
365 365
                . '</a>';
366 366
     }
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
                    'ee_read_registrations',
433 433
                    'espresso_registrations_view_registration'
434 434
                )
435
-            ? '<a href="' . $attendees_link . '">' . $registered_attendees . '</a>'
435
+            ? '<a href="'.$attendees_link.'">'.$registered_attendees.'</a>'
436 436
             : $registered_attendees;
437 437
     }
438 438
 
@@ -462,13 +462,13 @@  discard block
 block discarded – undo
462 462
     public function column_actions(EE_Event $item)
463 463
     {
464 464
         // todo: remove when attendees is active
465
-        if (! defined('REG_ADMIN_URL')) {
465
+        if ( ! defined('REG_ADMIN_URL')) {
466 466
             define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
467 467
         }
468 468
         $action_links = array();
469 469
         $view_link = get_permalink($item->ID());
470
-        $action_links[] = '<a href="' . $view_link . '"'
471
-                          . ' title="' . esc_attr__('View Event', 'event_espresso') . '" target="_blank">';
470
+        $action_links[] = '<a href="'.$view_link.'"'
471
+                          . ' title="'.esc_attr__('View Event', 'event_espresso').'" target="_blank">';
472 472
         $action_links[] = '<div class="dashicons dashicons-search"></div></a>';
473 473
         if (EE_Registry::instance()->CAP->current_user_can(
474 474
             'ee_edit_event',
@@ -480,8 +480,8 @@  discard block
 block discarded – undo
480 480
                 'post'   => $item->ID(),
481 481
             );
482 482
             $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
483
-            $action_links[] = '<a href="' . $edit_link . '"'
484
-                              . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
483
+            $action_links[] = '<a href="'.$edit_link.'"'
484
+                              . ' title="'.esc_attr__('Edit Event', 'event_espresso').'">'
485 485
                               . '<div class="ee-icon ee-icon-calendar-edit"></div>'
486 486
                               . '</a>';
487 487
         }
@@ -499,8 +499,8 @@  discard block
 block discarded – undo
499 499
                 'event_id' => $item->ID(),
500 500
             );
501 501
             $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
502
-            $action_links[] = '<a href="' . $attendees_link . '"'
503
-                              . ' title="' . esc_attr__('View Registrants', 'event_espresso') . '">'
502
+            $action_links[] = '<a href="'.$attendees_link.'"'
503
+                              . ' title="'.esc_attr__('View Registrants', 'event_espresso').'">'
504 504
                               . '<div class="dashicons dashicons-groups"></div>'
505 505
                               . '</a>';
506 506
         }
Please login to merge, or discard this patch.
core/services/orm/ModelFieldFactory.php 3 patches
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -33,9 +33,6 @@
 block discarded – undo
33 33
 use EE_WP_Post_Status_Field;
34 34
 use EE_WP_Post_Type_Field;
35 35
 use EE_WP_User_Field;
36
-use EventEspresso\core\exceptions\InvalidDataTypeException;
37
-use EventEspresso\core\exceptions\InvalidInterfaceException;
38
-use EventEspresso\core\services\loaders\LoaderFactory;
39 36
 use EventEspresso\core\services\loaders\LoaderInterface;
40 37
 use InvalidArgumentException;
41 38
 
Please login to merge, or discard this patch.
Doc Comments   +4 added lines, -5 removed lines patch added patch discarded remove patch
@@ -125,7 +125,6 @@  discard block
 block discarded – undo
125 125
     /**
126 126
      * @param string $table_column
127 127
      * @param string $nice_name
128
-     * @param string $timezone_string
129 128
      * @param bool   $nullable
130 129
      * @param string $default_value
131 130
      * @throws EE_Error
@@ -170,7 +169,7 @@  discard block
 block discarded – undo
170 169
      * @param string $table_column
171 170
      * @param string $nice_name
172 171
      * @param bool   $nullable
173
-     * @param null   $default_value
172
+     * @param integer   $default_value
174 173
      * @return EE_DB_Only_Int_Field
175 174
      */
176 175
     public function createDbOnlyIntField($table_column, $nice_name, $nullable, $default_value = null)
@@ -280,7 +279,7 @@  discard block
 block discarded – undo
280 279
      * @param string $table_column
281 280
      * @param string $nice_name
282 281
      * @param bool   $nullable
283
-     * @param null   $default_value
282
+     * @param integer   $default_value
284 283
      * @param string $model_name
285 284
      * @return EE_Foreign_Key_Int_Field
286 285
      */
@@ -297,7 +296,7 @@  discard block
 block discarded – undo
297 296
      * @param string $table_column
298 297
      * @param string $nice_name
299 298
      * @param bool   $nullable
300
-     * @param null   $default_value
299
+     * @param string   $default_value
301 300
      * @param string $model_name
302 301
      * @return EE_Foreign_Key_String_Field
303 302
      */
@@ -533,7 +532,7 @@  discard block
 block discarded – undo
533 532
      * @param string $table_column
534 533
      * @param string $nice_name
535 534
      * @param bool   $nullable
536
-     * @param mixed  $default_value
535
+     * @param string  $default_value
537 536
      * @param array  $values                            If additional stati are to be used other than the default WP
538 537
      *                                                  statuses, then they can be registered via this property. The
539 538
      *                                                  format of the array should be as follows: array(
Please login to merge, or discard this patch.
Indentation   +543 added lines, -543 removed lines patch added patch discarded remove patch
@@ -51,547 +51,547 @@
 block discarded – undo
51 51
 class ModelFieldFactory
52 52
 {
53 53
 
54
-    /**
55
-     * @var LoaderInterface $loader
56
-     */
57
-    private $loader;
58
-
59
-
60
-    /**
61
-     * ModelFieldFactory constructor.
62
-     *
63
-     * @param LoaderInterface $loader
64
-     */
65
-    public function __construct(LoaderInterface $loader)
66
-    {
67
-        $this->loader = $loader;
68
-    }
69
-
70
-
71
-    /**
72
-     * @param string $table_column
73
-     * @param string $nice_name
74
-     * @param bool   $nullable
75
-     * @param null   $default_value
76
-     * @return EE_All_Caps_Text_Field
77
-     */
78
-    public function createAllCapsTextField($table_column, $nice_name, $nullable, $default_value = null)
79
-    {
80
-        return $this->loader->getNew(
81
-            'EE_All_Caps_Text_Field',
82
-            array($table_column, $nice_name, $nullable, $default_value)
83
-        );
84
-    }
85
-
86
-
87
-    /**
88
-     * @param string $table_column
89
-     * @param string $nice_name
90
-     * @param bool   $nullable
91
-     * @param null   $default_value
92
-     * @param string $model_name
93
-     * @return EE_Any_Foreign_Model_Name_Field
94
-     */
95
-    public function createAnyForeignModelNameField(
96
-        $table_column,
97
-        $nice_name,
98
-        $nullable,
99
-        $default_value = null,
100
-        $model_name
101
-    ) {
102
-        return $this->loader->getNew(
103
-            'EE_Any_Foreign_Model_Name_Field',
104
-            array($table_column, $nice_name, $nullable, $default_value, $model_name)
105
-        );
106
-    }
107
-
108
-
109
-    /**
110
-     * @param string $table_column
111
-     * @param string $nice_name
112
-     * @param bool   $nullable
113
-     * @param null   $default_value
114
-     * @return EE_Boolean_Field
115
-     */
116
-    public function createBooleanField($table_column, $nice_name, $nullable, $default_value = null)
117
-    {
118
-        return $this->loader->getNew(
119
-            'EE_Boolean_Field',
120
-            array($table_column, $nice_name, $nullable, $default_value)
121
-        );
122
-    }
123
-
124
-
125
-    /**
126
-     * @param string $table_column
127
-     * @param string $nice_name
128
-     * @param string $timezone_string
129
-     * @param bool   $nullable
130
-     * @param string $default_value
131
-     * @throws EE_Error
132
-     * @throws InvalidArgumentException
133
-     * @return EE_Datetime_Field
134
-     */
135
-    public function createDatetimeField(
136
-        $table_column,
137
-        $nice_name,
138
-        $nullable = false,
139
-        $default_value = EE_Datetime_Field::now
140
-    ) {
141
-        return $this->loader->getNew(
142
-            'EE_Datetime_Field',
143
-            array(
144
-                $table_column,
145
-                $nice_name,
146
-                $nullable,
147
-                $default_value,
148
-            )
149
-        );
150
-    }
151
-
152
-
153
-    /**
154
-     * @param string $table_column
155
-     * @param string $nice_name
156
-     * @param bool   $nullable
157
-     * @param null   $default_value
158
-     * @return EE_DB_Only_Float_Field
159
-     */
160
-    public function createDbOnlyFloatField($table_column, $nice_name, $nullable, $default_value = null)
161
-    {
162
-        return $this->loader->getNew(
163
-            'EE_DB_Only_Float_Field',
164
-            array($table_column, $nice_name, $nullable, $default_value)
165
-        );
166
-    }
167
-
168
-
169
-    /**
170
-     * @param string $table_column
171
-     * @param string $nice_name
172
-     * @param bool   $nullable
173
-     * @param null   $default_value
174
-     * @return EE_DB_Only_Int_Field
175
-     */
176
-    public function createDbOnlyIntField($table_column, $nice_name, $nullable, $default_value = null)
177
-    {
178
-        return $this->loader->getNew(
179
-            'EE_DB_Only_Int_Field',
180
-            array($table_column, $nice_name, $nullable, $default_value)
181
-        );
182
-    }
183
-
184
-
185
-    /**
186
-     * @param string $table_column
187
-     * @param string $nice_name
188
-     * @param bool   $nullable
189
-     * @param null   $default_value
190
-     * @return EE_DB_Only_Text_Field
191
-     */
192
-    public function createDbOnlyTextField($table_column, $nice_name, $nullable, $default_value = null)
193
-    {
194
-        return $this->loader->getNew(
195
-            'EE_DB_Only_Text_Field',
196
-            array($table_column, $nice_name, $nullable, $default_value)
197
-        );
198
-    }
199
-
200
-
201
-    /**
202
-     * @param string $table_column
203
-     * @param string $nice_name
204
-     * @param bool   $nullable
205
-     * @param string $default_value
206
-     * @return EE_Email_Field
207
-     */
208
-    public function createEmailField($table_column, $nice_name, $nullable = true, $default_value = '')
209
-    {
210
-        return $this->loader->getNew(
211
-            'EE_Email_Field',
212
-            array($table_column, $nice_name, $nullable, $default_value)
213
-        );
214
-    }
215
-
216
-
217
-    /**
218
-     * @param string $table_column
219
-     * @param string $nice_name
220
-     * @param bool   $nullable
221
-     * @param null   $default_value
222
-     * @param array  $allowed_enum_values keys are values to be used in the DB,
223
-     *                                    values are how they should be displayed
224
-     * @return EE_Enum_Integer_Field
225
-     */
226
-    public function createEnumIntegerField(
227
-        $table_column,
228
-        $nice_name,
229
-        $nullable,
230
-        $default_value = null,
231
-        array $allowed_enum_values
232
-    ) {
233
-        return $this->loader->getNew(
234
-            'EE_Enum_Integer_Field',
235
-            array($table_column, $nice_name, $nullable, $default_value, $allowed_enum_values)
236
-        );
237
-    }
238
-
239
-
240
-    /**
241
-     * @param string $table_column
242
-     * @param string $nice_name
243
-     * @param bool   $nullable
244
-     * @param null   $default_value
245
-     * @param array  $allowed_enum_values keys are values to be used in the DB,
246
-     *                                    values are how they should be displayed
247
-     * @return EE_Enum_Text_Field
248
-     */
249
-    public function createEnumTextField(
250
-        $table_column,
251
-        $nice_name,
252
-        $nullable,
253
-        $default_value,
254
-        array $allowed_enum_values
255
-    ) {
256
-        return $this->loader->getNew(
257
-            'EE_Enum_Text_Field',
258
-            array($table_column, $nice_name, $nullable, $default_value, $allowed_enum_values)
259
-        );
260
-    }
261
-
262
-
263
-    /**
264
-     * @param string $table_column
265
-     * @param string $nice_name
266
-     * @param bool   $nullable
267
-     * @param null   $default_value
268
-     * @return EE_Float_Field
269
-     */
270
-    public function createFloatField($table_column, $nice_name, $nullable, $default_value = null)
271
-    {
272
-        return $this->loader->getNew(
273
-            'EE_Float_Field',
274
-            array($table_column, $nice_name, $nullable, $default_value)
275
-        );
276
-    }
277
-
278
-
279
-    /**
280
-     * @param string $table_column
281
-     * @param string $nice_name
282
-     * @param bool   $nullable
283
-     * @param null   $default_value
284
-     * @param string $model_name
285
-     * @return EE_Foreign_Key_Int_Field
286
-     */
287
-    public function createForeignKeyIntField($table_column, $nice_name, $nullable, $default_value, $model_name)
288
-    {
289
-        return $this->loader->getNew(
290
-            'EE_Foreign_Key_Int_Field',
291
-            array($table_column, $nice_name, $nullable, $default_value, $model_name)
292
-        );
293
-    }
294
-
295
-
296
-    /**
297
-     * @param string $table_column
298
-     * @param string $nice_name
299
-     * @param bool   $nullable
300
-     * @param null   $default_value
301
-     * @param string $model_name
302
-     * @return EE_Foreign_Key_String_Field
303
-     */
304
-    public function createForeignKeyStringField(
305
-        $table_column,
306
-        $nice_name,
307
-        $nullable,
308
-        $default_value,
309
-        $model_name
310
-    ) {
311
-        return $this->loader->getNew(
312
-            'EE_Foreign_Key_String_Field',
313
-            array($table_column, $nice_name, $nullable, $default_value, $model_name)
314
-        );
315
-    }
316
-
317
-
318
-    /**
319
-     * @param string $table_column
320
-     * @param string $nice_name
321
-     * @param bool   $nullable
322
-     * @param null   $default_value
323
-     * @return EE_Full_HTML_Field
324
-     */
325
-    public function createFullHtmlField($table_column, $nice_name, $nullable, $default_value = null)
326
-    {
327
-        return $this->loader->getNew(
328
-            'EE_Full_HTML_Field',
329
-            array($table_column, $nice_name, $nullable, $default_value)
330
-        );
331
-    }
332
-
333
-
334
-    /**
335
-     * @param string $table_column
336
-     * @param string $nice_name
337
-     * @param bool   $nullable
338
-     * @param null   $default_value
339
-     * @return EE_Infinite_Integer_Field
340
-     */
341
-    public function createInfiniteIntegerField($table_column, $nice_name, $nullable, $default_value = null)
342
-    {
343
-        return $this->loader->getNew(
344
-            'EE_Infinite_Integer_Field',
345
-            array($table_column, $nice_name, $nullable, $default_value)
346
-        );
347
-    }
348
-
349
-
350
-    /**
351
-     * @param string  $table_column
352
-     * @param string  $nice_name
353
-     * @param bool    $nullable
354
-     * @param integer $default_value
355
-     * @return EE_Integer_Field
356
-     */
357
-    public function createIntegerField($table_column, $nice_name, $nullable = false, $default_value = 0)
358
-    {
359
-        return $this->loader->getNew(
360
-            'EE_Integer_Field',
361
-            array($table_column, $nice_name, $nullable, $default_value)
362
-        );
363
-    }
364
-
365
-
366
-    /**
367
-     * @param string $table_column
368
-     * @param string $nice_name
369
-     * @param bool   $nullable
370
-     * @param null   $default_value
371
-     * @return EE_Maybe_Serialized_Simple_HTML_Field
372
-     */
373
-    public function createMaybeSerializedSimpleHtmlField($table_column, $nice_name, $nullable, $default_value = null)
374
-    {
375
-        return $this->loader->getNew(
376
-            'EE_Maybe_Serialized_Simple_HTML_Field',
377
-            array($table_column, $nice_name, $nullable, $default_value)
378
-        );
379
-    }
380
-
381
-
382
-    /**
383
-     * @param string $table_column
384
-     * @param string $nice_name
385
-     * @param bool   $nullable
386
-     * @param null   $default_value
387
-     * @return EE_Maybe_Serialized_Text_Field
388
-     */
389
-    public function createMaybeSerializedTextField($table_column, $nice_name, $nullable, $default_value = null)
390
-    {
391
-        return $this->loader->getNew(
392
-            'EE_Maybe_Serialized_Text_Field',
393
-            array($table_column, $nice_name, $nullable, $default_value)
394
-        );
395
-    }
396
-
397
-
398
-    /**
399
-     * @param string $table_column
400
-     * @param string $nice_name
401
-     * @param bool   $nullable
402
-     * @param null   $default_value
403
-     * @return EE_Money_Field
404
-     */
405
-    public function createMoneyField($table_column, $nice_name, $nullable, $default_value = null)
406
-    {
407
-        return $this->loader->getNew(
408
-            'EE_Money_Field',
409
-            array($table_column, $nice_name, $nullable, $default_value)
410
-        );
411
-    }
412
-
413
-
414
-    /**
415
-     * @param string $table_column
416
-     * @param string $nice_name
417
-     * @param bool   $nullable
418
-     * @param string $default_value
419
-     * @return EE_Plain_Text_Field
420
-     */
421
-    public function createPlainTextField($table_column, $nice_name, $nullable = true, $default_value = '')
422
-    {
423
-        return $this->loader->getNew(
424
-            'EE_Plain_Text_Field',
425
-            array($table_column, $nice_name, $nullable, $default_value)
426
-        );
427
-    }
428
-
429
-
430
-    /**
431
-     * @param string $table_column
432
-     * @param string $nice_name
433
-     * @param bool   $nullable
434
-     * @param null   $default_value
435
-     * @return EE_Post_Content_Field
436
-     */
437
-    public function createPostContentField($table_column, $nice_name, $nullable, $default_value = null)
438
-    {
439
-        return $this->loader->getNew(
440
-            'EE_Post_Content_Field',
441
-            array($table_column, $nice_name, $nullable, $default_value)
442
-        );
443
-    }
444
-
445
-
446
-    /**
447
-     * @param string $table_column
448
-     * @param string $nice_name
449
-     * @return EE_Primary_Key_Int_Field
450
-     */
451
-    public function createPrimaryKeyIntField($table_column, $nice_name)
452
-    {
453
-        return $this->loader->getNew('EE_Primary_Key_Int_Field', array($table_column, $nice_name));
454
-    }
455
-
456
-
457
-    /**
458
-     * @param string $table_column
459
-     * @param string $nice_name
460
-     * @return EE_Primary_Key_String_Field
461
-     */
462
-    public function createPrimaryKeyStringField($table_column, $nice_name)
463
-    {
464
-        return $this->loader->getNew('EE_Primary_Key_String_Field', array($table_column, $nice_name));
465
-    }
466
-
467
-
468
-    /**
469
-     * @param string $table_column
470
-     * @param string $nice_name
471
-     * @param bool   $nullable
472
-     * @param null   $default_value
473
-     * @return EE_Serialized_Text_Field
474
-     */
475
-    public function createSerializedTextField($table_column, $nice_name, $nullable, $default_value = null)
476
-    {
477
-        return $this->loader->getNew(
478
-            'EE_Serialized_Text_Field',
479
-            array($table_column, $nice_name, $nullable, $default_value)
480
-        );
481
-    }
482
-
483
-
484
-    /**
485
-     * @param string $table_column
486
-     * @param string $nice_name
487
-     * @param bool   $nullable
488
-     * @param null   $default_value
489
-     * @return EE_Simple_HTML_Field
490
-     */
491
-    public function createSimpleHtmlField($table_column, $nice_name, $nullable, $default_value = null)
492
-    {
493
-        return $this->loader->getNew(
494
-            'EE_Simple_HTML_Field',
495
-            array($table_column, $nice_name, $nullable, $default_value)
496
-        );
497
-    }
498
-
499
-
500
-    /**
501
-     * @param string $table_column
502
-     * @param string $nice_name
503
-     * @param bool   $nullable
504
-     * @param null   $default_value
505
-     * @return EE_Slug_Field
506
-     */
507
-    public function createSlugField($table_column, $nice_name, $nullable = false, $default_value = null)
508
-    {
509
-        return $this->loader->getNew(
510
-            'EE_Slug_Field',
511
-            array($table_column, $nice_name, $nullable, $default_value)
512
-        );
513
-    }
514
-
515
-
516
-    /**
517
-     * @param string $table_column
518
-     * @param string $nice_name
519
-     * @param bool   $nullable
520
-     * @param null   $default_value
521
-     * @return EE_Trashed_Flag_Field
522
-     */
523
-    public function createTrashedFlagField($table_column, $nice_name, $nullable, $default_value = null)
524
-    {
525
-        return $this->loader->getNew(
526
-            'EE_Trashed_Flag_Field',
527
-            array($table_column, $nice_name, $nullable, $default_value)
528
-        );
529
-    }
530
-
531
-
532
-    /**
533
-     * @param string $table_column
534
-     * @param string $nice_name
535
-     * @param bool   $nullable
536
-     * @param mixed  $default_value
537
-     * @param array  $values                            If additional stati are to be used other than the default WP
538
-     *                                                  statuses, then they can be registered via this property. The
539
-     *                                                  format of the array should be as follows: array(
540
-     *                                                  'status_reference' => array(
541
-     *                                                  'label' => __('Status Reference Label', 'event_espresso'),
542
-     *                                                  'public' => true,                 // whether this status should
543
-     *                                                  be shown on the frontend of the site
544
-     *                                                  'exclude_from_search' => false,   // whether this status should
545
-     *                                                  be excluded from wp searches
546
-     *                                                  'show_in_admin_all_list' => true, // whether this status is
547
-     *                                                  included in queries for the admin "all" view in list table
548
-     *                                                  views.
549
-     *                                                  'show_in_admin_status_list' => true, // show in the list of
550
-     *                                                  statuses with post counts at the top of the admin list tables
551
-     *                                                  (i.e. Status Reference(2) )
552
-     *                                                  'label_count' => _n_noop(
553
-     *                                                  'Status Reference <span class="count">(%s)</span>',
554
-     *                                                  'Status References <span class="count">(%s)</span>'
555
-     *                                                  ),                                   // the text to display on
556
-     *                                                  the admin screen
557
-     *                                                  ( or you won't see your status count ).
558
-     *                                                  )
559
-     *                                                  )
560
-     * @link http://codex.wordpress.org/Function_Reference/register_post_status for more info
561
-     * @return EE_WP_Post_Status_Field
562
-     */
563
-    public function createWpPostStatusField(
564
-        $table_column,
565
-        $nice_name,
566
-        $nullable,
567
-        $default_value = null,
568
-        array $values = array()
569
-    ) {
570
-        return $this->loader->getNew(
571
-            'EE_WP_Post_Status_Field',
572
-            array($table_column, $nice_name, $nullable, $default_value, $values)
573
-        );
574
-    }
575
-
576
-
577
-    /**
578
-     * @param string $post_type
579
-     * @return EE_WP_Post_Type_Field
580
-     */
581
-    public function createWpPostTypeField($post_type)
582
-    {
583
-        return $this->loader->getNew('EE_WP_Post_Type_Field', array($post_type));
584
-    }
585
-
586
-
587
-    /**
588
-     * @param string $table_column
589
-     * @param string $nice_name
590
-     * @param bool   $nullable
591
-     * @return EE_WP_User_Field
592
-     */
593
-    public function createWpUserField($table_column, $nice_name, $nullable)
594
-    {
595
-        return $this->loader->getNew('EE_WP_User_Field', array($table_column, $nice_name, $nullable));
596
-    }
54
+	/**
55
+	 * @var LoaderInterface $loader
56
+	 */
57
+	private $loader;
58
+
59
+
60
+	/**
61
+	 * ModelFieldFactory constructor.
62
+	 *
63
+	 * @param LoaderInterface $loader
64
+	 */
65
+	public function __construct(LoaderInterface $loader)
66
+	{
67
+		$this->loader = $loader;
68
+	}
69
+
70
+
71
+	/**
72
+	 * @param string $table_column
73
+	 * @param string $nice_name
74
+	 * @param bool   $nullable
75
+	 * @param null   $default_value
76
+	 * @return EE_All_Caps_Text_Field
77
+	 */
78
+	public function createAllCapsTextField($table_column, $nice_name, $nullable, $default_value = null)
79
+	{
80
+		return $this->loader->getNew(
81
+			'EE_All_Caps_Text_Field',
82
+			array($table_column, $nice_name, $nullable, $default_value)
83
+		);
84
+	}
85
+
86
+
87
+	/**
88
+	 * @param string $table_column
89
+	 * @param string $nice_name
90
+	 * @param bool   $nullable
91
+	 * @param null   $default_value
92
+	 * @param string $model_name
93
+	 * @return EE_Any_Foreign_Model_Name_Field
94
+	 */
95
+	public function createAnyForeignModelNameField(
96
+		$table_column,
97
+		$nice_name,
98
+		$nullable,
99
+		$default_value = null,
100
+		$model_name
101
+	) {
102
+		return $this->loader->getNew(
103
+			'EE_Any_Foreign_Model_Name_Field',
104
+			array($table_column, $nice_name, $nullable, $default_value, $model_name)
105
+		);
106
+	}
107
+
108
+
109
+	/**
110
+	 * @param string $table_column
111
+	 * @param string $nice_name
112
+	 * @param bool   $nullable
113
+	 * @param null   $default_value
114
+	 * @return EE_Boolean_Field
115
+	 */
116
+	public function createBooleanField($table_column, $nice_name, $nullable, $default_value = null)
117
+	{
118
+		return $this->loader->getNew(
119
+			'EE_Boolean_Field',
120
+			array($table_column, $nice_name, $nullable, $default_value)
121
+		);
122
+	}
123
+
124
+
125
+	/**
126
+	 * @param string $table_column
127
+	 * @param string $nice_name
128
+	 * @param string $timezone_string
129
+	 * @param bool   $nullable
130
+	 * @param string $default_value
131
+	 * @throws EE_Error
132
+	 * @throws InvalidArgumentException
133
+	 * @return EE_Datetime_Field
134
+	 */
135
+	public function createDatetimeField(
136
+		$table_column,
137
+		$nice_name,
138
+		$nullable = false,
139
+		$default_value = EE_Datetime_Field::now
140
+	) {
141
+		return $this->loader->getNew(
142
+			'EE_Datetime_Field',
143
+			array(
144
+				$table_column,
145
+				$nice_name,
146
+				$nullable,
147
+				$default_value,
148
+			)
149
+		);
150
+	}
151
+
152
+
153
+	/**
154
+	 * @param string $table_column
155
+	 * @param string $nice_name
156
+	 * @param bool   $nullable
157
+	 * @param null   $default_value
158
+	 * @return EE_DB_Only_Float_Field
159
+	 */
160
+	public function createDbOnlyFloatField($table_column, $nice_name, $nullable, $default_value = null)
161
+	{
162
+		return $this->loader->getNew(
163
+			'EE_DB_Only_Float_Field',
164
+			array($table_column, $nice_name, $nullable, $default_value)
165
+		);
166
+	}
167
+
168
+
169
+	/**
170
+	 * @param string $table_column
171
+	 * @param string $nice_name
172
+	 * @param bool   $nullable
173
+	 * @param null   $default_value
174
+	 * @return EE_DB_Only_Int_Field
175
+	 */
176
+	public function createDbOnlyIntField($table_column, $nice_name, $nullable, $default_value = null)
177
+	{
178
+		return $this->loader->getNew(
179
+			'EE_DB_Only_Int_Field',
180
+			array($table_column, $nice_name, $nullable, $default_value)
181
+		);
182
+	}
183
+
184
+
185
+	/**
186
+	 * @param string $table_column
187
+	 * @param string $nice_name
188
+	 * @param bool   $nullable
189
+	 * @param null   $default_value
190
+	 * @return EE_DB_Only_Text_Field
191
+	 */
192
+	public function createDbOnlyTextField($table_column, $nice_name, $nullable, $default_value = null)
193
+	{
194
+		return $this->loader->getNew(
195
+			'EE_DB_Only_Text_Field',
196
+			array($table_column, $nice_name, $nullable, $default_value)
197
+		);
198
+	}
199
+
200
+
201
+	/**
202
+	 * @param string $table_column
203
+	 * @param string $nice_name
204
+	 * @param bool   $nullable
205
+	 * @param string $default_value
206
+	 * @return EE_Email_Field
207
+	 */
208
+	public function createEmailField($table_column, $nice_name, $nullable = true, $default_value = '')
209
+	{
210
+		return $this->loader->getNew(
211
+			'EE_Email_Field',
212
+			array($table_column, $nice_name, $nullable, $default_value)
213
+		);
214
+	}
215
+
216
+
217
+	/**
218
+	 * @param string $table_column
219
+	 * @param string $nice_name
220
+	 * @param bool   $nullable
221
+	 * @param null   $default_value
222
+	 * @param array  $allowed_enum_values keys are values to be used in the DB,
223
+	 *                                    values are how they should be displayed
224
+	 * @return EE_Enum_Integer_Field
225
+	 */
226
+	public function createEnumIntegerField(
227
+		$table_column,
228
+		$nice_name,
229
+		$nullable,
230
+		$default_value = null,
231
+		array $allowed_enum_values
232
+	) {
233
+		return $this->loader->getNew(
234
+			'EE_Enum_Integer_Field',
235
+			array($table_column, $nice_name, $nullable, $default_value, $allowed_enum_values)
236
+		);
237
+	}
238
+
239
+
240
+	/**
241
+	 * @param string $table_column
242
+	 * @param string $nice_name
243
+	 * @param bool   $nullable
244
+	 * @param null   $default_value
245
+	 * @param array  $allowed_enum_values keys are values to be used in the DB,
246
+	 *                                    values are how they should be displayed
247
+	 * @return EE_Enum_Text_Field
248
+	 */
249
+	public function createEnumTextField(
250
+		$table_column,
251
+		$nice_name,
252
+		$nullable,
253
+		$default_value,
254
+		array $allowed_enum_values
255
+	) {
256
+		return $this->loader->getNew(
257
+			'EE_Enum_Text_Field',
258
+			array($table_column, $nice_name, $nullable, $default_value, $allowed_enum_values)
259
+		);
260
+	}
261
+
262
+
263
+	/**
264
+	 * @param string $table_column
265
+	 * @param string $nice_name
266
+	 * @param bool   $nullable
267
+	 * @param null   $default_value
268
+	 * @return EE_Float_Field
269
+	 */
270
+	public function createFloatField($table_column, $nice_name, $nullable, $default_value = null)
271
+	{
272
+		return $this->loader->getNew(
273
+			'EE_Float_Field',
274
+			array($table_column, $nice_name, $nullable, $default_value)
275
+		);
276
+	}
277
+
278
+
279
+	/**
280
+	 * @param string $table_column
281
+	 * @param string $nice_name
282
+	 * @param bool   $nullable
283
+	 * @param null   $default_value
284
+	 * @param string $model_name
285
+	 * @return EE_Foreign_Key_Int_Field
286
+	 */
287
+	public function createForeignKeyIntField($table_column, $nice_name, $nullable, $default_value, $model_name)
288
+	{
289
+		return $this->loader->getNew(
290
+			'EE_Foreign_Key_Int_Field',
291
+			array($table_column, $nice_name, $nullable, $default_value, $model_name)
292
+		);
293
+	}
294
+
295
+
296
+	/**
297
+	 * @param string $table_column
298
+	 * @param string $nice_name
299
+	 * @param bool   $nullable
300
+	 * @param null   $default_value
301
+	 * @param string $model_name
302
+	 * @return EE_Foreign_Key_String_Field
303
+	 */
304
+	public function createForeignKeyStringField(
305
+		$table_column,
306
+		$nice_name,
307
+		$nullable,
308
+		$default_value,
309
+		$model_name
310
+	) {
311
+		return $this->loader->getNew(
312
+			'EE_Foreign_Key_String_Field',
313
+			array($table_column, $nice_name, $nullable, $default_value, $model_name)
314
+		);
315
+	}
316
+
317
+
318
+	/**
319
+	 * @param string $table_column
320
+	 * @param string $nice_name
321
+	 * @param bool   $nullable
322
+	 * @param null   $default_value
323
+	 * @return EE_Full_HTML_Field
324
+	 */
325
+	public function createFullHtmlField($table_column, $nice_name, $nullable, $default_value = null)
326
+	{
327
+		return $this->loader->getNew(
328
+			'EE_Full_HTML_Field',
329
+			array($table_column, $nice_name, $nullable, $default_value)
330
+		);
331
+	}
332
+
333
+
334
+	/**
335
+	 * @param string $table_column
336
+	 * @param string $nice_name
337
+	 * @param bool   $nullable
338
+	 * @param null   $default_value
339
+	 * @return EE_Infinite_Integer_Field
340
+	 */
341
+	public function createInfiniteIntegerField($table_column, $nice_name, $nullable, $default_value = null)
342
+	{
343
+		return $this->loader->getNew(
344
+			'EE_Infinite_Integer_Field',
345
+			array($table_column, $nice_name, $nullable, $default_value)
346
+		);
347
+	}
348
+
349
+
350
+	/**
351
+	 * @param string  $table_column
352
+	 * @param string  $nice_name
353
+	 * @param bool    $nullable
354
+	 * @param integer $default_value
355
+	 * @return EE_Integer_Field
356
+	 */
357
+	public function createIntegerField($table_column, $nice_name, $nullable = false, $default_value = 0)
358
+	{
359
+		return $this->loader->getNew(
360
+			'EE_Integer_Field',
361
+			array($table_column, $nice_name, $nullable, $default_value)
362
+		);
363
+	}
364
+
365
+
366
+	/**
367
+	 * @param string $table_column
368
+	 * @param string $nice_name
369
+	 * @param bool   $nullable
370
+	 * @param null   $default_value
371
+	 * @return EE_Maybe_Serialized_Simple_HTML_Field
372
+	 */
373
+	public function createMaybeSerializedSimpleHtmlField($table_column, $nice_name, $nullable, $default_value = null)
374
+	{
375
+		return $this->loader->getNew(
376
+			'EE_Maybe_Serialized_Simple_HTML_Field',
377
+			array($table_column, $nice_name, $nullable, $default_value)
378
+		);
379
+	}
380
+
381
+
382
+	/**
383
+	 * @param string $table_column
384
+	 * @param string $nice_name
385
+	 * @param bool   $nullable
386
+	 * @param null   $default_value
387
+	 * @return EE_Maybe_Serialized_Text_Field
388
+	 */
389
+	public function createMaybeSerializedTextField($table_column, $nice_name, $nullable, $default_value = null)
390
+	{
391
+		return $this->loader->getNew(
392
+			'EE_Maybe_Serialized_Text_Field',
393
+			array($table_column, $nice_name, $nullable, $default_value)
394
+		);
395
+	}
396
+
397
+
398
+	/**
399
+	 * @param string $table_column
400
+	 * @param string $nice_name
401
+	 * @param bool   $nullable
402
+	 * @param null   $default_value
403
+	 * @return EE_Money_Field
404
+	 */
405
+	public function createMoneyField($table_column, $nice_name, $nullable, $default_value = null)
406
+	{
407
+		return $this->loader->getNew(
408
+			'EE_Money_Field',
409
+			array($table_column, $nice_name, $nullable, $default_value)
410
+		);
411
+	}
412
+
413
+
414
+	/**
415
+	 * @param string $table_column
416
+	 * @param string $nice_name
417
+	 * @param bool   $nullable
418
+	 * @param string $default_value
419
+	 * @return EE_Plain_Text_Field
420
+	 */
421
+	public function createPlainTextField($table_column, $nice_name, $nullable = true, $default_value = '')
422
+	{
423
+		return $this->loader->getNew(
424
+			'EE_Plain_Text_Field',
425
+			array($table_column, $nice_name, $nullable, $default_value)
426
+		);
427
+	}
428
+
429
+
430
+	/**
431
+	 * @param string $table_column
432
+	 * @param string $nice_name
433
+	 * @param bool   $nullable
434
+	 * @param null   $default_value
435
+	 * @return EE_Post_Content_Field
436
+	 */
437
+	public function createPostContentField($table_column, $nice_name, $nullable, $default_value = null)
438
+	{
439
+		return $this->loader->getNew(
440
+			'EE_Post_Content_Field',
441
+			array($table_column, $nice_name, $nullable, $default_value)
442
+		);
443
+	}
444
+
445
+
446
+	/**
447
+	 * @param string $table_column
448
+	 * @param string $nice_name
449
+	 * @return EE_Primary_Key_Int_Field
450
+	 */
451
+	public function createPrimaryKeyIntField($table_column, $nice_name)
452
+	{
453
+		return $this->loader->getNew('EE_Primary_Key_Int_Field', array($table_column, $nice_name));
454
+	}
455
+
456
+
457
+	/**
458
+	 * @param string $table_column
459
+	 * @param string $nice_name
460
+	 * @return EE_Primary_Key_String_Field
461
+	 */
462
+	public function createPrimaryKeyStringField($table_column, $nice_name)
463
+	{
464
+		return $this->loader->getNew('EE_Primary_Key_String_Field', array($table_column, $nice_name));
465
+	}
466
+
467
+
468
+	/**
469
+	 * @param string $table_column
470
+	 * @param string $nice_name
471
+	 * @param bool   $nullable
472
+	 * @param null   $default_value
473
+	 * @return EE_Serialized_Text_Field
474
+	 */
475
+	public function createSerializedTextField($table_column, $nice_name, $nullable, $default_value = null)
476
+	{
477
+		return $this->loader->getNew(
478
+			'EE_Serialized_Text_Field',
479
+			array($table_column, $nice_name, $nullable, $default_value)
480
+		);
481
+	}
482
+
483
+
484
+	/**
485
+	 * @param string $table_column
486
+	 * @param string $nice_name
487
+	 * @param bool   $nullable
488
+	 * @param null   $default_value
489
+	 * @return EE_Simple_HTML_Field
490
+	 */
491
+	public function createSimpleHtmlField($table_column, $nice_name, $nullable, $default_value = null)
492
+	{
493
+		return $this->loader->getNew(
494
+			'EE_Simple_HTML_Field',
495
+			array($table_column, $nice_name, $nullable, $default_value)
496
+		);
497
+	}
498
+
499
+
500
+	/**
501
+	 * @param string $table_column
502
+	 * @param string $nice_name
503
+	 * @param bool   $nullable
504
+	 * @param null   $default_value
505
+	 * @return EE_Slug_Field
506
+	 */
507
+	public function createSlugField($table_column, $nice_name, $nullable = false, $default_value = null)
508
+	{
509
+		return $this->loader->getNew(
510
+			'EE_Slug_Field',
511
+			array($table_column, $nice_name, $nullable, $default_value)
512
+		);
513
+	}
514
+
515
+
516
+	/**
517
+	 * @param string $table_column
518
+	 * @param string $nice_name
519
+	 * @param bool   $nullable
520
+	 * @param null   $default_value
521
+	 * @return EE_Trashed_Flag_Field
522
+	 */
523
+	public function createTrashedFlagField($table_column, $nice_name, $nullable, $default_value = null)
524
+	{
525
+		return $this->loader->getNew(
526
+			'EE_Trashed_Flag_Field',
527
+			array($table_column, $nice_name, $nullable, $default_value)
528
+		);
529
+	}
530
+
531
+
532
+	/**
533
+	 * @param string $table_column
534
+	 * @param string $nice_name
535
+	 * @param bool   $nullable
536
+	 * @param mixed  $default_value
537
+	 * @param array  $values                            If additional stati are to be used other than the default WP
538
+	 *                                                  statuses, then they can be registered via this property. The
539
+	 *                                                  format of the array should be as follows: array(
540
+	 *                                                  'status_reference' => array(
541
+	 *                                                  'label' => __('Status Reference Label', 'event_espresso'),
542
+	 *                                                  'public' => true,                 // whether this status should
543
+	 *                                                  be shown on the frontend of the site
544
+	 *                                                  'exclude_from_search' => false,   // whether this status should
545
+	 *                                                  be excluded from wp searches
546
+	 *                                                  'show_in_admin_all_list' => true, // whether this status is
547
+	 *                                                  included in queries for the admin "all" view in list table
548
+	 *                                                  views.
549
+	 *                                                  'show_in_admin_status_list' => true, // show in the list of
550
+	 *                                                  statuses with post counts at the top of the admin list tables
551
+	 *                                                  (i.e. Status Reference(2) )
552
+	 *                                                  'label_count' => _n_noop(
553
+	 *                                                  'Status Reference <span class="count">(%s)</span>',
554
+	 *                                                  'Status References <span class="count">(%s)</span>'
555
+	 *                                                  ),                                   // the text to display on
556
+	 *                                                  the admin screen
557
+	 *                                                  ( or you won't see your status count ).
558
+	 *                                                  )
559
+	 *                                                  )
560
+	 * @link http://codex.wordpress.org/Function_Reference/register_post_status for more info
561
+	 * @return EE_WP_Post_Status_Field
562
+	 */
563
+	public function createWpPostStatusField(
564
+		$table_column,
565
+		$nice_name,
566
+		$nullable,
567
+		$default_value = null,
568
+		array $values = array()
569
+	) {
570
+		return $this->loader->getNew(
571
+			'EE_WP_Post_Status_Field',
572
+			array($table_column, $nice_name, $nullable, $default_value, $values)
573
+		);
574
+	}
575
+
576
+
577
+	/**
578
+	 * @param string $post_type
579
+	 * @return EE_WP_Post_Type_Field
580
+	 */
581
+	public function createWpPostTypeField($post_type)
582
+	{
583
+		return $this->loader->getNew('EE_WP_Post_Type_Field', array($post_type));
584
+	}
585
+
586
+
587
+	/**
588
+	 * @param string $table_column
589
+	 * @param string $nice_name
590
+	 * @param bool   $nullable
591
+	 * @return EE_WP_User_Field
592
+	 */
593
+	public function createWpUserField($table_column, $nice_name, $nullable)
594
+	{
595
+		return $this->loader->getNew('EE_WP_User_Field', array($table_column, $nice_name, $nullable));
596
+	}
597 597
 }
Please login to merge, or discard this patch.
core/EE_Request_Handler.core.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 
276 276
 
277 277
     /**
278
-     * @param $string
278
+     * @param string $string
279 279
      * @return void
280 280
      */
281 281
     public function add_output($string)
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
 
328 328
 
329 329
     /**
330
-     * @return    mixed
330
+     * @return    boolean
331 331
      */
332 332
     public function is_espresso_page()
333 333
     {
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
     /**
390 390
      * remove param
391 391
      *
392
-     * @param $key
392
+     * @param string $key
393 393
      * @return    void
394 394
      */
395 395
     public function un_set($key)
Please login to merge, or discard this patch.
Indentation   +365 added lines, -365 removed lines patch added patch discarded remove patch
@@ -12,369 +12,369 @@
 block discarded – undo
12 12
 final class EE_Request_Handler implements InterminableInterface
13 13
 {
14 14
 
15
-    /**
16
-     * @var EE_Request $request
17
-     */
18
-    private $request;
19
-
20
-    /**
21
-     * @var array $_notice
22
-     */
23
-    private $_notice = array();
24
-
25
-    /**
26
-     * rendered output to be returned to WP
27
-     *
28
-     * @var string $_output
29
-     */
30
-    private $_output = '';
31
-
32
-    /**
33
-     * whether current request is via AJAX
34
-     *
35
-     * @var boolean $ajax
36
-     */
37
-    public $ajax = false;
38
-
39
-    /**
40
-     * whether current request is via AJAX from the frontend of the site
41
-     *
42
-     * @var boolean $front_ajax
43
-     */
44
-    public $front_ajax = false;
45
-
46
-
47
-    /**
48
-     * @param  EE_Request $request
49
-     */
50
-    public function __construct(EE_Request $request)
51
-    {
52
-        $this->request = $request;
53
-        $this->ajax = $this->request->ajax;
54
-        $this->front_ajax = $this->request->front_ajax;
55
-        do_action('AHEE__EE_Request_Handler__construct__complete');
56
-    }
57
-
58
-
59
-    /**
60
-     * @param WP $wp
61
-     * @return void
62
-     * @throws EE_Error
63
-     * @throws ReflectionException
64
-     */
65
-    public function parse_request($wp = null)
66
-    {
67
-        // if somebody forgot to provide us with WP, that's ok because its global
68
-        if (! $wp instanceof WP) {
69
-            global $wp;
70
-        }
71
-        $this->set_request_vars($wp);
72
-    }
73
-
74
-
75
-    /**
76
-     * @param WP $wp
77
-     * @return void
78
-     * @throws EE_Error
79
-     * @throws ReflectionException
80
-     */
81
-    public function set_request_vars($wp = null)
82
-    {
83
-        if (! is_admin()) {
84
-            // set request post_id
85
-            $this->request->set('post_id', $this->get_post_id_from_request($wp));
86
-            // set request post name
87
-            $this->request->set('post_name', $this->get_post_name_from_request($wp));
88
-            // set request post_type
89
-            $this->request->set('post_type', $this->get_post_type_from_request($wp));
90
-            // true or false ? is this page being used by EE ?
91
-            $this->set_espresso_page();
92
-        }
93
-    }
94
-
95
-
96
-    /**
97
-     * @param WP $wp
98
-     * @return int
99
-     */
100
-    public function get_post_id_from_request($wp = null)
101
-    {
102
-        if (! $wp instanceof WP) {
103
-            global $wp;
104
-        }
105
-        $post_id = null;
106
-        if (isset($wp->query_vars['p'])) {
107
-            $post_id = $wp->query_vars['p'];
108
-        }
109
-        if (! $post_id && isset($wp->query_vars['page_id'])) {
110
-            $post_id = $wp->query_vars['page_id'];
111
-        }
112
-        if (! $post_id && $wp->request !== null && is_numeric(basename($wp->request))) {
113
-            $post_id = basename($wp->request);
114
-        }
115
-        return $post_id;
116
-    }
117
-
118
-
119
-    /**
120
-     * @param WP $wp
121
-     * @return string
122
-     */
123
-    public function get_post_name_from_request($wp = null)
124
-    {
125
-        if (! $wp instanceof WP) {
126
-            global $wp;
127
-        }
128
-        $post_name = null;
129
-        if (isset($wp->query_vars['name']) && ! empty($wp->query_vars['name'])) {
130
-            $post_name = $wp->query_vars['name'];
131
-        }
132
-        if (! $post_name && isset($wp->query_vars['pagename']) && ! empty($wp->query_vars['pagename'])) {
133
-            $post_name = $wp->query_vars['pagename'];
134
-        }
135
-        if (! $post_name && $wp->request !== null && ! empty($wp->request)) {
136
-            $possible_post_name = basename($wp->request);
137
-            if (! is_numeric($possible_post_name)) {
138
-                /** @type WPDB $wpdb */
139
-                global $wpdb;
140
-                $SQL =
141
-                    "SELECT ID from {$wpdb->posts} WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND post_name=%s";
142
-                $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
143
-                if ($possible_post_name) {
144
-                    $post_name = $possible_post_name;
145
-                }
146
-            }
147
-        }
148
-        if (! $post_name && $this->get('post_id')) {
149
-            /** @type WPDB $wpdb */
150
-            global $wpdb;
151
-            $SQL =
152
-                "SELECT post_name from {$wpdb->posts} WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND ID=%d";
153
-            $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->get('post_id')));
154
-            if ($possible_post_name) {
155
-                $post_name = $possible_post_name;
156
-            }
157
-        }
158
-        return $post_name;
159
-    }
160
-
161
-
162
-    /**
163
-     * @param WP $wp
164
-     * @return mixed
165
-     */
166
-    public function get_post_type_from_request($wp = null)
167
-    {
168
-        if (! $wp instanceof WP) {
169
-            global $wp;
170
-        }
171
-        return isset($wp->query_vars['post_type'])
172
-            ? $wp->query_vars['post_type']
173
-            : null;
174
-    }
175
-
176
-
177
-    /**
178
-     * Just a helper method for getting the url for the displayed page.
179
-     *
180
-     * @param  WP $wp
181
-     * @return string
182
-     */
183
-    public function get_current_page_permalink($wp = null)
184
-    {
185
-        $post_id = $this->get_post_id_from_request($wp);
186
-        if ($post_id) {
187
-            $current_page_permalink = get_permalink($post_id);
188
-        } else {
189
-            if (! $wp instanceof WP) {
190
-                global $wp;
191
-            }
192
-            if ($wp->request) {
193
-                $current_page_permalink = site_url($wp->request);
194
-            } else {
195
-                $current_page_permalink = esc_url(site_url($_SERVER['REQUEST_URI']));
196
-            }
197
-        }
198
-        return $current_page_permalink;
199
-    }
200
-
201
-
202
-    /**
203
-     * @return bool
204
-     * @throws EE_Error
205
-     * @throws ReflectionException
206
-     */
207
-    public function test_for_espresso_page()
208
-    {
209
-        global $wp;
210
-        /** @type EE_CPT_Strategy $EE_CPT_Strategy */
211
-        $EE_CPT_Strategy = EE_Registry::instance()->load_core('CPT_Strategy');
212
-        $espresso_CPT_taxonomies = $EE_CPT_Strategy->get_CPT_taxonomies();
213
-        if (is_array($espresso_CPT_taxonomies)) {
214
-            foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
215
-                if (isset($wp->query_vars, $wp->query_vars[ $espresso_CPT_taxonomy ])) {
216
-                    return true;
217
-                }
218
-            }
219
-        }
220
-        // load espresso CPT endpoints
221
-        $espresso_CPT_endpoints = $EE_CPT_Strategy->get_CPT_endpoints();
222
-        $post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
223
-        $post_types = (array) $this->get('post_type');
224
-        foreach ($post_types as $post_type) {
225
-            // was a post name passed ?
226
-            if (isset($post_type_CPT_endpoints[ $post_type ])) {
227
-                // kk we know this is an espresso page, but is it a specific post ?
228
-                if (! $this->get('post_name')) {
229
-                    // there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
230
-                    $post_name = isset($post_type_CPT_endpoints[ $this->get('post_type') ])
231
-                        ? $post_type_CPT_endpoints[ $this->get('post_type') ]
232
-                        : '';
233
-                    // if the post type matches on of our then set the endpoint
234
-                    if ($post_name) {
235
-                        $this->set('post_name', $post_name);
236
-                    }
237
-                }
238
-                return true;
239
-            }
240
-        }
241
-        return false;
242
-    }
243
-
244
-    /**
245
-     * @param $key
246
-     * @param $value
247
-     * @return    void
248
-     */
249
-    public function set_notice($key, $value)
250
-    {
251
-        $this->_notice[ $key ] = $value;
252
-    }
253
-
254
-
255
-    /**
256
-     * @param $key
257
-     * @return    mixed
258
-     */
259
-    public function get_notice($key)
260
-    {
261
-        return isset($this->_notice[ $key ])
262
-            ? $this->_notice[ $key ]
263
-            : null;
264
-    }
265
-
266
-
267
-    /**
268
-     * @param $string
269
-     * @return void
270
-     */
271
-    public function add_output($string)
272
-    {
273
-        $this->_output .= $string;
274
-    }
275
-
276
-
277
-    /**
278
-     * @return string
279
-     */
280
-    public function get_output()
281
-    {
282
-        return $this->_output;
283
-    }
284
-
285
-
286
-    /**
287
-     * @param $item
288
-     * @param $key
289
-     */
290
-    public function sanitize_text_field_for_array_walk(&$item, &$key)
291
-    {
292
-        $item = strpos($item, 'email') !== false
293
-            ? sanitize_email($item)
294
-            : sanitize_text_field($item);
295
-    }
296
-
297
-
298
-    /**
299
-     * @param null|bool $value
300
-     * @return void
301
-     * @throws EE_Error
302
-     * @throws ReflectionException
303
-     */
304
-    public function set_espresso_page($value = null)
305
-    {
306
-        $this->request->set(
307
-            'is_espresso_page',
308
-            ! empty($value)
309
-                ? $value
310
-                : $this->test_for_espresso_page()
311
-        );
312
-    }
313
-
314
-
315
-    /**
316
-     * @return    mixed
317
-     */
318
-    public function is_espresso_page()
319
-    {
320
-        return $this->request->is_set('is_espresso_page');
321
-    }
322
-
323
-
324
-    /**
325
-     * returns contents of $_REQUEST
326
-     *
327
-     * @return array
328
-     */
329
-    public function params()
330
-    {
331
-        return $this->request->params();
332
-    }
333
-
334
-
335
-    /**
336
-     * @param      $key
337
-     * @param      $value
338
-     * @param bool $override_ee
339
-     * @return    void
340
-     */
341
-    public function set($key, $value, $override_ee = false)
342
-    {
343
-        $this->request->set($key, $value, $override_ee);
344
-    }
345
-
346
-
347
-    /**
348
-     * @param      $key
349
-     * @param null $default
350
-     * @return    mixed
351
-     */
352
-    public function get($key, $default = null)
353
-    {
354
-        return $this->request->get($key, $default);
355
-    }
356
-
357
-
358
-    /**
359
-     * check if param exists
360
-     *
361
-     * @param $key
362
-     * @return    boolean
363
-     */
364
-    public function is_set($key)
365
-    {
366
-        return $this->request->is_set($key);
367
-    }
368
-
369
-
370
-    /**
371
-     * remove param
372
-     *
373
-     * @param $key
374
-     * @return    void
375
-     */
376
-    public function un_set($key)
377
-    {
378
-        $this->request->un_set($key);
379
-    }
15
+	/**
16
+	 * @var EE_Request $request
17
+	 */
18
+	private $request;
19
+
20
+	/**
21
+	 * @var array $_notice
22
+	 */
23
+	private $_notice = array();
24
+
25
+	/**
26
+	 * rendered output to be returned to WP
27
+	 *
28
+	 * @var string $_output
29
+	 */
30
+	private $_output = '';
31
+
32
+	/**
33
+	 * whether current request is via AJAX
34
+	 *
35
+	 * @var boolean $ajax
36
+	 */
37
+	public $ajax = false;
38
+
39
+	/**
40
+	 * whether current request is via AJAX from the frontend of the site
41
+	 *
42
+	 * @var boolean $front_ajax
43
+	 */
44
+	public $front_ajax = false;
45
+
46
+
47
+	/**
48
+	 * @param  EE_Request $request
49
+	 */
50
+	public function __construct(EE_Request $request)
51
+	{
52
+		$this->request = $request;
53
+		$this->ajax = $this->request->ajax;
54
+		$this->front_ajax = $this->request->front_ajax;
55
+		do_action('AHEE__EE_Request_Handler__construct__complete');
56
+	}
57
+
58
+
59
+	/**
60
+	 * @param WP $wp
61
+	 * @return void
62
+	 * @throws EE_Error
63
+	 * @throws ReflectionException
64
+	 */
65
+	public function parse_request($wp = null)
66
+	{
67
+		// if somebody forgot to provide us with WP, that's ok because its global
68
+		if (! $wp instanceof WP) {
69
+			global $wp;
70
+		}
71
+		$this->set_request_vars($wp);
72
+	}
73
+
74
+
75
+	/**
76
+	 * @param WP $wp
77
+	 * @return void
78
+	 * @throws EE_Error
79
+	 * @throws ReflectionException
80
+	 */
81
+	public function set_request_vars($wp = null)
82
+	{
83
+		if (! is_admin()) {
84
+			// set request post_id
85
+			$this->request->set('post_id', $this->get_post_id_from_request($wp));
86
+			// set request post name
87
+			$this->request->set('post_name', $this->get_post_name_from_request($wp));
88
+			// set request post_type
89
+			$this->request->set('post_type', $this->get_post_type_from_request($wp));
90
+			// true or false ? is this page being used by EE ?
91
+			$this->set_espresso_page();
92
+		}
93
+	}
94
+
95
+
96
+	/**
97
+	 * @param WP $wp
98
+	 * @return int
99
+	 */
100
+	public function get_post_id_from_request($wp = null)
101
+	{
102
+		if (! $wp instanceof WP) {
103
+			global $wp;
104
+		}
105
+		$post_id = null;
106
+		if (isset($wp->query_vars['p'])) {
107
+			$post_id = $wp->query_vars['p'];
108
+		}
109
+		if (! $post_id && isset($wp->query_vars['page_id'])) {
110
+			$post_id = $wp->query_vars['page_id'];
111
+		}
112
+		if (! $post_id && $wp->request !== null && is_numeric(basename($wp->request))) {
113
+			$post_id = basename($wp->request);
114
+		}
115
+		return $post_id;
116
+	}
117
+
118
+
119
+	/**
120
+	 * @param WP $wp
121
+	 * @return string
122
+	 */
123
+	public function get_post_name_from_request($wp = null)
124
+	{
125
+		if (! $wp instanceof WP) {
126
+			global $wp;
127
+		}
128
+		$post_name = null;
129
+		if (isset($wp->query_vars['name']) && ! empty($wp->query_vars['name'])) {
130
+			$post_name = $wp->query_vars['name'];
131
+		}
132
+		if (! $post_name && isset($wp->query_vars['pagename']) && ! empty($wp->query_vars['pagename'])) {
133
+			$post_name = $wp->query_vars['pagename'];
134
+		}
135
+		if (! $post_name && $wp->request !== null && ! empty($wp->request)) {
136
+			$possible_post_name = basename($wp->request);
137
+			if (! is_numeric($possible_post_name)) {
138
+				/** @type WPDB $wpdb */
139
+				global $wpdb;
140
+				$SQL =
141
+					"SELECT ID from {$wpdb->posts} WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND post_name=%s";
142
+				$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
143
+				if ($possible_post_name) {
144
+					$post_name = $possible_post_name;
145
+				}
146
+			}
147
+		}
148
+		if (! $post_name && $this->get('post_id')) {
149
+			/** @type WPDB $wpdb */
150
+			global $wpdb;
151
+			$SQL =
152
+				"SELECT post_name from {$wpdb->posts} WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND ID=%d";
153
+			$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->get('post_id')));
154
+			if ($possible_post_name) {
155
+				$post_name = $possible_post_name;
156
+			}
157
+		}
158
+		return $post_name;
159
+	}
160
+
161
+
162
+	/**
163
+	 * @param WP $wp
164
+	 * @return mixed
165
+	 */
166
+	public function get_post_type_from_request($wp = null)
167
+	{
168
+		if (! $wp instanceof WP) {
169
+			global $wp;
170
+		}
171
+		return isset($wp->query_vars['post_type'])
172
+			? $wp->query_vars['post_type']
173
+			: null;
174
+	}
175
+
176
+
177
+	/**
178
+	 * Just a helper method for getting the url for the displayed page.
179
+	 *
180
+	 * @param  WP $wp
181
+	 * @return string
182
+	 */
183
+	public function get_current_page_permalink($wp = null)
184
+	{
185
+		$post_id = $this->get_post_id_from_request($wp);
186
+		if ($post_id) {
187
+			$current_page_permalink = get_permalink($post_id);
188
+		} else {
189
+			if (! $wp instanceof WP) {
190
+				global $wp;
191
+			}
192
+			if ($wp->request) {
193
+				$current_page_permalink = site_url($wp->request);
194
+			} else {
195
+				$current_page_permalink = esc_url(site_url($_SERVER['REQUEST_URI']));
196
+			}
197
+		}
198
+		return $current_page_permalink;
199
+	}
200
+
201
+
202
+	/**
203
+	 * @return bool
204
+	 * @throws EE_Error
205
+	 * @throws ReflectionException
206
+	 */
207
+	public function test_for_espresso_page()
208
+	{
209
+		global $wp;
210
+		/** @type EE_CPT_Strategy $EE_CPT_Strategy */
211
+		$EE_CPT_Strategy = EE_Registry::instance()->load_core('CPT_Strategy');
212
+		$espresso_CPT_taxonomies = $EE_CPT_Strategy->get_CPT_taxonomies();
213
+		if (is_array($espresso_CPT_taxonomies)) {
214
+			foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
215
+				if (isset($wp->query_vars, $wp->query_vars[ $espresso_CPT_taxonomy ])) {
216
+					return true;
217
+				}
218
+			}
219
+		}
220
+		// load espresso CPT endpoints
221
+		$espresso_CPT_endpoints = $EE_CPT_Strategy->get_CPT_endpoints();
222
+		$post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
223
+		$post_types = (array) $this->get('post_type');
224
+		foreach ($post_types as $post_type) {
225
+			// was a post name passed ?
226
+			if (isset($post_type_CPT_endpoints[ $post_type ])) {
227
+				// kk we know this is an espresso page, but is it a specific post ?
228
+				if (! $this->get('post_name')) {
229
+					// there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
230
+					$post_name = isset($post_type_CPT_endpoints[ $this->get('post_type') ])
231
+						? $post_type_CPT_endpoints[ $this->get('post_type') ]
232
+						: '';
233
+					// if the post type matches on of our then set the endpoint
234
+					if ($post_name) {
235
+						$this->set('post_name', $post_name);
236
+					}
237
+				}
238
+				return true;
239
+			}
240
+		}
241
+		return false;
242
+	}
243
+
244
+	/**
245
+	 * @param $key
246
+	 * @param $value
247
+	 * @return    void
248
+	 */
249
+	public function set_notice($key, $value)
250
+	{
251
+		$this->_notice[ $key ] = $value;
252
+	}
253
+
254
+
255
+	/**
256
+	 * @param $key
257
+	 * @return    mixed
258
+	 */
259
+	public function get_notice($key)
260
+	{
261
+		return isset($this->_notice[ $key ])
262
+			? $this->_notice[ $key ]
263
+			: null;
264
+	}
265
+
266
+
267
+	/**
268
+	 * @param $string
269
+	 * @return void
270
+	 */
271
+	public function add_output($string)
272
+	{
273
+		$this->_output .= $string;
274
+	}
275
+
276
+
277
+	/**
278
+	 * @return string
279
+	 */
280
+	public function get_output()
281
+	{
282
+		return $this->_output;
283
+	}
284
+
285
+
286
+	/**
287
+	 * @param $item
288
+	 * @param $key
289
+	 */
290
+	public function sanitize_text_field_for_array_walk(&$item, &$key)
291
+	{
292
+		$item = strpos($item, 'email') !== false
293
+			? sanitize_email($item)
294
+			: sanitize_text_field($item);
295
+	}
296
+
297
+
298
+	/**
299
+	 * @param null|bool $value
300
+	 * @return void
301
+	 * @throws EE_Error
302
+	 * @throws ReflectionException
303
+	 */
304
+	public function set_espresso_page($value = null)
305
+	{
306
+		$this->request->set(
307
+			'is_espresso_page',
308
+			! empty($value)
309
+				? $value
310
+				: $this->test_for_espresso_page()
311
+		);
312
+	}
313
+
314
+
315
+	/**
316
+	 * @return    mixed
317
+	 */
318
+	public function is_espresso_page()
319
+	{
320
+		return $this->request->is_set('is_espresso_page');
321
+	}
322
+
323
+
324
+	/**
325
+	 * returns contents of $_REQUEST
326
+	 *
327
+	 * @return array
328
+	 */
329
+	public function params()
330
+	{
331
+		return $this->request->params();
332
+	}
333
+
334
+
335
+	/**
336
+	 * @param      $key
337
+	 * @param      $value
338
+	 * @param bool $override_ee
339
+	 * @return    void
340
+	 */
341
+	public function set($key, $value, $override_ee = false)
342
+	{
343
+		$this->request->set($key, $value, $override_ee);
344
+	}
345
+
346
+
347
+	/**
348
+	 * @param      $key
349
+	 * @param null $default
350
+	 * @return    mixed
351
+	 */
352
+	public function get($key, $default = null)
353
+	{
354
+		return $this->request->get($key, $default);
355
+	}
356
+
357
+
358
+	/**
359
+	 * check if param exists
360
+	 *
361
+	 * @param $key
362
+	 * @return    boolean
363
+	 */
364
+	public function is_set($key)
365
+	{
366
+		return $this->request->is_set($key);
367
+	}
368
+
369
+
370
+	/**
371
+	 * remove param
372
+	 *
373
+	 * @param $key
374
+	 * @return    void
375
+	 */
376
+	public function un_set($key)
377
+	{
378
+		$this->request->un_set($key);
379
+	}
380 380
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
     public function parse_request($wp = null)
66 66
     {
67 67
         // if somebody forgot to provide us with WP, that's ok because its global
68
-        if (! $wp instanceof WP) {
68
+        if ( ! $wp instanceof WP) {
69 69
             global $wp;
70 70
         }
71 71
         $this->set_request_vars($wp);
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
      */
81 81
     public function set_request_vars($wp = null)
82 82
     {
83
-        if (! is_admin()) {
83
+        if ( ! is_admin()) {
84 84
             // set request post_id
85 85
             $this->request->set('post_id', $this->get_post_id_from_request($wp));
86 86
             // set request post name
@@ -99,17 +99,17 @@  discard block
 block discarded – undo
99 99
      */
100 100
     public function get_post_id_from_request($wp = null)
101 101
     {
102
-        if (! $wp instanceof WP) {
102
+        if ( ! $wp instanceof WP) {
103 103
             global $wp;
104 104
         }
105 105
         $post_id = null;
106 106
         if (isset($wp->query_vars['p'])) {
107 107
             $post_id = $wp->query_vars['p'];
108 108
         }
109
-        if (! $post_id && isset($wp->query_vars['page_id'])) {
109
+        if ( ! $post_id && isset($wp->query_vars['page_id'])) {
110 110
             $post_id = $wp->query_vars['page_id'];
111 111
         }
112
-        if (! $post_id && $wp->request !== null && is_numeric(basename($wp->request))) {
112
+        if ( ! $post_id && $wp->request !== null && is_numeric(basename($wp->request))) {
113 113
             $post_id = basename($wp->request);
114 114
         }
115 115
         return $post_id;
@@ -122,19 +122,19 @@  discard block
 block discarded – undo
122 122
      */
123 123
     public function get_post_name_from_request($wp = null)
124 124
     {
125
-        if (! $wp instanceof WP) {
125
+        if ( ! $wp instanceof WP) {
126 126
             global $wp;
127 127
         }
128 128
         $post_name = null;
129 129
         if (isset($wp->query_vars['name']) && ! empty($wp->query_vars['name'])) {
130 130
             $post_name = $wp->query_vars['name'];
131 131
         }
132
-        if (! $post_name && isset($wp->query_vars['pagename']) && ! empty($wp->query_vars['pagename'])) {
132
+        if ( ! $post_name && isset($wp->query_vars['pagename']) && ! empty($wp->query_vars['pagename'])) {
133 133
             $post_name = $wp->query_vars['pagename'];
134 134
         }
135
-        if (! $post_name && $wp->request !== null && ! empty($wp->request)) {
135
+        if ( ! $post_name && $wp->request !== null && ! empty($wp->request)) {
136 136
             $possible_post_name = basename($wp->request);
137
-            if (! is_numeric($possible_post_name)) {
137
+            if ( ! is_numeric($possible_post_name)) {
138 138
                 /** @type WPDB $wpdb */
139 139
                 global $wpdb;
140 140
                 $SQL =
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
                 }
146 146
             }
147 147
         }
148
-        if (! $post_name && $this->get('post_id')) {
148
+        if ( ! $post_name && $this->get('post_id')) {
149 149
             /** @type WPDB $wpdb */
150 150
             global $wpdb;
151 151
             $SQL =
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
      */
166 166
     public function get_post_type_from_request($wp = null)
167 167
     {
168
-        if (! $wp instanceof WP) {
168
+        if ( ! $wp instanceof WP) {
169 169
             global $wp;
170 170
         }
171 171
         return isset($wp->query_vars['post_type'])
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
         if ($post_id) {
187 187
             $current_page_permalink = get_permalink($post_id);
188 188
         } else {
189
-            if (! $wp instanceof WP) {
189
+            if ( ! $wp instanceof WP) {
190 190
                 global $wp;
191 191
             }
192 192
             if ($wp->request) {
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
         $espresso_CPT_taxonomies = $EE_CPT_Strategy->get_CPT_taxonomies();
213 213
         if (is_array($espresso_CPT_taxonomies)) {
214 214
             foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
215
-                if (isset($wp->query_vars, $wp->query_vars[ $espresso_CPT_taxonomy ])) {
215
+                if (isset($wp->query_vars, $wp->query_vars[$espresso_CPT_taxonomy])) {
216 216
                     return true;
217 217
                 }
218 218
             }
@@ -223,12 +223,12 @@  discard block
 block discarded – undo
223 223
         $post_types = (array) $this->get('post_type');
224 224
         foreach ($post_types as $post_type) {
225 225
             // was a post name passed ?
226
-            if (isset($post_type_CPT_endpoints[ $post_type ])) {
226
+            if (isset($post_type_CPT_endpoints[$post_type])) {
227 227
                 // kk we know this is an espresso page, but is it a specific post ?
228
-                if (! $this->get('post_name')) {
228
+                if ( ! $this->get('post_name')) {
229 229
                     // there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
230
-                    $post_name = isset($post_type_CPT_endpoints[ $this->get('post_type') ])
231
-                        ? $post_type_CPT_endpoints[ $this->get('post_type') ]
230
+                    $post_name = isset($post_type_CPT_endpoints[$this->get('post_type')])
231
+                        ? $post_type_CPT_endpoints[$this->get('post_type')]
232 232
                         : '';
233 233
                     // if the post type matches on of our then set the endpoint
234 234
                     if ($post_name) {
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
      */
249 249
     public function set_notice($key, $value)
250 250
     {
251
-        $this->_notice[ $key ] = $value;
251
+        $this->_notice[$key] = $value;
252 252
     }
253 253
 
254 254
 
@@ -258,8 +258,8 @@  discard block
 block discarded – undo
258 258
      */
259 259
     public function get_notice($key)
260 260
     {
261
-        return isset($this->_notice[ $key ])
262
-            ? $this->_notice[ $key ]
261
+        return isset($this->_notice[$key])
262
+            ? $this->_notice[$key]
263 263
             : null;
264 264
     }
265 265
 
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +15 added lines, -13 removed lines patch added patch discarded remove patch
@@ -967,7 +967,7 @@  discard block
 block discarded – undo
967 967
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
968 968
      * foreign key to the WP_User table)
969 969
      *
970
-     * @return string|boolean string on success, boolean false when there is no
970
+     * @return string|false string on success, boolean false when there is no
971 971
      * foreign key to the WP_User table
972 972
      */
973 973
     public function wp_user_field_name()
@@ -1072,7 +1072,7 @@  discard block
 block discarded – undo
1072 1072
      *
1073 1073
      * @param array  $query_params      like EEM_Base::get_all's $query_params
1074 1074
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1075
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1075
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1076 1076
      *                                  fields on the model, and the models we joined to in the query. However, you can
1077 1077
      *                                  override this and set the select to "*", or a specific column name, like
1078 1078
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1486,7 +1486,7 @@  discard block
 block discarded – undo
1486 1486
      * @param string $field_name The name of the field the formats are being retrieved for.
1487 1487
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1488 1488
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1489
-     * @return array formats in an array with the date format first, and the time format last.
1489
+     * @return string[] formats in an array with the date format first, and the time format last.
1490 1490
      */
1491 1491
     public function get_formats_for($field_name, $pretty = false)
1492 1492
     {
@@ -1521,7 +1521,7 @@  discard block
 block discarded – undo
1521 1521
      *                                 be returned.
1522 1522
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1523 1523
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1524
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1524
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1525 1525
      *                                 exception is triggered.
1526 1526
      */
1527 1527
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1561,7 +1561,7 @@  discard block
 block discarded – undo
1561 1561
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1562 1562
      *                                format is
1563 1563
      *                                'U', this is ignored.
1564
-     * @return DateTime
1564
+     * @return string
1565 1565
      * @throws EE_Error
1566 1566
      */
1567 1567
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -2426,7 +2426,7 @@  discard block
 block discarded – undo
2426 2426
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2427 2427
      * EEM_Base::$_db_verification_level
2428 2428
      *
2429
-     * @param $wpdb_method
2429
+     * @param string $wpdb_method
2430 2430
      * @param $arguments_to_provide
2431 2431
      * @return string
2432 2432
      */
@@ -2550,6 +2550,7 @@  discard block
 block discarded – undo
2550 2550
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2551 2551
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2552 2552
      *                             because these will be inserted in any new rows created as well.
2553
+     * @param EE_Base_Class $id_or_obj
2553 2554
      */
2554 2555
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2555 2556
     {
@@ -2560,7 +2561,7 @@  discard block
 block discarded – undo
2560 2561
 
2561 2562
 
2562 2563
     /**
2563
-     * @param mixed           $id_or_obj
2564
+     * @param EE_Base_Class           $id_or_obj
2564 2565
      * @param string          $relationName
2565 2566
      * @param array           $where_query_params
2566 2567
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2601,7 +2602,7 @@  discard block
 block discarded – undo
2601 2602
      * However, if the model objects can't be deleted because of blocking related model objects, then
2602 2603
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2603 2604
      *
2604
-     * @param EE_Base_Class|int|string $id_or_obj
2605
+     * @param EE_Base_Class $id_or_obj
2605 2606
      * @param string                   $model_name
2606 2607
      * @param array                    $query_params
2607 2608
      * @return int how many deleted
@@ -2622,7 +2623,7 @@  discard block
 block discarded – undo
2622 2623
      * the model objects can't be hard deleted because of blocking related model objects,
2623 2624
      * just does a soft-delete on them instead.
2624 2625
      *
2625
-     * @param EE_Base_Class|int|string $id_or_obj
2626
+     * @param EE_Base_Class $id_or_obj
2626 2627
      * @param string                   $model_name
2627 2628
      * @param array                    $query_params
2628 2629
      * @return int how many deleted
@@ -2679,6 +2680,7 @@  discard block
 block discarded – undo
2679 2680
      * @param string $model_name   like 'Event', or 'Registration'
2680 2681
      * @param array  $query_params like EEM_Base::get_all's
2681 2682
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2683
+     * @param EE_Base_Class $id_or_obj
2682 2684
      * @return float
2683 2685
      * @throws EE_Error
2684 2686
      */
@@ -3639,7 +3641,7 @@  discard block
 block discarded – undo
3639 3641
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3640 3642
      * We should use default where conditions on related models when they requested to use default where conditions
3641 3643
      * on all models, or specifically just on other related models
3642
-     * @param      $default_where_conditions_value
3644
+     * @param      string $default_where_conditions_value
3643 3645
      * @param bool $for_this_model false means this is for OTHER related models
3644 3646
      * @return bool
3645 3647
      */
@@ -3677,7 +3679,7 @@  discard block
 block discarded – undo
3677 3679
      * where conditions.
3678 3680
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3679 3681
      * on this model or others
3680
-     * @param      $default_where_conditions_value
3682
+     * @param      string $default_where_conditions_value
3681 3683
      * @param bool $for_this_model false means this is for OTHER related models
3682 3684
      * @return bool
3683 3685
      */
@@ -4732,7 +4734,7 @@  discard block
 block discarded – undo
4732 4734
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4733 4735
      * Eg, on EE_Answer that would be ANS_ID field object
4734 4736
      *
4735
-     * @param $field_obj
4737
+     * @param EE_Model_Field_Base $field_obj
4736 4738
      * @return boolean
4737 4739
      */
4738 4740
     public function is_primary_key_field($field_obj)
@@ -5450,7 +5452,7 @@  discard block
 block discarded – undo
5450 5452
     /**
5451 5453
      * Read comments for assume_values_already_prepared_by_model_object()
5452 5454
      *
5453
-     * @return int
5455
+     * @return boolean
5454 5456
      */
5455 5457
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5456 5458
     {
Please login to merge, or discard this patch.
Indentation   +6342 added lines, -6342 removed lines patch added patch discarded remove patch
@@ -34,6348 +34,6348 @@
 block discarded – undo
34 34
 abstract class EEM_Base extends EE_Base implements ResettableInterface
35 35
 {
36 36
 
37
-    /**
38
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
-     * They almost always WILL NOT, but it's not necessarily a requirement.
41
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
-     *
43
-     * @var boolean
44
-     */
45
-    private $_values_already_prepared_by_model_object = 0;
46
-
47
-    /**
48
-     * when $_values_already_prepared_by_model_object equals this, we assume
49
-     * the data is just like form input that needs to have the model fields'
50
-     * prepare_for_set and prepare_for_use_in_db called on it
51
-     */
52
-    const not_prepared_by_model_object = 0;
53
-
54
-    /**
55
-     * when $_values_already_prepared_by_model_object equals this, we
56
-     * assume this value is coming from a model object and doesn't need to have
57
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
58
-     */
59
-    const prepared_by_model_object = 1;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the values are already to be used in the database (ie no processing is done
64
-     * on them by the model's fields)
65
-     */
66
-    const prepared_for_use_in_db = 2;
67
-
68
-
69
-    protected $singular_item = 'Item';
70
-
71
-    protected $plural_item   = 'Items';
72
-
73
-    /**
74
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
-     */
76
-    protected $_tables;
77
-
78
-    /**
79
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
-     *
83
-     * @var \EE_Model_Field_Base[][] $_fields
84
-     */
85
-    protected $_fields;
86
-
87
-    /**
88
-     * array of different kinds of relations
89
-     *
90
-     * @var \EE_Model_Relation_Base[] $_model_relations
91
-     */
92
-    protected $_model_relations;
93
-
94
-    /**
95
-     * @var \EE_Index[] $_indexes
96
-     */
97
-    protected $_indexes = array();
98
-
99
-    /**
100
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
101
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
-     * by setting the same columns as used in these queries in the query yourself.
103
-     *
104
-     * @var EE_Default_Where_Conditions
105
-     */
106
-    protected $_default_where_conditions_strategy;
107
-
108
-    /**
109
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
-     * This is particularly useful when you want something between 'none' and 'default'
111
-     *
112
-     * @var EE_Default_Where_Conditions
113
-     */
114
-    protected $_minimum_where_conditions_strategy;
115
-
116
-    /**
117
-     * String describing how to find the "owner" of this model's objects.
118
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
-     * But when there isn't, this indicates which related model, or transiently-related model,
120
-     * has the foreign key to the wp_users table.
121
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
-     * related to events, and events have a foreign key to wp_users.
123
-     * On EEM_Transaction, this would be 'Transaction.Event'
124
-     *
125
-     * @var string
126
-     */
127
-    protected $_model_chain_to_wp_user = '';
128
-
129
-    /**
130
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
-     * don't need it (particularly CPT models)
132
-     *
133
-     * @var bool
134
-     */
135
-    protected $_ignore_where_strategy = false;
136
-
137
-    /**
138
-     * String used in caps relating to this model. Eg, if the caps relating to this
139
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
-     *
141
-     * @var string. If null it hasn't been initialized yet. If false then we
142
-     * have indicated capabilities don't apply to this
143
-     */
144
-    protected $_caps_slug = null;
145
-
146
-    /**
147
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
-     * and next-level keys are capability names, and each's value is a
149
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
-     * they specify which context to use (ie, frontend, backend, edit or delete)
151
-     * and then each capability in the corresponding sub-array that they're missing
152
-     * adds the where conditions onto the query.
153
-     *
154
-     * @var array
155
-     */
156
-    protected $_cap_restrictions = array(
157
-        self::caps_read       => array(),
158
-        self::caps_read_admin => array(),
159
-        self::caps_edit       => array(),
160
-        self::caps_delete     => array(),
161
-    );
162
-
163
-    /**
164
-     * Array defining which cap restriction generators to use to create default
165
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
166
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
-     * automatically set this to false (not just null).
169
-     *
170
-     * @var EE_Restriction_Generator_Base[]
171
-     */
172
-    protected $_cap_restriction_generators = array();
173
-
174
-    /**
175
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
-     */
177
-    const caps_read       = 'read';
178
-
179
-    const caps_read_admin = 'read_admin';
180
-
181
-    const caps_edit       = 'edit';
182
-
183
-    const caps_delete     = 'delete';
184
-
185
-    /**
186
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
-     * maps to 'read' because when looking for relevant permissions we're going to use
189
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
190
-     *
191
-     * @var array
192
-     */
193
-    protected $_cap_contexts_to_cap_action_map = array(
194
-        self::caps_read       => 'read',
195
-        self::caps_read_admin => 'read',
196
-        self::caps_edit       => 'edit',
197
-        self::caps_delete     => 'delete',
198
-    );
199
-
200
-    /**
201
-     * Timezone
202
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
-     * EE_Datetime_Field data type will have access to it.
206
-     *
207
-     * @var string
208
-     */
209
-    protected $_timezone;
210
-
211
-
212
-    /**
213
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
-     * multisite.
215
-     *
216
-     * @var int
217
-     */
218
-    protected static $_model_query_blog_id;
219
-
220
-    /**
221
-     * A copy of _fields, except the array keys are the model names pointed to by
222
-     * the field
223
-     *
224
-     * @var EE_Model_Field_Base[]
225
-     */
226
-    private $_cache_foreign_key_to_fields = array();
227
-
228
-    /**
229
-     * Cached list of all the fields on the model, indexed by their name
230
-     *
231
-     * @var EE_Model_Field_Base[]
232
-     */
233
-    private $_cached_fields = null;
234
-
235
-    /**
236
-     * Cached list of all the fields on the model, except those that are
237
-     * marked as only pertinent to the database
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cached_fields_non_db_only = null;
242
-
243
-    /**
244
-     * A cached reference to the primary key for quick lookup
245
-     *
246
-     * @var EE_Model_Field_Base
247
-     */
248
-    private $_primary_key_field = null;
249
-
250
-    /**
251
-     * Flag indicating whether this model has a primary key or not
252
-     *
253
-     * @var boolean
254
-     */
255
-    protected $_has_primary_key_field = null;
256
-
257
-    /**
258
-     * Whether or not this model is based off a table in WP core only (CPTs should set
259
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
-     * This should be true for models that deal with data that should exist independent of EE.
261
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
263
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
265
-     * @var boolean
266
-     */
267
-    protected $_wp_core_model = false;
268
-
269
-    /**
270
-     *    List of valid operators that can be used for querying.
271
-     * The keys are all operators we'll accept, the values are the real SQL
272
-     * operators used
273
-     *
274
-     * @var array
275
-     */
276
-    protected $_valid_operators = array(
277
-        '='           => '=',
278
-        '<='          => '<=',
279
-        '<'           => '<',
280
-        '>='          => '>=',
281
-        '>'           => '>',
282
-        '!='          => '!=',
283
-        'LIKE'        => 'LIKE',
284
-        'like'        => 'LIKE',
285
-        'NOT_LIKE'    => 'NOT LIKE',
286
-        'not_like'    => 'NOT LIKE',
287
-        'NOT LIKE'    => 'NOT LIKE',
288
-        'not like'    => 'NOT LIKE',
289
-        'IN'          => 'IN',
290
-        'in'          => 'IN',
291
-        'NOT_IN'      => 'NOT IN',
292
-        'not_in'      => 'NOT IN',
293
-        'NOT IN'      => 'NOT IN',
294
-        'not in'      => 'NOT IN',
295
-        'between'     => 'BETWEEN',
296
-        'BETWEEN'     => 'BETWEEN',
297
-        'IS_NOT_NULL' => 'IS NOT NULL',
298
-        'is_not_null' => 'IS NOT NULL',
299
-        'IS NOT NULL' => 'IS NOT NULL',
300
-        'is not null' => 'IS NOT NULL',
301
-        'IS_NULL'     => 'IS NULL',
302
-        'is_null'     => 'IS NULL',
303
-        'IS NULL'     => 'IS NULL',
304
-        'is null'     => 'IS NULL',
305
-        'REGEXP'      => 'REGEXP',
306
-        'regexp'      => 'REGEXP',
307
-        'NOT_REGEXP'  => 'NOT REGEXP',
308
-        'not_regexp'  => 'NOT REGEXP',
309
-        'NOT REGEXP'  => 'NOT REGEXP',
310
-        'not regexp'  => 'NOT REGEXP',
311
-    );
312
-
313
-    /**
314
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
-     *
316
-     * @var array
317
-     */
318
-    protected $_in_style_operators = array('IN', 'NOT IN');
319
-
320
-    /**
321
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
-     * '12-31-2012'"
323
-     *
324
-     * @var array
325
-     */
326
-    protected $_between_style_operators = array('BETWEEN');
327
-
328
-    /**
329
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
-     * @var array
331
-     */
332
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
-    /**
334
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
-     * on a join table.
336
-     *
337
-     * @var array
338
-     */
339
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
-
341
-    /**
342
-     * Allowed values for $query_params['order'] for ordering in queries
343
-     *
344
-     * @var array
345
-     */
346
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
-
348
-    /**
349
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
351
-     *
352
-     * @var array
353
-     */
354
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
-
356
-    /**
357
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
359
-     *
360
-     * @var array
361
-     */
362
-    private $_allowed_query_params = array(
363
-        0,
364
-        'limit',
365
-        'order_by',
366
-        'group_by',
367
-        'having',
368
-        'force_join',
369
-        'order',
370
-        'on_join_limit',
371
-        'default_where_conditions',
372
-        'caps',
373
-        'extra_selects'
374
-    );
375
-
376
-    /**
377
-     * All the data types that can be used in $wpdb->prepare statements.
378
-     *
379
-     * @var array
380
-     */
381
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
-
383
-    /**
384
-     * @var EE_Registry $EE
385
-     */
386
-    protected $EE = null;
387
-
388
-
389
-    /**
390
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
-     *
392
-     * @var int
393
-     */
394
-    protected $_show_next_x_db_queries = 0;
395
-
396
-    /**
397
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
-     * WHERE, GROUP_BY, etc.
400
-     *
401
-     * @var CustomSelects
402
-     */
403
-    protected $_custom_selections = array();
404
-
405
-    /**
406
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
-     * caches every model object we've fetched from the DB on this request
408
-     *
409
-     * @var array
410
-     */
411
-    protected $_entity_map;
412
-
413
-    /**
414
-     * @var LoaderInterface $loader
415
-     */
416
-    private static $loader;
417
-
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error(
520
-                sprintf(
521
-                    __(
522
-                        '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.',
523
-                        'event_espresso'
524
-                    ),
525
-                    get_class($this)
526
-                )
527
-            );
528
-        }
529
-        /**
530
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
531
-         */
532
-        if (empty(EEM_Base::$_model_query_blog_id)) {
533
-            EEM_Base::set_model_query_blog_id();
534
-        }
535
-        /**
536
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
537
-         * just use EE_Register_Model_Extension
538
-         *
539
-         * @var EE_Table_Base[] $_tables
540
-         */
541
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
542
-        foreach ($this->_tables as $table_alias => $table_obj) {
543
-            /** @var $table_obj EE_Table_Base */
544
-            $table_obj->_construct_finalize_with_alias($table_alias);
545
-            if ($table_obj instanceof EE_Secondary_Table) {
546
-                /** @var $table_obj EE_Secondary_Table */
547
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
548
-            }
549
-        }
550
-        /**
551
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
552
-         * EE_Register_Model_Extension
553
-         *
554
-         * @param EE_Model_Field_Base[] $_fields
555
-         */
556
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
557
-        $this->_invalidate_field_caches();
558
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
559
-            if (! array_key_exists($table_alias, $this->_tables)) {
560
-                throw new EE_Error(sprintf(__(
561
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
562
-                    'event_espresso'
563
-                ), $table_alias, implode(",", $this->_fields)));
564
-            }
565
-            foreach ($fields_for_table as $field_name => $field_obj) {
566
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
-                // primary key field base has a slightly different _construct_finalize
568
-                /** @var $field_obj EE_Model_Field_Base */
569
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
-            }
571
-        }
572
-        // everything is related to Extra_Meta
573
-        if (get_class($this) !== 'EEM_Extra_Meta') {
574
-            // make extra meta related to everything, but don't block deleting things just
575
-            // because they have related extra meta info. For now just orphan those extra meta
576
-            // in the future we should automatically delete them
577
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        // and change logs
580
-        if (get_class($this) !== 'EEM_Change_Log') {
581
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
-        }
583
-        /**
584
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
-         * EE_Register_Model_Extension
586
-         *
587
-         * @param EE_Model_Relation_Base[] $_model_relations
588
-         */
589
-        $this->_model_relations = (array) apply_filters(
590
-            'FHEE__' . get_class($this) . '__construct__model_relations',
591
-            $this->_model_relations
592
-        );
593
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
594
-            /** @var $relation_obj EE_Model_Relation_Base */
595
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
596
-        }
597
-        foreach ($this->_indexes as $index_name => $index_obj) {
598
-            /** @var $index_obj EE_Index */
599
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
600
-        }
601
-        $this->set_timezone($timezone);
602
-        // finalize default where condition strategy, or set default
603
-        if (! $this->_default_where_conditions_strategy) {
604
-            // nothing was set during child constructor, so set default
605
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
606
-        }
607
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
608
-        if (! $this->_minimum_where_conditions_strategy) {
609
-            // nothing was set during child constructor, so set default
610
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
611
-        }
612
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
613
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
614
-        // to indicate to NOT set it, set it to the logical default
615
-        if ($this->_caps_slug === null) {
616
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
617
-        }
618
-        // initialize the standard cap restriction generators if none were specified by the child constructor
619
-        if ($this->_cap_restriction_generators !== false) {
620
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
621
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
622
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
623
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
624
-                        new EE_Restriction_Generator_Protected(),
625
-                        $cap_context,
626
-                        $this
627
-                    );
628
-                }
629
-            }
630
-        }
631
-        // if there are cap restriction generators, use them to make the default cap restrictions
632
-        if ($this->_cap_restriction_generators !== false) {
633
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
634
-                if (! $generator_object) {
635
-                    continue;
636
-                }
637
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
638
-                    throw new EE_Error(
639
-                        sprintf(
640
-                            __(
641
-                                '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.',
642
-                                'event_espresso'
643
-                            ),
644
-                            $context,
645
-                            $this->get_this_model_name()
646
-                        )
647
-                    );
648
-                }
649
-                $action = $this->cap_action_for_context($context);
650
-                if (! $generator_object->construction_finalized()) {
651
-                    $generator_object->_construct_finalize($this, $action);
652
-                }
653
-            }
654
-        }
655
-        do_action('AHEE__' . get_class($this) . '__construct__end');
656
-    }
657
-
658
-
659
-
660
-    /**
661
-     * Used to set the $_model_query_blog_id static property.
662
-     *
663
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
664
-     *                      value for get_current_blog_id() will be used.
665
-     */
666
-    public static function set_model_query_blog_id($blog_id = 0)
667
-    {
668
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
669
-    }
670
-
671
-
672
-
673
-    /**
674
-     * Returns whatever is set as the internal $model_query_blog_id.
675
-     *
676
-     * @return int
677
-     */
678
-    public static function get_model_query_blog_id()
679
-    {
680
-        return EEM_Base::$_model_query_blog_id;
681
-    }
682
-
683
-
684
-
685
-    /**
686
-     * This function is a singleton method used to instantiate the Espresso_model object
687
-     *
688
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
689
-     *                                (and any incoming timezone data that gets saved).
690
-     *                                Note this just sends the timezone info to the date time model field objects.
691
-     *                                Default is NULL
692
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
693
-     * @return static (as in the concrete child class)
694
-     * @throws EE_Error
695
-     * @throws InvalidArgumentException
696
-     * @throws InvalidDataTypeException
697
-     * @throws InvalidInterfaceException
698
-     */
699
-    public static function instance($timezone = null)
700
-    {
701
-        // check if instance of Espresso_model already exists
702
-        if (! static::$_instance instanceof static) {
703
-            // instantiate Espresso_model
704
-            static::$_instance = new static(
705
-                $timezone,
706
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
707
-            );
708
-        }
709
-        // we might have a timezone set, let set_timezone decide what to do with it
710
-        static::$_instance->set_timezone($timezone);
711
-        // Espresso_model object
712
-        return static::$_instance;
713
-    }
714
-
715
-
716
-
717
-    /**
718
-     * resets the model and returns it
719
-     *
720
-     * @param null | string $timezone
721
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
722
-     * all its properties reset; if it wasn't instantiated, returns null)
723
-     * @throws EE_Error
724
-     * @throws ReflectionException
725
-     * @throws InvalidArgumentException
726
-     * @throws InvalidDataTypeException
727
-     * @throws InvalidInterfaceException
728
-     */
729
-    public static function reset($timezone = null)
730
-    {
731
-        if (static::$_instance instanceof EEM_Base) {
732
-            // let's try to NOT swap out the current instance for a new one
733
-            // because if someone has a reference to it, we can't remove their reference
734
-            // so it's best to keep using the same reference, but change the original object
735
-            // reset all its properties to their original values as defined in the class
736
-            $r = new ReflectionClass(get_class(static::$_instance));
737
-            $static_properties = $r->getStaticProperties();
738
-            foreach ($r->getDefaultProperties() as $property => $value) {
739
-                // don't set instance to null like it was originally,
740
-                // but it's static anyways, and we're ignoring static properties (for now at least)
741
-                if (! isset($static_properties[ $property ])) {
742
-                    static::$_instance->{$property} = $value;
743
-                }
744
-            }
745
-            // and then directly call its constructor again, like we would if we were creating a new one
746
-            static::$_instance->__construct(
747
-                $timezone,
748
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
749
-            );
750
-            return self::instance();
751
-        }
752
-        return null;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * @return LoaderInterface
759
-     * @throws InvalidArgumentException
760
-     * @throws InvalidDataTypeException
761
-     * @throws InvalidInterfaceException
762
-     */
763
-    private static function getLoader()
764
-    {
765
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
766
-            EEM_Base::$loader = LoaderFactory::getLoader();
767
-        }
768
-        return EEM_Base::$loader;
769
-    }
770
-
771
-
772
-
773
-    /**
774
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
775
-     *
776
-     * @param  boolean $translated return localized strings or JUST the array.
777
-     * @return array
778
-     * @throws EE_Error
779
-     * @throws InvalidArgumentException
780
-     * @throws InvalidDataTypeException
781
-     * @throws InvalidInterfaceException
782
-     */
783
-    public function status_array($translated = false)
784
-    {
785
-        if (! array_key_exists('Status', $this->_model_relations)) {
786
-            return array();
787
-        }
788
-        $model_name = $this->get_this_model_name();
789
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
790
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
791
-        $status_array = array();
792
-        foreach ($stati as $status) {
793
-            $status_array[ $status->ID() ] = $status->get('STS_code');
794
-        }
795
-        return $translated
796
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
797
-            : $status_array;
798
-    }
799
-
800
-
801
-
802
-    /**
803
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
804
-     *
805
-     * @param array $query_params             {
806
-     * @var array $0 (where) array {
807
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
808
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
809
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
810
-     *                                        conditions based on related models (and even
811
-     *                                        models-related-to-related-models) prepend the model's name onto the field
812
-     *                                        name. Eg,
813
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
814
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
815
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
816
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
817
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
818
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
819
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
820
-     *                                        to Venues (even when each of those models actually consisted of two
821
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
822
-     *                                        just having
823
-     *                                        "Venue.VNU_ID", you could have
824
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
825
-     *                                        events are related to Registrations, which are related to Attendees). You
826
-     *                                        can take it even further with
827
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
828
-     *                                        (from the default of '='), change the value to an numerically-indexed
829
-     *                                        array, where the first item in the list is the operator. eg: array(
830
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
831
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
832
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
833
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
834
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
835
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
836
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
837
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
838
-     *                                        the value is a field, simply provide a third array item (true) to the
839
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
840
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
841
-     *                                        Note: you can also use related model field names like you would any other
842
-     *                                        field name. eg:
843
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
844
-     *                                        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__>' =>
845
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
846
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
847
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
848
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
849
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
850
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
851
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
852
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
853
-     *                                        "stick" until you specify an AND. eg
854
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
855
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
856
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
857
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
858
-     *                                        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 >>
859
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
860
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
861
-     *                                        too, eg:
862
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
863
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
864
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
865
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
866
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
867
-     *                                        the OFFSET, the 2nd is the LIMIT
868
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
869
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
870
-     *                                        following format array('on_join_limit'
871
-     *                                        => array( 'table_alias', array(1,2) ) ).
872
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
873
-     *                                        values are either 'ASC' or 'DESC'.
874
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
875
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
876
-     *                                        DESC..." respectively. Like the
877
-     *                                        'where' conditions, these fields can be on related models. Eg
878
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
879
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
880
-     *                                        Attendee, Price, Datetime, etc.)
881
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
882
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
883
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
884
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
885
-     *                                        order by the primary key. Eg,
886
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
887
-     *                                        //(will join with the Datetime model's table(s) and order by its field
888
-     *                                        DTT_EVT_start) or
889
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
890
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
891
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
892
-     *                                        'group_by'=>'VNU_ID', or
893
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
894
-     *                                        if no
895
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
896
-     *                                        model's primary key (or combined primary keys). This avoids some
897
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
898
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
899
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
900
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
901
-     *                                        results)
902
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
903
-     *                                        array where values are models to be joined in the query.Eg
904
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
905
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
906
-     *                                        probably only want to do this in hopes of increasing efficiency, as
907
-     *                                        related models which belongs to the current model
908
-     *                                        (ie, the current model has a foreign key to them, like how Registration
909
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
910
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
911
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
912
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
913
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
914
-     *                                        default where conditions set it to 'other_models_only'. If you only want
915
-     *                                        this model's default where conditions added to the query, use
916
-     *                                        'this_model_only'. If you want to use all default where conditions
917
-     *                                        (default), set to 'all'.
918
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
919
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
920
-     *                                        everything? Or should we only show the current user items they should be
921
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
922
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
923
-     *                                        }
924
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
925
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
926
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
927
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
928
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
929
-     *                                        array( array(
930
-     *                                        'OR'=>array(
931
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
932
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
933
-     *                                        )
934
-     *                                        ),
935
-     *                                        'limit'=>10,
936
-     *                                        'group_by'=>'TXN_ID'
937
-     *                                        ));
938
-     *                                        get all the answers to the question titled "shirt size" for event with id
939
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
940
-     *                                        'Question.QST_display_text'=>'shirt size',
941
-     *                                        'Registration.Event.EVT_ID'=>12
942
-     *                                        ),
943
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
944
-     *                                        ));
945
-     * @throws EE_Error
946
-     */
947
-    public function get_all($query_params = array())
948
-    {
949
-        if (isset($query_params['limit'])
950
-            && ! isset($query_params['group_by'])
951
-        ) {
952
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
953
-        }
954
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
955
-    }
956
-
957
-
958
-
959
-    /**
960
-     * Modifies the query parameters so we only get back model objects
961
-     * that "belong" to the current user
962
-     *
963
-     * @param array $query_params @see EEM_Base::get_all()
964
-     * @return array like EEM_Base::get_all
965
-     */
966
-    public function alter_query_params_to_only_include_mine($query_params = array())
967
-    {
968
-        $wp_user_field_name = $this->wp_user_field_name();
969
-        if ($wp_user_field_name) {
970
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
971
-        }
972
-        return $query_params;
973
-    }
974
-
975
-
976
-
977
-    /**
978
-     * Returns the name of the field's name that points to the WP_User table
979
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
980
-     * foreign key to the WP_User table)
981
-     *
982
-     * @return string|boolean string on success, boolean false when there is no
983
-     * foreign key to the WP_User table
984
-     */
985
-    public function wp_user_field_name()
986
-    {
987
-        try {
988
-            if (! empty($this->_model_chain_to_wp_user)) {
989
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
990
-                $last_model_name = end($models_to_follow_to_wp_users);
991
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
992
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
993
-            } else {
994
-                $model_with_fk_to_wp_users = $this;
995
-                $model_chain_to_wp_user = '';
996
-            }
997
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
998
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
999
-        } catch (EE_Error $e) {
1000
-            return false;
1001
-        }
1002
-    }
1003
-
1004
-
1005
-
1006
-    /**
1007
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
1008
-     * (or transiently-related model) has a foreign key to the wp_users table;
1009
-     * useful for finding if model objects of this type are 'owned' by the current user.
1010
-     * This is an empty string when the foreign key is on this model and when it isn't,
1011
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
1012
-     * (or transiently-related model)
1013
-     *
1014
-     * @return string
1015
-     */
1016
-    public function model_chain_to_wp_user()
1017
-    {
1018
-        return $this->_model_chain_to_wp_user;
1019
-    }
1020
-
1021
-
1022
-
1023
-    /**
1024
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1025
-     * like how registrations don't have a foreign key to wp_users, but the
1026
-     * events they are for are), or is unrelated to wp users.
1027
-     * generally available
1028
-     *
1029
-     * @return boolean
1030
-     */
1031
-    public function is_owned()
1032
-    {
1033
-        if ($this->model_chain_to_wp_user()) {
1034
-            return true;
1035
-        }
1036
-        try {
1037
-            $this->get_foreign_key_to('WP_User');
1038
-            return true;
1039
-        } catch (EE_Error $e) {
1040
-            return false;
1041
-        }
1042
-    }
1043
-
1044
-
1045
-    /**
1046
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1047
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1048
-     * the model)
1049
-     *
1050
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1051
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1052
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1053
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1054
-     *                                  override this and set the select to "*", or a specific column name, like
1055
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1056
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1057
-     *                                  the aliases used to refer to this selection, and values are to be
1058
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1059
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1060
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1061
-     * @throws EE_Error
1062
-     * @throws InvalidArgumentException
1063
-     */
1064
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1065
-    {
1066
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1067
-        ;
1068
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1069
-        $select_expressions = $columns_to_select === null
1070
-            ? $this->_construct_default_select_sql($model_query_info)
1071
-            : '';
1072
-        if ($this->_custom_selections instanceof CustomSelects) {
1073
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1074
-            $select_expressions .= $select_expressions
1075
-                ? ', ' . $custom_expressions
1076
-                : $custom_expressions;
1077
-        }
1078
-
1079
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1080
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1081
-    }
1082
-
1083
-
1084
-    /**
1085
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1086
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1087
-     * method of including extra select information.
1088
-     *
1089
-     * @param array             $query_params
1090
-     * @param null|array|string $columns_to_select
1091
-     * @return null|CustomSelects
1092
-     * @throws InvalidArgumentException
1093
-     */
1094
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1095
-    {
1096
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1097
-            return null;
1098
-        }
1099
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1100
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1101
-        return new CustomSelects($selects);
1102
-    }
1103
-
1104
-
1105
-
1106
-    /**
1107
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1108
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1109
-     * take care of joins, field preparation etc.
1110
-     *
1111
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1112
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1113
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1114
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1115
-     *                                  override this and set the select to "*", or a specific column name, like
1116
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1117
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1118
-     *                                  the aliases used to refer to this selection, and values are to be
1119
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1120
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1121
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1122
-     * @throws EE_Error
1123
-     */
1124
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1125
-    {
1126
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1127
-    }
1128
-
1129
-
1130
-
1131
-    /**
1132
-     * For creating a custom select statement
1133
-     *
1134
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1135
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1136
-     *                                 SQL, and 1=>is the datatype
1137
-     * @throws EE_Error
1138
-     * @return string
1139
-     */
1140
-    private function _construct_select_from_input($columns_to_select)
1141
-    {
1142
-        if (is_array($columns_to_select)) {
1143
-            $select_sql_array = array();
1144
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1145
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1146
-                    throw new EE_Error(
1147
-                        sprintf(
1148
-                            __(
1149
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1150
-                                'event_espresso'
1151
-                            ),
1152
-                            $selection_and_datatype,
1153
-                            $alias
1154
-                        )
1155
-                    );
1156
-                }
1157
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1158
-                    throw new EE_Error(
1159
-                        sprintf(
1160
-                            esc_html__(
1161
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1162
-                                'event_espresso'
1163
-                            ),
1164
-                            $selection_and_datatype[1],
1165
-                            $selection_and_datatype[0],
1166
-                            $alias,
1167
-                            implode(', ', $this->_valid_wpdb_data_types)
1168
-                        )
1169
-                    );
1170
-                }
1171
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1172
-            }
1173
-            $columns_to_select_string = implode(', ', $select_sql_array);
1174
-        } else {
1175
-            $columns_to_select_string = $columns_to_select;
1176
-        }
1177
-        return $columns_to_select_string;
1178
-    }
1179
-
1180
-
1181
-
1182
-    /**
1183
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1184
-     *
1185
-     * @return string
1186
-     * @throws EE_Error
1187
-     */
1188
-    public function primary_key_name()
1189
-    {
1190
-        return $this->get_primary_key_field()->get_name();
1191
-    }
1192
-
1193
-
1194
-
1195
-    /**
1196
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1197
-     * If there is no primary key on this model, $id is treated as primary key string
1198
-     *
1199
-     * @param mixed $id int or string, depending on the type of the model's primary key
1200
-     * @return EE_Base_Class
1201
-     */
1202
-    public function get_one_by_ID($id)
1203
-    {
1204
-        if ($this->get_from_entity_map($id)) {
1205
-            return $this->get_from_entity_map($id);
1206
-        }
1207
-        return $this->get_one(
1208
-            $this->alter_query_params_to_restrict_by_ID(
1209
-                $id,
1210
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1211
-            )
1212
-        );
1213
-    }
1214
-
1215
-
1216
-
1217
-    /**
1218
-     * Alters query parameters to only get items with this ID are returned.
1219
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1220
-     * or could just be a simple primary key ID
1221
-     *
1222
-     * @param int   $id
1223
-     * @param array $query_params
1224
-     * @return array of normal query params, @see EEM_Base::get_all
1225
-     * @throws EE_Error
1226
-     */
1227
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1228
-    {
1229
-        if (! isset($query_params[0])) {
1230
-            $query_params[0] = array();
1231
-        }
1232
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1233
-        if ($conditions_from_id === null) {
1234
-            $query_params[0][ $this->primary_key_name() ] = $id;
1235
-        } else {
1236
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1237
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1238
-        }
1239
-        return $query_params;
1240
-    }
1241
-
1242
-
1243
-
1244
-    /**
1245
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1246
-     * array. If no item is found, null is returned.
1247
-     *
1248
-     * @param array $query_params like EEM_Base's $query_params variable.
1249
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1250
-     * @throws EE_Error
1251
-     */
1252
-    public function get_one($query_params = array())
1253
-    {
1254
-        if (! is_array($query_params)) {
1255
-            EE_Error::doing_it_wrong(
1256
-                'EEM_Base::get_one',
1257
-                sprintf(
1258
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1259
-                    gettype($query_params)
1260
-                ),
1261
-                '4.6.0'
1262
-            );
1263
-            $query_params = array();
1264
-        }
1265
-        $query_params['limit'] = 1;
1266
-        $items = $this->get_all($query_params);
1267
-        if (empty($items)) {
1268
-            return null;
1269
-        }
1270
-        return array_shift($items);
1271
-    }
1272
-
1273
-
1274
-
1275
-    /**
1276
-     * Returns the next x number of items in sequence from the given value as
1277
-     * found in the database matching the given query conditions.
1278
-     *
1279
-     * @param mixed $current_field_value    Value used for the reference point.
1280
-     * @param null  $field_to_order_by      What field is used for the
1281
-     *                                      reference point.
1282
-     * @param int   $limit                  How many to return.
1283
-     * @param array $query_params           Extra conditions on the query.
1284
-     * @param null  $columns_to_select      If left null, then an array of
1285
-     *                                      EE_Base_Class objects is returned,
1286
-     *                                      otherwise you can indicate just the
1287
-     *                                      columns you want returned.
1288
-     * @return EE_Base_Class[]|array
1289
-     * @throws EE_Error
1290
-     */
1291
-    public function next_x(
1292
-        $current_field_value,
1293
-        $field_to_order_by = null,
1294
-        $limit = 1,
1295
-        $query_params = array(),
1296
-        $columns_to_select = null
1297
-    ) {
1298
-        return $this->_get_consecutive(
1299
-            $current_field_value,
1300
-            '>',
1301
-            $field_to_order_by,
1302
-            $limit,
1303
-            $query_params,
1304
-            $columns_to_select
1305
-        );
1306
-    }
1307
-
1308
-
1309
-
1310
-    /**
1311
-     * Returns the previous x number of items in sequence from the given value
1312
-     * as found in the database matching the given query conditions.
1313
-     *
1314
-     * @param mixed $current_field_value    Value used for the reference point.
1315
-     * @param null  $field_to_order_by      What field is used for the
1316
-     *                                      reference point.
1317
-     * @param int   $limit                  How many to return.
1318
-     * @param array $query_params           Extra conditions on the query.
1319
-     * @param null  $columns_to_select      If left null, then an array of
1320
-     *                                      EE_Base_Class objects is returned,
1321
-     *                                      otherwise you can indicate just the
1322
-     *                                      columns you want returned.
1323
-     * @return EE_Base_Class[]|array
1324
-     * @throws EE_Error
1325
-     */
1326
-    public function previous_x(
1327
-        $current_field_value,
1328
-        $field_to_order_by = null,
1329
-        $limit = 1,
1330
-        $query_params = array(),
1331
-        $columns_to_select = null
1332
-    ) {
1333
-        return $this->_get_consecutive(
1334
-            $current_field_value,
1335
-            '<',
1336
-            $field_to_order_by,
1337
-            $limit,
1338
-            $query_params,
1339
-            $columns_to_select
1340
-        );
1341
-    }
1342
-
1343
-
1344
-
1345
-    /**
1346
-     * Returns the next item in sequence from the given value as found in the
1347
-     * database matching the given query conditions.
1348
-     *
1349
-     * @param mixed $current_field_value    Value used for the reference point.
1350
-     * @param null  $field_to_order_by      What field is used for the
1351
-     *                                      reference point.
1352
-     * @param array $query_params           Extra conditions on the query.
1353
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1354
-     *                                      object is returned, otherwise you
1355
-     *                                      can indicate just the columns you
1356
-     *                                      want and a single array indexed by
1357
-     *                                      the columns will be returned.
1358
-     * @return EE_Base_Class|null|array()
1359
-     * @throws EE_Error
1360
-     */
1361
-    public function next(
1362
-        $current_field_value,
1363
-        $field_to_order_by = null,
1364
-        $query_params = array(),
1365
-        $columns_to_select = null
1366
-    ) {
1367
-        $results = $this->_get_consecutive(
1368
-            $current_field_value,
1369
-            '>',
1370
-            $field_to_order_by,
1371
-            1,
1372
-            $query_params,
1373
-            $columns_to_select
1374
-        );
1375
-        return empty($results) ? null : reset($results);
1376
-    }
1377
-
1378
-
1379
-
1380
-    /**
1381
-     * Returns the previous item in sequence from the given value as found in
1382
-     * the database matching the given query conditions.
1383
-     *
1384
-     * @param mixed $current_field_value    Value used for the reference point.
1385
-     * @param null  $field_to_order_by      What field is used for the
1386
-     *                                      reference point.
1387
-     * @param array $query_params           Extra conditions on the query.
1388
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1389
-     *                                      object is returned, otherwise you
1390
-     *                                      can indicate just the columns you
1391
-     *                                      want and a single array indexed by
1392
-     *                                      the columns will be returned.
1393
-     * @return EE_Base_Class|null|array()
1394
-     * @throws EE_Error
1395
-     */
1396
-    public function previous(
1397
-        $current_field_value,
1398
-        $field_to_order_by = null,
1399
-        $query_params = array(),
1400
-        $columns_to_select = null
1401
-    ) {
1402
-        $results = $this->_get_consecutive(
1403
-            $current_field_value,
1404
-            '<',
1405
-            $field_to_order_by,
1406
-            1,
1407
-            $query_params,
1408
-            $columns_to_select
1409
-        );
1410
-        return empty($results) ? null : reset($results);
1411
-    }
1412
-
1413
-
1414
-
1415
-    /**
1416
-     * Returns the a consecutive number of items in sequence from the given
1417
-     * value as found in the database matching the given query conditions.
1418
-     *
1419
-     * @param mixed  $current_field_value   Value used for the reference point.
1420
-     * @param string $operand               What operand is used for the sequence.
1421
-     * @param string $field_to_order_by     What field is used for the reference point.
1422
-     * @param int    $limit                 How many to return.
1423
-     * @param array  $query_params          Extra conditions on the query.
1424
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1425
-     *                                      otherwise you can indicate just the columns you want returned.
1426
-     * @return EE_Base_Class[]|array
1427
-     * @throws EE_Error
1428
-     */
1429
-    protected function _get_consecutive(
1430
-        $current_field_value,
1431
-        $operand = '>',
1432
-        $field_to_order_by = null,
1433
-        $limit = 1,
1434
-        $query_params = array(),
1435
-        $columns_to_select = null
1436
-    ) {
1437
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1438
-        if (empty($field_to_order_by)) {
1439
-            if ($this->has_primary_key_field()) {
1440
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1441
-            } else {
1442
-                if (WP_DEBUG) {
1443
-                    throw new EE_Error(__(
1444
-                        '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).',
1445
-                        'event_espresso'
1446
-                    ));
1447
-                }
1448
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1449
-                return array();
1450
-            }
1451
-        }
1452
-        if (! is_array($query_params)) {
1453
-            EE_Error::doing_it_wrong(
1454
-                'EEM_Base::_get_consecutive',
1455
-                sprintf(
1456
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1457
-                    gettype($query_params)
1458
-                ),
1459
-                '4.6.0'
1460
-            );
1461
-            $query_params = array();
1462
-        }
1463
-        // let's add the where query param for consecutive look up.
1464
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1465
-        $query_params['limit'] = $limit;
1466
-        // set direction
1467
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1468
-        $query_params['order_by'] = $operand === '>'
1469
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1470
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1471
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1472
-        if (empty($columns_to_select)) {
1473
-            return $this->get_all($query_params);
1474
-        }
1475
-        // getting just the fields
1476
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1477
-    }
1478
-
1479
-
1480
-
1481
-    /**
1482
-     * This sets the _timezone property after model object has been instantiated.
1483
-     *
1484
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1485
-     */
1486
-    public function set_timezone($timezone)
1487
-    {
1488
-        if ($timezone !== null) {
1489
-            $this->_timezone = $timezone;
1490
-        }
1491
-        // note we need to loop through relations and set the timezone on those objects as well.
1492
-        foreach ($this->_model_relations as $relation) {
1493
-            $relation->set_timezone($timezone);
1494
-        }
1495
-        // and finally we do the same for any datetime fields
1496
-        foreach ($this->_fields as $field) {
1497
-            if ($field instanceof EE_Datetime_Field) {
1498
-                $field->set_timezone($timezone);
1499
-            }
1500
-        }
1501
-    }
1502
-
1503
-
1504
-
1505
-    /**
1506
-     * This just returns whatever is set for the current timezone.
1507
-     *
1508
-     * @access public
1509
-     * @return string
1510
-     */
1511
-    public function get_timezone()
1512
-    {
1513
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1514
-        if (empty($this->_timezone)) {
1515
-            foreach ($this->_fields as $field) {
1516
-                if ($field instanceof EE_Datetime_Field) {
1517
-                    $this->set_timezone($field->get_timezone());
1518
-                    break;
1519
-                }
1520
-            }
1521
-        }
1522
-        // if timezone STILL empty then return the default timezone for the site.
1523
-        if (empty($this->_timezone)) {
1524
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1525
-        }
1526
-        return $this->_timezone;
1527
-    }
1528
-
1529
-
1530
-
1531
-    /**
1532
-     * This returns the date formats set for the given field name and also ensures that
1533
-     * $this->_timezone property is set correctly.
1534
-     *
1535
-     * @since 4.6.x
1536
-     * @param string $field_name The name of the field the formats are being retrieved for.
1537
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1538
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1539
-     * @return array formats in an array with the date format first, and the time format last.
1540
-     */
1541
-    public function get_formats_for($field_name, $pretty = false)
1542
-    {
1543
-        $field_settings = $this->field_settings_for($field_name);
1544
-        // if not a valid EE_Datetime_Field then throw error
1545
-        if (! $field_settings instanceof EE_Datetime_Field) {
1546
-            throw new EE_Error(sprintf(__(
1547
-                '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.',
1548
-                'event_espresso'
1549
-            ), $field_name));
1550
-        }
1551
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1552
-        // the field.
1553
-        $this->_timezone = $field_settings->get_timezone();
1554
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1555
-    }
1556
-
1557
-
1558
-
1559
-    /**
1560
-     * This returns the current time in a format setup for a query on this model.
1561
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1562
-     * it will return:
1563
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1564
-     *  NOW
1565
-     *  - or a unix timestamp (equivalent to time())
1566
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1567
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1568
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1569
-     * @since 4.6.x
1570
-     * @param string $field_name       The field the current time is needed for.
1571
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1572
-     *                                 formatted string matching the set format for the field in the set timezone will
1573
-     *                                 be returned.
1574
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1575
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1576
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1577
-     *                                 exception is triggered.
1578
-     */
1579
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1580
-    {
1581
-        $formats = $this->get_formats_for($field_name);
1582
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1583
-        if ($timestamp) {
1584
-            return $DateTime->format('U');
1585
-        }
1586
-        // not returning timestamp, so return formatted string in timezone.
1587
-        switch ($what) {
1588
-            case 'time':
1589
-                return $DateTime->format($formats[1]);
1590
-                break;
1591
-            case 'date':
1592
-                return $DateTime->format($formats[0]);
1593
-                break;
1594
-            default:
1595
-                return $DateTime->format(implode(' ', $formats));
1596
-                break;
1597
-        }
1598
-    }
1599
-
1600
-
1601
-
1602
-    /**
1603
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1604
-     * for the model are.  Returns a DateTime object.
1605
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1606
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1607
-     * ignored.
1608
-     *
1609
-     * @param string $field_name      The field being setup.
1610
-     * @param string $timestring      The date time string being used.
1611
-     * @param string $incoming_format The format for the time string.
1612
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1613
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1614
-     *                                format is
1615
-     *                                'U', this is ignored.
1616
-     * @return DateTime
1617
-     * @throws EE_Error
1618
-     */
1619
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1620
-    {
1621
-        // just using this to ensure the timezone is set correctly internally
1622
-        $this->get_formats_for($field_name);
1623
-        // load EEH_DTT_Helper
1624
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1625
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1626
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1627
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1628
-    }
1629
-
1630
-
1631
-
1632
-    /**
1633
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1634
-     *
1635
-     * @return EE_Table_Base[]
1636
-     */
1637
-    public function get_tables()
1638
-    {
1639
-        return $this->_tables;
1640
-    }
1641
-
1642
-
1643
-
1644
-    /**
1645
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1646
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1647
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1648
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1649
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1650
-     * model object with EVT_ID = 1
1651
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1652
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1653
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1654
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1655
-     * are not specified)
1656
-     *
1657
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1658
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1659
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1660
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1661
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1662
-     *                                         ID=34, we'd use this method as follows:
1663
-     *                                         EEM_Transaction::instance()->update(
1664
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1665
-     *                                         array(array('TXN_ID'=>34)));
1666
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1667
-     *                                         in client code into what's expected to be stored on each field. Eg,
1668
-     *                                         consider updating Question's QST_admin_label field is of type
1669
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1670
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1671
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1672
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1673
-     *                                         TRUE, it is assumed that you've already called
1674
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1675
-     *                                         malicious javascript. However, if
1676
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1677
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1678
-     *                                         and every other field, before insertion. We provide this parameter
1679
-     *                                         because model objects perform their prepare_for_set function on all
1680
-     *                                         their values, and so don't need to be called again (and in many cases,
1681
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1682
-     *                                         prepare_for_set method...)
1683
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1684
-     *                                         in this model's entity map according to $fields_n_values that match
1685
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1686
-     *                                         by setting this to FALSE, but be aware that model objects being used
1687
-     *                                         could get out-of-sync with the database
1688
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1689
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1690
-     *                                         bad)
1691
-     * @throws EE_Error
1692
-     */
1693
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1694
-    {
1695
-        if (! is_array($query_params)) {
1696
-            EE_Error::doing_it_wrong(
1697
-                'EEM_Base::update',
1698
-                sprintf(
1699
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1700
-                    gettype($query_params)
1701
-                ),
1702
-                '4.6.0'
1703
-            );
1704
-            $query_params = array();
1705
-        }
1706
-        /**
1707
-         * Action called before a model update call has been made.
1708
-         *
1709
-         * @param EEM_Base $model
1710
-         * @param array    $fields_n_values the updated fields and their new values
1711
-         * @param array    $query_params    @see EEM_Base::get_all()
1712
-         */
1713
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1714
-        /**
1715
-         * Filters the fields about to be updated given the query parameters. You can provide the
1716
-         * $query_params to $this->get_all() to find exactly which records will be updated
1717
-         *
1718
-         * @param array    $fields_n_values fields and their new values
1719
-         * @param EEM_Base $model           the model being queried
1720
-         * @param array    $query_params    see EEM_Base::get_all()
1721
-         */
1722
-        $fields_n_values = (array) apply_filters(
1723
-            'FHEE__EEM_Base__update__fields_n_values',
1724
-            $fields_n_values,
1725
-            $this,
1726
-            $query_params
1727
-        );
1728
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1729
-        // to do that, for each table, verify that it's PK isn't null.
1730
-        $tables = $this->get_tables();
1731
-        // 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
1732
-        // NOTE: we should make this code more efficient by NOT querying twice
1733
-        // before the real update, but that needs to first go through ALPHA testing
1734
-        // as it's dangerous. says Mike August 8 2014
1735
-        // we want to make sure the default_where strategy is ignored
1736
-        $this->_ignore_where_strategy = true;
1737
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1738
-        foreach ($wpdb_select_results as $wpdb_result) {
1739
-            // type cast stdClass as array
1740
-            $wpdb_result = (array) $wpdb_result;
1741
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1742
-            if ($this->has_primary_key_field()) {
1743
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1744
-            } else {
1745
-                // 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)
1746
-                $main_table_pk_value = null;
1747
-            }
1748
-            // 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
1749
-            // 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
1750
-            if (count($tables) > 1) {
1751
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1752
-                // in that table, and so we'll want to insert one
1753
-                foreach ($tables as $table_obj) {
1754
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1755
-                    // if there is no private key for this table on the results, it means there's no entry
1756
-                    // in this table, right? so insert a row in the current table, using any fields available
1757
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1758
-                           && $wpdb_result[ $this_table_pk_column ])
1759
-                    ) {
1760
-                        $success = $this->_insert_into_specific_table(
1761
-                            $table_obj,
1762
-                            $fields_n_values,
1763
-                            $main_table_pk_value
1764
-                        );
1765
-                        // if we died here, report the error
1766
-                        if (! $success) {
1767
-                            return false;
1768
-                        }
1769
-                    }
1770
-                }
1771
-            }
1772
-            //              //and now check that if we have cached any models by that ID on the model, that
1773
-            //              //they also get updated properly
1774
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1775
-            //              if( $model_object ){
1776
-            //                  foreach( $fields_n_values as $field => $value ){
1777
-            //                      $model_object->set($field, $value);
1778
-            // let's make sure default_where strategy is followed now
1779
-            $this->_ignore_where_strategy = false;
1780
-        }
1781
-        // if we want to keep model objects in sync, AND
1782
-        // if this wasn't called from a model object (to update itself)
1783
-        // then we want to make sure we keep all the existing
1784
-        // model objects in sync with the db
1785
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1786
-            if ($this->has_primary_key_field()) {
1787
-                $model_objs_affected_ids = $this->get_col($query_params);
1788
-            } else {
1789
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1790
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1791
-                $model_objs_affected_ids = array();
1792
-                foreach ($models_affected_key_columns as $row) {
1793
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1794
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1795
-                }
1796
-            }
1797
-            if (! $model_objs_affected_ids) {
1798
-                // wait wait wait- if nothing was affected let's stop here
1799
-                return 0;
1800
-            }
1801
-            foreach ($model_objs_affected_ids as $id) {
1802
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1803
-                if ($model_obj_in_entity_map) {
1804
-                    foreach ($fields_n_values as $field => $new_value) {
1805
-                        $model_obj_in_entity_map->set($field, $new_value);
1806
-                    }
1807
-                }
1808
-            }
1809
-            // if there is a primary key on this model, we can now do a slight optimization
1810
-            if ($this->has_primary_key_field()) {
1811
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1812
-                $query_params = array(
1813
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1814
-                    'limit'                    => count($model_objs_affected_ids),
1815
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1816
-                );
1817
-            }
1818
-        }
1819
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1820
-        $SQL = "UPDATE "
1821
-               . $model_query_info->get_full_join_sql()
1822
-               . " SET "
1823
-               . $this->_construct_update_sql($fields_n_values)
1824
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1825
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1826
-        /**
1827
-         * Action called after a model update call has been made.
1828
-         *
1829
-         * @param EEM_Base $model
1830
-         * @param array    $fields_n_values the updated fields and their new values
1831
-         * @param array    $query_params    @see EEM_Base::get_all()
1832
-         * @param int      $rows_affected
1833
-         */
1834
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1835
-        return $rows_affected;// how many supposedly got updated
1836
-    }
1837
-
1838
-
1839
-
1840
-    /**
1841
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1842
-     * are teh values of the field specified (or by default the primary key field)
1843
-     * that matched the query params. Note that you should pass the name of the
1844
-     * model FIELD, not the database table's column name.
1845
-     *
1846
-     * @param array  $query_params @see EEM_Base::get_all()
1847
-     * @param string $field_to_select
1848
-     * @return array just like $wpdb->get_col()
1849
-     * @throws EE_Error
1850
-     */
1851
-    public function get_col($query_params = array(), $field_to_select = null)
1852
-    {
1853
-        if ($field_to_select) {
1854
-            $field = $this->field_settings_for($field_to_select);
1855
-        } elseif ($this->has_primary_key_field()) {
1856
-            $field = $this->get_primary_key_field();
1857
-        } else {
1858
-            // no primary key, just grab the first column
1859
-            $field = reset($this->field_settings());
1860
-        }
1861
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1862
-        $select_expressions = $field->get_qualified_column();
1863
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1864
-        return $this->_do_wpdb_query('get_col', array($SQL));
1865
-    }
1866
-
1867
-
1868
-
1869
-    /**
1870
-     * Returns a single column value for a single row from the database
1871
-     *
1872
-     * @param array  $query_params    @see EEM_Base::get_all()
1873
-     * @param string $field_to_select @see EEM_Base::get_col()
1874
-     * @return string
1875
-     * @throws EE_Error
1876
-     */
1877
-    public function get_var($query_params = array(), $field_to_select = null)
1878
-    {
1879
-        $query_params['limit'] = 1;
1880
-        $col = $this->get_col($query_params, $field_to_select);
1881
-        if (! empty($col)) {
1882
-            return reset($col);
1883
-        }
1884
-        return null;
1885
-    }
1886
-
1887
-
1888
-
1889
-    /**
1890
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1891
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1892
-     * injection, but currently no further filtering is done
1893
-     *
1894
-     * @global      $wpdb
1895
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1896
-     *                               be updated to in the DB
1897
-     * @return string of SQL
1898
-     * @throws EE_Error
1899
-     */
1900
-    public function _construct_update_sql($fields_n_values)
1901
-    {
1902
-        /** @type WPDB $wpdb */
1903
-        global $wpdb;
1904
-        $cols_n_values = array();
1905
-        foreach ($fields_n_values as $field_name => $value) {
1906
-            $field_obj = $this->field_settings_for($field_name);
1907
-            // if the value is NULL, we want to assign the value to that.
1908
-            // wpdb->prepare doesn't really handle that properly
1909
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1910
-            $value_sql = $prepared_value === null ? 'NULL'
1911
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1912
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1913
-        }
1914
-        return implode(",", $cols_n_values);
1915
-    }
1916
-
1917
-
1918
-
1919
-    /**
1920
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1921
-     * Performs a HARD delete, meaning the database row should always be removed,
1922
-     * not just have a flag field on it switched
1923
-     * Wrapper for EEM_Base::delete_permanently()
1924
-     *
1925
-     * @param mixed $id
1926
-     * @param boolean $allow_blocking
1927
-     * @return int the number of rows deleted
1928
-     * @throws EE_Error
1929
-     */
1930
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1931
-    {
1932
-        return $this->delete_permanently(
1933
-            array(
1934
-                array($this->get_primary_key_field()->get_name() => $id),
1935
-                'limit' => 1,
1936
-            ),
1937
-            $allow_blocking
1938
-        );
1939
-    }
1940
-
1941
-
1942
-
1943
-    /**
1944
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1945
-     * Wrapper for EEM_Base::delete()
1946
-     *
1947
-     * @param mixed $id
1948
-     * @param boolean $allow_blocking
1949
-     * @return int the number of rows deleted
1950
-     * @throws EE_Error
1951
-     */
1952
-    public function delete_by_ID($id, $allow_blocking = true)
1953
-    {
1954
-        return $this->delete(
1955
-            array(
1956
-                array($this->get_primary_key_field()->get_name() => $id),
1957
-                'limit' => 1,
1958
-            ),
1959
-            $allow_blocking
1960
-        );
1961
-    }
1962
-
1963
-
1964
-
1965
-    /**
1966
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1967
-     * meaning if the model has a field that indicates its been "trashed" or
1968
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1969
-     *
1970
-     * @see EEM_Base::delete_permanently
1971
-     * @param array   $query_params
1972
-     * @param boolean $allow_blocking
1973
-     * @return int how many rows got deleted
1974
-     * @throws EE_Error
1975
-     */
1976
-    public function delete($query_params, $allow_blocking = true)
1977
-    {
1978
-        return $this->delete_permanently($query_params, $allow_blocking);
1979
-    }
1980
-
1981
-
1982
-
1983
-    /**
1984
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1985
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1986
-     * as archived, not actually deleted
1987
-     *
1988
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1989
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1990
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1991
-     *                                deletes regardless of other objects which may depend on it. Its generally
1992
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1993
-     *                                DB
1994
-     * @return int how many rows got deleted
1995
-     * @throws EE_Error
1996
-     */
1997
-    public function delete_permanently($query_params, $allow_blocking = true)
1998
-    {
1999
-        /**
2000
-         * Action called just before performing a real deletion query. You can use the
2001
-         * model and its $query_params to find exactly which items will be deleted
2002
-         *
2003
-         * @param EEM_Base $model
2004
-         * @param array    $query_params   @see EEM_Base::get_all()
2005
-         * @param boolean  $allow_blocking whether or not to allow related model objects
2006
-         *                                 to block (prevent) this deletion
2007
-         */
2008
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
2009
-        // some MySQL databases may be running safe mode, which may restrict
2010
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
2011
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
2012
-        // to delete them
2013
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
2014
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2015
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
2016
-            $columns_and_ids_for_deleting
2017
-        );
2018
-        /**
2019
-         * Allows client code to act on the items being deleted before the query is actually executed.
2020
-         *
2021
-         * @param EEM_Base $this  The model instance being acted on.
2022
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2023
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
2024
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
2025
-         *                                                  derived from the incoming query parameters.
2026
-         *                                                  @see details on the structure of this array in the phpdocs
2027
-         *                                                  for the `_get_ids_for_delete_method`
2028
-         *
2029
-         */
2030
-        do_action(
2031
-            'AHEE__EEM_Base__delete__before_query',
2032
-            $this,
2033
-            $query_params,
2034
-            $allow_blocking,
2035
-            $columns_and_ids_for_deleting
2036
-        );
2037
-        if ($deletion_where_query_part) {
2038
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2039
-            $table_aliases = array_keys($this->_tables);
2040
-            $SQL = "DELETE "
2041
-                   . implode(", ", $table_aliases)
2042
-                   . " FROM "
2043
-                   . $model_query_info->get_full_join_sql()
2044
-                   . " WHERE "
2045
-                   . $deletion_where_query_part;
2046
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2047
-        } else {
2048
-            $rows_deleted = 0;
2049
-        }
2050
-
2051
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2052
-        // there was no error with the delete query.
2053
-        if ($this->has_primary_key_field()
2054
-            && $rows_deleted !== false
2055
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2056
-        ) {
2057
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2058
-            foreach ($ids_for_removal as $id) {
2059
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2060
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2061
-                }
2062
-            }
2063
-
2064
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2065
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2066
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2067
-            // (although it is possible).
2068
-            // Note this can be skipped by using the provided filter and returning false.
2069
-            if (apply_filters(
2070
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2071
-                ! $this instanceof EEM_Extra_Meta,
2072
-                $this
2073
-            )) {
2074
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2075
-                    0 => array(
2076
-                        'EXM_type' => $this->get_this_model_name(),
2077
-                        'OBJ_ID'   => array(
2078
-                            'IN',
2079
-                            $ids_for_removal
2080
-                        )
2081
-                    )
2082
-                ));
2083
-            }
2084
-        }
2085
-
2086
-        /**
2087
-         * Action called just after performing a real deletion query. Although at this point the
2088
-         * items should have been deleted
2089
-         *
2090
-         * @param EEM_Base $model
2091
-         * @param array    $query_params @see EEM_Base::get_all()
2092
-         * @param int      $rows_deleted
2093
-         */
2094
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2095
-        return $rows_deleted;// how many supposedly got deleted
2096
-    }
2097
-
2098
-
2099
-
2100
-    /**
2101
-     * Checks all the relations that throw error messages when there are blocking related objects
2102
-     * for related model objects. If there are any related model objects on those relations,
2103
-     * adds an EE_Error, and return true
2104
-     *
2105
-     * @param EE_Base_Class|int $this_model_obj_or_id
2106
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2107
-     *                                                 should be ignored when determining whether there are related
2108
-     *                                                 model objects which block this model object's deletion. Useful
2109
-     *                                                 if you know A is related to B and are considering deleting A,
2110
-     *                                                 but want to see if A has any other objects blocking its deletion
2111
-     *                                                 before removing the relation between A and B
2112
-     * @return boolean
2113
-     * @throws EE_Error
2114
-     */
2115
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2116
-    {
2117
-        // first, if $ignore_this_model_obj was supplied, get its model
2118
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2119
-            $ignored_model = $ignore_this_model_obj->get_model();
2120
-        } else {
2121
-            $ignored_model = null;
2122
-        }
2123
-        // now check all the relations of $this_model_obj_or_id and see if there
2124
-        // are any related model objects blocking it?
2125
-        $is_blocked = false;
2126
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2127
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2128
-                // if $ignore_this_model_obj was supplied, then for the query
2129
-                // on that model needs to be told to ignore $ignore_this_model_obj
2130
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2131
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2132
-                        array(
2133
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2134
-                                '!=',
2135
-                                $ignore_this_model_obj->ID(),
2136
-                            ),
2137
-                        ),
2138
-                    ));
2139
-                } else {
2140
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2141
-                }
2142
-                if ($related_model_objects) {
2143
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2144
-                    $is_blocked = true;
2145
-                }
2146
-            }
2147
-        }
2148
-        return $is_blocked;
2149
-    }
2150
-
2151
-
2152
-    /**
2153
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2154
-     * @param array $row_results_for_deleting
2155
-     * @param bool  $allow_blocking
2156
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2157
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2158
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2159
-     *                 deleted. Example:
2160
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2161
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2162
-     *                 where each element is a group of columns and values that get deleted. Example:
2163
-     *                      array(
2164
-     *                          0 => array(
2165
-     *                              'Term_Relationship.object_id' => 1
2166
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2167
-     *                          ),
2168
-     *                          1 => array(
2169
-     *                              'Term_Relationship.object_id' => 1
2170
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2171
-     *                          )
2172
-     *                      )
2173
-     * @throws EE_Error
2174
-     */
2175
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2176
-    {
2177
-        $ids_to_delete_indexed_by_column = array();
2178
-        if ($this->has_primary_key_field()) {
2179
-            $primary_table = $this->_get_main_table();
2180
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2181
-            $other_tables = $this->_get_other_tables();
2182
-            $ids_to_delete_indexed_by_column = $query = array();
2183
-            foreach ($row_results_for_deleting as $item_to_delete) {
2184
-                // before we mark this item for deletion,
2185
-                // make sure there's no related entities blocking its deletion (if we're checking)
2186
-                if ($allow_blocking
2187
-                    && $this->delete_is_blocked_by_related_models(
2188
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2189
-                    )
2190
-                ) {
2191
-                    continue;
2192
-                }
2193
-                // primary table deletes
2194
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2195
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2196
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2197
-                }
2198
-            }
2199
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2200
-            $fields = $this->get_combined_primary_key_fields();
2201
-            foreach ($row_results_for_deleting as $item_to_delete) {
2202
-                $ids_to_delete_indexed_by_column_for_row = array();
2203
-                foreach ($fields as $cpk_field) {
2204
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2205
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2206
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2207
-                    }
2208
-                }
2209
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2210
-            }
2211
-        } else {
2212
-            // so there's no primary key and no combined key...
2213
-            // sorry, can't help you
2214
-            throw new EE_Error(
2215
-                sprintf(
2216
-                    __(
2217
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2218
-                        "event_espresso"
2219
-                    ),
2220
-                    get_class($this)
2221
-                )
2222
-            );
2223
-        }
2224
-        return $ids_to_delete_indexed_by_column;
2225
-    }
2226
-
2227
-
2228
-    /**
2229
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2230
-     * the corresponding query_part for the query performing the delete.
2231
-     *
2232
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2233
-     * @return string
2234
-     * @throws EE_Error
2235
-     */
2236
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2237
-    {
2238
-        $query_part = '';
2239
-        if (empty($ids_to_delete_indexed_by_column)) {
2240
-            return $query_part;
2241
-        } elseif ($this->has_primary_key_field()) {
2242
-            $query = array();
2243
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2244
-                // make sure we have unique $ids
2245
-                $ids = array_unique($ids);
2246
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2247
-            }
2248
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2249
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2250
-            $ways_to_identify_a_row = array();
2251
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2252
-                $values_for_each_combined_primary_key_for_a_row = array();
2253
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2254
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2255
-                }
2256
-                $ways_to_identify_a_row[] = '('
2257
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2258
-                                            . ')';
2259
-            }
2260
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2261
-        }
2262
-        return $query_part;
2263
-    }
2264
-
2265
-
2266
-
2267
-    /**
2268
-     * Gets the model field by the fully qualified name
2269
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2270
-     * @return EE_Model_Field_Base
2271
-     */
2272
-    public function get_field_by_column($qualified_column_name)
2273
-    {
2274
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2275
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2276
-                return $field_obj;
2277
-            }
2278
-        }
2279
-        throw new EE_Error(
2280
-            sprintf(
2281
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2282
-                $this->get_this_model_name(),
2283
-                $qualified_column_name
2284
-            )
2285
-        );
2286
-    }
2287
-
2288
-
2289
-
2290
-    /**
2291
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2292
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2293
-     * column
2294
-     *
2295
-     * @param array  $query_params   like EEM_Base::get_all's
2296
-     * @param string $field_to_count field on model to count by (not column name)
2297
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2298
-     *                               that by the setting $distinct to TRUE;
2299
-     * @return int
2300
-     * @throws EE_Error
2301
-     */
2302
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2303
-    {
2304
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2305
-        if ($field_to_count) {
2306
-            $field_obj = $this->field_settings_for($field_to_count);
2307
-            $column_to_count = $field_obj->get_qualified_column();
2308
-        } elseif ($this->has_primary_key_field()) {
2309
-            $pk_field_obj = $this->get_primary_key_field();
2310
-            $column_to_count = $pk_field_obj->get_qualified_column();
2311
-        } else {
2312
-            // there's no primary key
2313
-            // if we're counting distinct items, and there's no primary key,
2314
-            // we need to list out the columns for distinction;
2315
-            // otherwise we can just use star
2316
-            if ($distinct) {
2317
-                $columns_to_use = array();
2318
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2319
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2320
-                }
2321
-                $column_to_count = implode(',', $columns_to_use);
2322
-            } else {
2323
-                $column_to_count = '*';
2324
-            }
2325
-        }
2326
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2327
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2328
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2329
-    }
2330
-
2331
-
2332
-
2333
-    /**
2334
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2335
-     *
2336
-     * @param array  $query_params like EEM_Base::get_all
2337
-     * @param string $field_to_sum name of field (array key in $_fields array)
2338
-     * @return float
2339
-     * @throws EE_Error
2340
-     */
2341
-    public function sum($query_params, $field_to_sum = null)
2342
-    {
2343
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2344
-        if ($field_to_sum) {
2345
-            $field_obj = $this->field_settings_for($field_to_sum);
2346
-        } else {
2347
-            $field_obj = $this->get_primary_key_field();
2348
-        }
2349
-        $column_to_count = $field_obj->get_qualified_column();
2350
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2351
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2352
-        $data_type = $field_obj->get_wpdb_data_type();
2353
-        if ($data_type === '%d' || $data_type === '%s') {
2354
-            return (float) $return_value;
2355
-        }
2356
-        // must be %f
2357
-        return (float) $return_value;
2358
-    }
2359
-
2360
-
2361
-
2362
-    /**
2363
-     * Just calls the specified method on $wpdb with the given arguments
2364
-     * Consolidates a little extra error handling code
2365
-     *
2366
-     * @param string $wpdb_method
2367
-     * @param array  $arguments_to_provide
2368
-     * @throws EE_Error
2369
-     * @global wpdb  $wpdb
2370
-     * @return mixed
2371
-     */
2372
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2373
-    {
2374
-        // if we're in maintenance mode level 2, DON'T run any queries
2375
-        // because level 2 indicates the database needs updating and
2376
-        // is probably out of sync with the code
2377
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2378
-            throw new EE_Error(sprintf(__(
2379
-                "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.",
2380
-                "event_espresso"
2381
-            )));
2382
-        }
2383
-        /** @type WPDB $wpdb */
2384
-        global $wpdb;
2385
-        if (! method_exists($wpdb, $wpdb_method)) {
2386
-            throw new EE_Error(sprintf(__(
2387
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2388
-                'event_espresso'
2389
-            ), $wpdb_method));
2390
-        }
2391
-        if (WP_DEBUG) {
2392
-            $old_show_errors_value = $wpdb->show_errors;
2393
-            $wpdb->show_errors(false);
2394
-        }
2395
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2396
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2397
-        if (WP_DEBUG) {
2398
-            $wpdb->show_errors($old_show_errors_value);
2399
-            if (! empty($wpdb->last_error)) {
2400
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2401
-            }
2402
-            if ($result === false) {
2403
-                throw new EE_Error(sprintf(__(
2404
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2405
-                    'event_espresso'
2406
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2407
-            }
2408
-        } elseif ($result === false) {
2409
-            EE_Error::add_error(
2410
-                sprintf(
2411
-                    __(
2412
-                        '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"',
2413
-                        'event_espresso'
2414
-                    ),
2415
-                    $wpdb_method,
2416
-                    var_export($arguments_to_provide, true),
2417
-                    $wpdb->last_error
2418
-                ),
2419
-                __FILE__,
2420
-                __FUNCTION__,
2421
-                __LINE__
2422
-            );
2423
-        }
2424
-        return $result;
2425
-    }
2426
-
2427
-
2428
-
2429
-    /**
2430
-     * Attempts to run the indicated WPDB method with the provided arguments,
2431
-     * and if there's an error tries to verify the DB is correct. Uses
2432
-     * the static property EEM_Base::$_db_verification_level to determine whether
2433
-     * we should try to fix the EE core db, the addons, or just give up
2434
-     *
2435
-     * @param string $wpdb_method
2436
-     * @param array  $arguments_to_provide
2437
-     * @return mixed
2438
-     */
2439
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2440
-    {
2441
-        /** @type WPDB $wpdb */
2442
-        global $wpdb;
2443
-        $wpdb->last_error = null;
2444
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2445
-        // was there an error running the query? but we don't care on new activations
2446
-        // (we're going to setup the DB anyway on new activations)
2447
-        if (($result === false || ! empty($wpdb->last_error))
2448
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2449
-        ) {
2450
-            switch (EEM_Base::$_db_verification_level) {
2451
-                case EEM_Base::db_verified_none:
2452
-                    // let's double-check core's DB
2453
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2454
-                    break;
2455
-                case EEM_Base::db_verified_core:
2456
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2457
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2458
-                    break;
2459
-                case EEM_Base::db_verified_addons:
2460
-                    // ummmm... you in trouble
2461
-                    return $result;
2462
-                    break;
2463
-            }
2464
-            if (! empty($error_message)) {
2465
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2466
-                trigger_error($error_message);
2467
-            }
2468
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2469
-        }
2470
-        return $result;
2471
-    }
2472
-
2473
-
2474
-
2475
-    /**
2476
-     * Verifies the EE core database is up-to-date and records that we've done it on
2477
-     * EEM_Base::$_db_verification_level
2478
-     *
2479
-     * @param string $wpdb_method
2480
-     * @param array  $arguments_to_provide
2481
-     * @return string
2482
-     */
2483
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2484
-    {
2485
-        /** @type WPDB $wpdb */
2486
-        global $wpdb;
2487
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2488
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2489
-        $error_message = sprintf(
2490
-            __(
2491
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2492
-                'event_espresso'
2493
-            ),
2494
-            $wpdb->last_error,
2495
-            $wpdb_method,
2496
-            wp_json_encode($arguments_to_provide)
2497
-        );
2498
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2499
-        return $error_message;
2500
-    }
2501
-
2502
-
2503
-
2504
-    /**
2505
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2506
-     * EEM_Base::$_db_verification_level
2507
-     *
2508
-     * @param $wpdb_method
2509
-     * @param $arguments_to_provide
2510
-     * @return string
2511
-     */
2512
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2513
-    {
2514
-        /** @type WPDB $wpdb */
2515
-        global $wpdb;
2516
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2517
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2518
-        $error_message = sprintf(
2519
-            __(
2520
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2521
-                'event_espresso'
2522
-            ),
2523
-            $wpdb->last_error,
2524
-            $wpdb_method,
2525
-            wp_json_encode($arguments_to_provide)
2526
-        );
2527
-        EE_System::instance()->initialize_addons();
2528
-        return $error_message;
2529
-    }
2530
-
2531
-
2532
-
2533
-    /**
2534
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2535
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2536
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2537
-     * ..."
2538
-     *
2539
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2540
-     * @return string
2541
-     */
2542
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2543
-    {
2544
-        return " FROM " . $model_query_info->get_full_join_sql() .
2545
-               $model_query_info->get_where_sql() .
2546
-               $model_query_info->get_group_by_sql() .
2547
-               $model_query_info->get_having_sql() .
2548
-               $model_query_info->get_order_by_sql() .
2549
-               $model_query_info->get_limit_sql();
2550
-    }
2551
-
2552
-
2553
-
2554
-    /**
2555
-     * Set to easily debug the next X queries ran from this model.
2556
-     *
2557
-     * @param int $count
2558
-     */
2559
-    public function show_next_x_db_queries($count = 1)
2560
-    {
2561
-        $this->_show_next_x_db_queries = $count;
2562
-    }
2563
-
2564
-
2565
-
2566
-    /**
2567
-     * @param $sql_query
2568
-     */
2569
-    public function show_db_query_if_previously_requested($sql_query)
2570
-    {
2571
-        if ($this->_show_next_x_db_queries > 0) {
2572
-            echo $sql_query;
2573
-            $this->_show_next_x_db_queries--;
2574
-        }
2575
-    }
2576
-
2577
-
2578
-
2579
-    /**
2580
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2581
-     * There are the 3 cases:
2582
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2583
-     * $otherModelObject has no ID, it is first saved.
2584
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2585
-     * has no ID, it is first saved.
2586
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2587
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2588
-     * join table
2589
-     *
2590
-     * @param        EE_Base_Class                     /int $thisModelObject
2591
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2592
-     * @param string $relationName                     , key in EEM_Base::_relations
2593
-     *                                                 an attendee to a group, you also want to specify which role they
2594
-     *                                                 will have in that group. So you would use this parameter to
2595
-     *                                                 specify array('role-column-name'=>'role-id')
2596
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2597
-     *                                                 to for relation to methods that allow you to further specify
2598
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2599
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2600
-     *                                                 because these will be inserted in any new rows created as well.
2601
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2602
-     * @throws EE_Error
2603
-     */
2604
-    public function add_relationship_to(
2605
-        $id_or_obj,
2606
-        $other_model_id_or_obj,
2607
-        $relationName,
2608
-        $extra_join_model_fields_n_values = array()
2609
-    ) {
2610
-        $relation_obj = $this->related_settings_for($relationName);
2611
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2612
-    }
2613
-
2614
-
2615
-
2616
-    /**
2617
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2618
-     * There are the 3 cases:
2619
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2620
-     * error
2621
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2622
-     * an error
2623
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2624
-     *
2625
-     * @param        EE_Base_Class /int $id_or_obj
2626
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2627
-     * @param string $relationName key in EEM_Base::_relations
2628
-     * @return boolean of success
2629
-     * @throws EE_Error
2630
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2631
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2632
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2633
-     *                             because these will be inserted in any new rows created as well.
2634
-     */
2635
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2636
-    {
2637
-        $relation_obj = $this->related_settings_for($relationName);
2638
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2639
-    }
2640
-
2641
-
2642
-
2643
-    /**
2644
-     * @param mixed           $id_or_obj
2645
-     * @param string          $relationName
2646
-     * @param array           $where_query_params
2647
-     * @param EE_Base_Class[] objects to which relations were removed
2648
-     * @return \EE_Base_Class[]
2649
-     * @throws EE_Error
2650
-     */
2651
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2652
-    {
2653
-        $relation_obj = $this->related_settings_for($relationName);
2654
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2655
-    }
2656
-
2657
-
2658
-
2659
-    /**
2660
-     * Gets all the related items of the specified $model_name, using $query_params.
2661
-     * Note: by default, we remove the "default query params"
2662
-     * because we want to get even deleted items etc.
2663
-     *
2664
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2665
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2666
-     * @param array  $query_params like EEM_Base::get_all
2667
-     * @return EE_Base_Class[]
2668
-     * @throws EE_Error
2669
-     */
2670
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2671
-    {
2672
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2673
-        $relation_settings = $this->related_settings_for($model_name);
2674
-        return $relation_settings->get_all_related($model_obj, $query_params);
2675
-    }
2676
-
2677
-
2678
-
2679
-    /**
2680
-     * Deletes all the model objects across the relation indicated by $model_name
2681
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2682
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2683
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2684
-     *
2685
-     * @param EE_Base_Class|int|string $id_or_obj
2686
-     * @param string                   $model_name
2687
-     * @param array                    $query_params
2688
-     * @return int how many deleted
2689
-     * @throws EE_Error
2690
-     */
2691
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2692
-    {
2693
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2694
-        $relation_settings = $this->related_settings_for($model_name);
2695
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2696
-    }
2697
-
2698
-
2699
-
2700
-    /**
2701
-     * Hard deletes all the model objects across the relation indicated by $model_name
2702
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2703
-     * the model objects can't be hard deleted because of blocking related model objects,
2704
-     * just does a soft-delete on them instead.
2705
-     *
2706
-     * @param EE_Base_Class|int|string $id_or_obj
2707
-     * @param string                   $model_name
2708
-     * @param array                    $query_params
2709
-     * @return int how many deleted
2710
-     * @throws EE_Error
2711
-     */
2712
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2713
-    {
2714
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2715
-        $relation_settings = $this->related_settings_for($model_name);
2716
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2717
-    }
2718
-
2719
-
2720
-
2721
-    /**
2722
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2723
-     * unless otherwise specified in the $query_params
2724
-     *
2725
-     * @param        int             /EE_Base_Class $id_or_obj
2726
-     * @param string $model_name     like 'Event', or 'Registration'
2727
-     * @param array  $query_params   like EEM_Base::get_all's
2728
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2729
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2730
-     *                               that by the setting $distinct to TRUE;
2731
-     * @return int
2732
-     * @throws EE_Error
2733
-     */
2734
-    public function count_related(
2735
-        $id_or_obj,
2736
-        $model_name,
2737
-        $query_params = array(),
2738
-        $field_to_count = null,
2739
-        $distinct = false
2740
-    ) {
2741
-        $related_model = $this->get_related_model_obj($model_name);
2742
-        // we're just going to use the query params on the related model's normal get_all query,
2743
-        // except add a condition to say to match the current mod
2744
-        if (! isset($query_params['default_where_conditions'])) {
2745
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2746
-        }
2747
-        $this_model_name = $this->get_this_model_name();
2748
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2749
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2750
-        return $related_model->count($query_params, $field_to_count, $distinct);
2751
-    }
2752
-
2753
-
2754
-
2755
-    /**
2756
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2757
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2758
-     *
2759
-     * @param        int           /EE_Base_Class $id_or_obj
2760
-     * @param string $model_name   like 'Event', or 'Registration'
2761
-     * @param array  $query_params like EEM_Base::get_all's
2762
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2763
-     * @return float
2764
-     * @throws EE_Error
2765
-     */
2766
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2767
-    {
2768
-        $related_model = $this->get_related_model_obj($model_name);
2769
-        if (! is_array($query_params)) {
2770
-            EE_Error::doing_it_wrong(
2771
-                'EEM_Base::sum_related',
2772
-                sprintf(
2773
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2774
-                    gettype($query_params)
2775
-                ),
2776
-                '4.6.0'
2777
-            );
2778
-            $query_params = array();
2779
-        }
2780
-        // we're just going to use the query params on the related model's normal get_all query,
2781
-        // except add a condition to say to match the current mod
2782
-        if (! isset($query_params['default_where_conditions'])) {
2783
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2784
-        }
2785
-        $this_model_name = $this->get_this_model_name();
2786
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2787
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2788
-        return $related_model->sum($query_params, $field_to_sum);
2789
-    }
2790
-
2791
-
2792
-
2793
-    /**
2794
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2795
-     * $modelObject
2796
-     *
2797
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2798
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2799
-     * @param array               $query_params     like EEM_Base::get_all's
2800
-     * @return EE_Base_Class
2801
-     * @throws EE_Error
2802
-     */
2803
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2804
-    {
2805
-        $query_params['limit'] = 1;
2806
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2807
-        if ($results) {
2808
-            return array_shift($results);
2809
-        }
2810
-        return null;
2811
-    }
2812
-
2813
-
2814
-
2815
-    /**
2816
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2817
-     *
2818
-     * @return string
2819
-     */
2820
-    public function get_this_model_name()
2821
-    {
2822
-        return str_replace("EEM_", "", get_class($this));
2823
-    }
2824
-
2825
-
2826
-
2827
-    /**
2828
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2829
-     *
2830
-     * @return EE_Any_Foreign_Model_Name_Field
2831
-     * @throws EE_Error
2832
-     */
2833
-    public function get_field_containing_related_model_name()
2834
-    {
2835
-        foreach ($this->field_settings(true) as $field) {
2836
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2837
-                $field_with_model_name = $field;
2838
-            }
2839
-        }
2840
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2841
-            throw new EE_Error(sprintf(
2842
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2843
-                $this->get_this_model_name()
2844
-            ));
2845
-        }
2846
-        return $field_with_model_name;
2847
-    }
2848
-
2849
-
2850
-
2851
-    /**
2852
-     * Inserts a new entry into the database, for each table.
2853
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2854
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2855
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2856
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2857
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2858
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2859
-     *
2860
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2861
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2862
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2863
-     *                              of EEM_Base)
2864
-     * @return int new primary key on main table that got inserted
2865
-     * @throws EE_Error
2866
-     */
2867
-    public function insert($field_n_values)
2868
-    {
2869
-        /**
2870
-         * Filters the fields and their values before inserting an item using the models
2871
-         *
2872
-         * @param array    $fields_n_values keys are the fields and values are their new values
2873
-         * @param EEM_Base $model           the model used
2874
-         */
2875
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2876
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2877
-            $main_table = $this->_get_main_table();
2878
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2879
-            if ($new_id !== false) {
2880
-                foreach ($this->_get_other_tables() as $other_table) {
2881
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2882
-                }
2883
-            }
2884
-            /**
2885
-             * Done just after attempting to insert a new model object
2886
-             *
2887
-             * @param EEM_Base   $model           used
2888
-             * @param array      $fields_n_values fields and their values
2889
-             * @param int|string the              ID of the newly-inserted model object
2890
-             */
2891
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2892
-            return $new_id;
2893
-        }
2894
-        return false;
2895
-    }
2896
-
2897
-
2898
-
2899
-    /**
2900
-     * Checks that the result would satisfy the unique indexes on this model
2901
-     *
2902
-     * @param array  $field_n_values
2903
-     * @param string $action
2904
-     * @return boolean
2905
-     * @throws EE_Error
2906
-     */
2907
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2908
-    {
2909
-        foreach ($this->unique_indexes() as $index_name => $index) {
2910
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2911
-            if ($this->exists(array($uniqueness_where_params))) {
2912
-                EE_Error::add_error(
2913
-                    sprintf(
2914
-                        __(
2915
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2916
-                            "event_espresso"
2917
-                        ),
2918
-                        $action,
2919
-                        $this->_get_class_name(),
2920
-                        $index_name,
2921
-                        implode(",", $index->field_names()),
2922
-                        http_build_query($uniqueness_where_params)
2923
-                    ),
2924
-                    __FILE__,
2925
-                    __FUNCTION__,
2926
-                    __LINE__
2927
-                );
2928
-                return false;
2929
-            }
2930
-        }
2931
-        return true;
2932
-    }
2933
-
2934
-
2935
-
2936
-    /**
2937
-     * Checks the database for an item that conflicts (ie, if this item were
2938
-     * saved to the DB would break some uniqueness requirement, like a primary key
2939
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2940
-     * can be either an EE_Base_Class or an array of fields n values
2941
-     *
2942
-     * @param EE_Base_Class|array $obj_or_fields_array
2943
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2944
-     *                                                 when looking for conflicts
2945
-     *                                                 (ie, if false, we ignore the model object's primary key
2946
-     *                                                 when finding "conflicts". If true, it's also considered).
2947
-     *                                                 Only works for INT primary key,
2948
-     *                                                 STRING primary keys cannot be ignored
2949
-     * @throws EE_Error
2950
-     * @return EE_Base_Class|array
2951
-     */
2952
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2953
-    {
2954
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2955
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2956
-        } elseif (is_array($obj_or_fields_array)) {
2957
-            $fields_n_values = $obj_or_fields_array;
2958
-        } else {
2959
-            throw new EE_Error(
2960
-                sprintf(
2961
-                    __(
2962
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2963
-                        "event_espresso"
2964
-                    ),
2965
-                    get_class($this),
2966
-                    $obj_or_fields_array
2967
-                )
2968
-            );
2969
-        }
2970
-        $query_params = array();
2971
-        if ($this->has_primary_key_field()
2972
-            && ($include_primary_key
2973
-                || $this->get_primary_key_field()
2974
-                   instanceof
2975
-                   EE_Primary_Key_String_Field)
2976
-            && isset($fields_n_values[ $this->primary_key_name() ])
2977
-        ) {
2978
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2979
-        }
2980
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2981
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2982
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2983
-        }
2984
-        // if there is nothing to base this search on, then we shouldn't find anything
2985
-        if (empty($query_params)) {
2986
-            return array();
2987
-        }
2988
-        return $this->get_one($query_params);
2989
-    }
2990
-
2991
-
2992
-
2993
-    /**
2994
-     * Like count, but is optimized and returns a boolean instead of an int
2995
-     *
2996
-     * @param array $query_params
2997
-     * @return boolean
2998
-     * @throws EE_Error
2999
-     */
3000
-    public function exists($query_params)
3001
-    {
3002
-        $query_params['limit'] = 1;
3003
-        return $this->count($query_params) > 0;
3004
-    }
3005
-
3006
-
3007
-
3008
-    /**
3009
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
3010
-     *
3011
-     * @param int|string $id
3012
-     * @return boolean
3013
-     * @throws EE_Error
3014
-     */
3015
-    public function exists_by_ID($id)
3016
-    {
3017
-        return $this->exists(
3018
-            array(
3019
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3020
-                array(
3021
-                    $this->primary_key_name() => $id,
3022
-                ),
3023
-            )
3024
-        );
3025
-    }
3026
-
3027
-
3028
-
3029
-    /**
3030
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3031
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3032
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3033
-     * on the main table)
3034
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3035
-     * cases where we want to call it directly rather than via insert().
3036
-     *
3037
-     * @access   protected
3038
-     * @param EE_Table_Base $table
3039
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3040
-     *                                       float
3041
-     * @param int           $new_id          for now we assume only int keys
3042
-     * @throws EE_Error
3043
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3044
-     * @return int ID of new row inserted, or FALSE on failure
3045
-     */
3046
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3047
-    {
3048
-        global $wpdb;
3049
-        $insertion_col_n_values = array();
3050
-        $format_for_insertion = array();
3051
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
3052
-        foreach ($fields_on_table as $field_name => $field_obj) {
3053
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3054
-            if ($field_obj->is_auto_increment()) {
3055
-                continue;
3056
-            }
3057
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3058
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3059
-            if ($prepared_value !== null) {
3060
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3061
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3062
-            }
3063
-        }
3064
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3065
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3066
-            // so add the fk to the main table as a column
3067
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3068
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3069
-        }
3070
-        // insert the new entry
3071
-        $result = $this->_do_wpdb_query(
3072
-            'insert',
3073
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3074
-        );
3075
-        if ($result === false) {
3076
-            return false;
3077
-        }
3078
-        // ok, now what do we return for the ID of the newly-inserted thing?
3079
-        if ($this->has_primary_key_field()) {
3080
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3081
-                return $wpdb->insert_id;
3082
-            }
3083
-            // it's not an auto-increment primary key, so
3084
-            // it must have been supplied
3085
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3086
-        }
3087
-        // we can't return a  primary key because there is none. instead return
3088
-        // a unique string indicating this model
3089
-        return $this->get_index_primary_key_string($fields_n_values);
3090
-    }
3091
-
3092
-
3093
-
3094
-    /**
3095
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3096
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3097
-     * and there is no default, we pass it along. WPDB will take care of it)
3098
-     *
3099
-     * @param EE_Model_Field_Base $field_obj
3100
-     * @param array               $fields_n_values
3101
-     * @return mixed string|int|float depending on what the table column will be expecting
3102
-     * @throws EE_Error
3103
-     */
3104
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3105
-    {
3106
-        // if this field doesn't allow nullable, don't allow it
3107
-        if (! $field_obj->is_nullable()
3108
-            && (
3109
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3110
-                || $fields_n_values[ $field_obj->get_name() ] === null
3111
-            )
3112
-        ) {
3113
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3114
-        }
3115
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3116
-            ? $fields_n_values[ $field_obj->get_name() ]
3117
-            : null;
3118
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3119
-    }
3120
-
3121
-
3122
-
3123
-    /**
3124
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3125
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3126
-     * the field's prepare_for_set() method.
3127
-     *
3128
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3129
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3130
-     *                                   top of file)
3131
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3132
-     *                                   $value is a custom selection
3133
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3134
-     */
3135
-    private function _prepare_value_for_use_in_db($value, $field)
3136
-    {
3137
-        if ($field && $field instanceof EE_Model_Field_Base) {
3138
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3139
-            switch ($this->_values_already_prepared_by_model_object) {
3140
-                /** @noinspection PhpMissingBreakStatementInspection */
3141
-                case self::not_prepared_by_model_object:
3142
-                    $value = $field->prepare_for_set($value);
3143
-                // purposefully left out "return"
3144
-                case self::prepared_by_model_object:
3145
-                    /** @noinspection SuspiciousAssignmentsInspection */
3146
-                    $value = $field->prepare_for_use_in_db($value);
3147
-                case self::prepared_for_use_in_db:
3148
-                    // leave the value alone
3149
-            }
3150
-            return $value;
3151
-            // phpcs:enable
3152
-        }
3153
-        return $value;
3154
-    }
3155
-
3156
-
3157
-
3158
-    /**
3159
-     * Returns the main table on this model
3160
-     *
3161
-     * @return EE_Primary_Table
3162
-     * @throws EE_Error
3163
-     */
3164
-    protected function _get_main_table()
3165
-    {
3166
-        foreach ($this->_tables as $table) {
3167
-            if ($table instanceof EE_Primary_Table) {
3168
-                return $table;
3169
-            }
3170
-        }
3171
-        throw new EE_Error(sprintf(__(
3172
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3173
-            'event_espresso'
3174
-        ), get_class($this)));
3175
-    }
3176
-
3177
-
3178
-
3179
-    /**
3180
-     * table
3181
-     * returns EE_Primary_Table table name
3182
-     *
3183
-     * @return string
3184
-     * @throws EE_Error
3185
-     */
3186
-    public function table()
3187
-    {
3188
-        return $this->_get_main_table()->get_table_name();
3189
-    }
3190
-
3191
-
3192
-
3193
-    /**
3194
-     * table
3195
-     * returns first EE_Secondary_Table table name
3196
-     *
3197
-     * @return string
3198
-     */
3199
-    public function second_table()
3200
-    {
3201
-        // grab second table from tables array
3202
-        $second_table = end($this->_tables);
3203
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3204
-    }
3205
-
3206
-
3207
-
3208
-    /**
3209
-     * get_table_obj_by_alias
3210
-     * returns table name given it's alias
3211
-     *
3212
-     * @param string $table_alias
3213
-     * @return EE_Primary_Table | EE_Secondary_Table
3214
-     */
3215
-    public function get_table_obj_by_alias($table_alias = '')
3216
-    {
3217
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3218
-    }
3219
-
3220
-
3221
-
3222
-    /**
3223
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3224
-     *
3225
-     * @return EE_Secondary_Table[]
3226
-     */
3227
-    protected function _get_other_tables()
3228
-    {
3229
-        $other_tables = array();
3230
-        foreach ($this->_tables as $table_alias => $table) {
3231
-            if ($table instanceof EE_Secondary_Table) {
3232
-                $other_tables[ $table_alias ] = $table;
3233
-            }
3234
-        }
3235
-        return $other_tables;
3236
-    }
3237
-
3238
-
3239
-
3240
-    /**
3241
-     * Finds all the fields that correspond to the given table
3242
-     *
3243
-     * @param string $table_alias , array key in EEM_Base::_tables
3244
-     * @return EE_Model_Field_Base[]
3245
-     */
3246
-    public function _get_fields_for_table($table_alias)
3247
-    {
3248
-        return $this->_fields[ $table_alias ];
3249
-    }
3250
-
3251
-
3252
-
3253
-    /**
3254
-     * Recurses through all the where parameters, and finds all the related models we'll need
3255
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3256
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3257
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3258
-     * related Registration, Transaction, and Payment models.
3259
-     *
3260
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3261
-     * @return EE_Model_Query_Info_Carrier
3262
-     * @throws EE_Error
3263
-     */
3264
-    public function _extract_related_models_from_query($query_params)
3265
-    {
3266
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3267
-        if (array_key_exists(0, $query_params)) {
3268
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3269
-        }
3270
-        if (array_key_exists('group_by', $query_params)) {
3271
-            if (is_array($query_params['group_by'])) {
3272
-                $this->_extract_related_models_from_sub_params_array_values(
3273
-                    $query_params['group_by'],
3274
-                    $query_info_carrier,
3275
-                    'group_by'
3276
-                );
3277
-            } elseif (! empty($query_params['group_by'])) {
3278
-                $this->_extract_related_model_info_from_query_param(
3279
-                    $query_params['group_by'],
3280
-                    $query_info_carrier,
3281
-                    'group_by'
3282
-                );
3283
-            }
3284
-        }
3285
-        if (array_key_exists('having', $query_params)) {
3286
-            $this->_extract_related_models_from_sub_params_array_keys(
3287
-                $query_params[0],
3288
-                $query_info_carrier,
3289
-                'having'
3290
-            );
3291
-        }
3292
-        if (array_key_exists('order_by', $query_params)) {
3293
-            if (is_array($query_params['order_by'])) {
3294
-                $this->_extract_related_models_from_sub_params_array_keys(
3295
-                    $query_params['order_by'],
3296
-                    $query_info_carrier,
3297
-                    'order_by'
3298
-                );
3299
-            } elseif (! empty($query_params['order_by'])) {
3300
-                $this->_extract_related_model_info_from_query_param(
3301
-                    $query_params['order_by'],
3302
-                    $query_info_carrier,
3303
-                    'order_by'
3304
-                );
3305
-            }
3306
-        }
3307
-        if (array_key_exists('force_join', $query_params)) {
3308
-            $this->_extract_related_models_from_sub_params_array_values(
3309
-                $query_params['force_join'],
3310
-                $query_info_carrier,
3311
-                'force_join'
3312
-            );
3313
-        }
3314
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3315
-        return $query_info_carrier;
3316
-    }
3317
-
3318
-
3319
-
3320
-    /**
3321
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3322
-     *
3323
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3324
-     *                                                      $query_params['having']
3325
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3326
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3327
-     * @throws EE_Error
3328
-     * @return \EE_Model_Query_Info_Carrier
3329
-     */
3330
-    private function _extract_related_models_from_sub_params_array_keys(
3331
-        $sub_query_params,
3332
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3333
-        $query_param_type
3334
-    ) {
3335
-        if (! empty($sub_query_params)) {
3336
-            $sub_query_params = (array) $sub_query_params;
3337
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3338
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3339
-                $this->_extract_related_model_info_from_query_param(
3340
-                    $param,
3341
-                    $model_query_info_carrier,
3342
-                    $query_param_type
3343
-                );
3344
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3345
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3346
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3347
-                // of array('Registration.TXN_ID'=>23)
3348
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3349
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3350
-                    if (! is_array($possibly_array_of_params)) {
3351
-                        throw new EE_Error(sprintf(
3352
-                            __(
3353
-                                "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'))",
3354
-                                "event_espresso"
3355
-                            ),
3356
-                            $param,
3357
-                            $possibly_array_of_params
3358
-                        ));
3359
-                    }
3360
-                    $this->_extract_related_models_from_sub_params_array_keys(
3361
-                        $possibly_array_of_params,
3362
-                        $model_query_info_carrier,
3363
-                        $query_param_type
3364
-                    );
3365
-                } elseif ($query_param_type === 0 // ie WHERE
3366
-                          && is_array($possibly_array_of_params)
3367
-                          && isset($possibly_array_of_params[2])
3368
-                          && $possibly_array_of_params[2] == true
3369
-                ) {
3370
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3371
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3372
-                    // from which we should extract query parameters!
3373
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3374
-                        throw new EE_Error(sprintf(__(
3375
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3376
-                            "event_espresso"
3377
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3378
-                    }
3379
-                    $this->_extract_related_model_info_from_query_param(
3380
-                        $possibly_array_of_params[1],
3381
-                        $model_query_info_carrier,
3382
-                        $query_param_type
3383
-                    );
3384
-                }
3385
-            }
3386
-        }
3387
-        return $model_query_info_carrier;
3388
-    }
3389
-
3390
-
3391
-
3392
-    /**
3393
-     * For extracting related models from forced_joins, where the array values contain the info about what
3394
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3395
-     *
3396
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3397
-     *                                                      $query_params['having']
3398
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3399
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3400
-     * @throws EE_Error
3401
-     * @return \EE_Model_Query_Info_Carrier
3402
-     */
3403
-    private function _extract_related_models_from_sub_params_array_values(
3404
-        $sub_query_params,
3405
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3406
-        $query_param_type
3407
-    ) {
3408
-        if (! empty($sub_query_params)) {
3409
-            if (! is_array($sub_query_params)) {
3410
-                throw new EE_Error(sprintf(
3411
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3412
-                    $sub_query_params
3413
-                ));
3414
-            }
3415
-            foreach ($sub_query_params as $param) {
3416
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3417
-                $this->_extract_related_model_info_from_query_param(
3418
-                    $param,
3419
-                    $model_query_info_carrier,
3420
-                    $query_param_type
3421
-                );
3422
-            }
3423
-        }
3424
-        return $model_query_info_carrier;
3425
-    }
3426
-
3427
-
3428
-
3429
-    /**
3430
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3431
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3432
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3433
-     * but use them in a different order. Eg, we need to know what models we are querying
3434
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3435
-     * other models before we can finalize the where clause SQL.
3436
-     *
3437
-     * @param array $query_params
3438
-     * @throws EE_Error
3439
-     * @return EE_Model_Query_Info_Carrier
3440
-     */
3441
-    public function _create_model_query_info_carrier($query_params)
3442
-    {
3443
-        if (! is_array($query_params)) {
3444
-            EE_Error::doing_it_wrong(
3445
-                'EEM_Base::_create_model_query_info_carrier',
3446
-                sprintf(
3447
-                    __(
3448
-                        '$query_params should be an array, you passed a variable of type %s',
3449
-                        'event_espresso'
3450
-                    ),
3451
-                    gettype($query_params)
3452
-                ),
3453
-                '4.6.0'
3454
-            );
3455
-            $query_params = array();
3456
-        }
3457
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3458
-        // first check if we should alter the query to account for caps or not
3459
-        // because the caps might require us to do extra joins
3460
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3461
-            $query_params[0] = $where_query_params = array_replace_recursive(
3462
-                $where_query_params,
3463
-                $this->caps_where_conditions(
3464
-                    $query_params['caps']
3465
-                )
3466
-            );
3467
-        }
3468
-        $query_object = $this->_extract_related_models_from_query($query_params);
3469
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3470
-        foreach ($where_query_params as $key => $value) {
3471
-            if (is_int($key)) {
3472
-                throw new EE_Error(
3473
-                    sprintf(
3474
-                        __(
3475
-                            "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.",
3476
-                            "event_espresso"
3477
-                        ),
3478
-                        $key,
3479
-                        var_export($value, true),
3480
-                        var_export($query_params, true),
3481
-                        get_class($this)
3482
-                    )
3483
-                );
3484
-            }
3485
-        }
3486
-        if (array_key_exists('default_where_conditions', $query_params)
3487
-            && ! empty($query_params['default_where_conditions'])
3488
-        ) {
3489
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3490
-        } else {
3491
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3492
-        }
3493
-        $where_query_params = array_merge(
3494
-            $this->_get_default_where_conditions_for_models_in_query(
3495
-                $query_object,
3496
-                $use_default_where_conditions,
3497
-                $where_query_params
3498
-            ),
3499
-            $where_query_params
3500
-        );
3501
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3502
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3503
-        // So we need to setup a subquery and use that for the main join.
3504
-        // Note for now this only works on the primary table for the model.
3505
-        // So for instance, you could set the limit array like this:
3506
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3507
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3508
-            $query_object->set_main_model_join_sql(
3509
-                $this->_construct_limit_join_select(
3510
-                    $query_params['on_join_limit'][0],
3511
-                    $query_params['on_join_limit'][1]
3512
-                )
3513
-            );
3514
-        }
3515
-        // set limit
3516
-        if (array_key_exists('limit', $query_params)) {
3517
-            if (is_array($query_params['limit'])) {
3518
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3519
-                    $e = sprintf(
3520
-                        __(
3521
-                            "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)",
3522
-                            "event_espresso"
3523
-                        ),
3524
-                        http_build_query($query_params['limit'])
3525
-                    );
3526
-                    throw new EE_Error($e . "|" . $e);
3527
-                }
3528
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3529
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3530
-            } elseif (! empty($query_params['limit'])) {
3531
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3532
-            }
3533
-        }
3534
-        // set order by
3535
-        if (array_key_exists('order_by', $query_params)) {
3536
-            if (is_array($query_params['order_by'])) {
3537
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3538
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3539
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3540
-                if (array_key_exists('order', $query_params)) {
3541
-                    throw new EE_Error(
3542
-                        sprintf(
3543
-                            __(
3544
-                                "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 ",
3545
-                                "event_espresso"
3546
-                            ),
3547
-                            get_class($this),
3548
-                            implode(", ", array_keys($query_params['order_by'])),
3549
-                            implode(", ", $query_params['order_by']),
3550
-                            $query_params['order']
3551
-                        )
3552
-                    );
3553
-                }
3554
-                $this->_extract_related_models_from_sub_params_array_keys(
3555
-                    $query_params['order_by'],
3556
-                    $query_object,
3557
-                    'order_by'
3558
-                );
3559
-                // assume it's an array of fields to order by
3560
-                $order_array = array();
3561
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3562
-                    $order = $this->_extract_order($order);
3563
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3564
-                }
3565
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3566
-            } elseif (! empty($query_params['order_by'])) {
3567
-                $this->_extract_related_model_info_from_query_param(
3568
-                    $query_params['order_by'],
3569
-                    $query_object,
3570
-                    'order',
3571
-                    $query_params['order_by']
3572
-                );
3573
-                $order = isset($query_params['order'])
3574
-                    ? $this->_extract_order($query_params['order'])
3575
-                    : 'DESC';
3576
-                $query_object->set_order_by_sql(
3577
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3578
-                );
3579
-            }
3580
-        }
3581
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3582
-        if (! array_key_exists('order_by', $query_params)
3583
-            && array_key_exists('order', $query_params)
3584
-            && ! empty($query_params['order'])
3585
-        ) {
3586
-            $pk_field = $this->get_primary_key_field();
3587
-            $order = $this->_extract_order($query_params['order']);
3588
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3589
-        }
3590
-        // set group by
3591
-        if (array_key_exists('group_by', $query_params)) {
3592
-            if (is_array($query_params['group_by'])) {
3593
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3594
-                $group_by_array = array();
3595
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3596
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3597
-                }
3598
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3599
-            } elseif (! empty($query_params['group_by'])) {
3600
-                $query_object->set_group_by_sql(
3601
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3602
-                );
3603
-            }
3604
-        }
3605
-        // set having
3606
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3607
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3608
-        }
3609
-        // now, just verify they didn't pass anything wack
3610
-        foreach ($query_params as $query_key => $query_value) {
3611
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3612
-                throw new EE_Error(
3613
-                    sprintf(
3614
-                        __(
3615
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3616
-                            'event_espresso'
3617
-                        ),
3618
-                        $query_key,
3619
-                        get_class($this),
3620
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3621
-                        implode(',', $this->_allowed_query_params)
3622
-                    )
3623
-                );
3624
-            }
3625
-        }
3626
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3627
-        if (empty($main_model_join_sql)) {
3628
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3629
-        }
3630
-        return $query_object;
3631
-    }
3632
-
3633
-
3634
-
3635
-    /**
3636
-     * Gets the where conditions that should be imposed on the query based on the
3637
-     * context (eg reading frontend, backend, edit or delete).
3638
-     *
3639
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3640
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3641
-     * @throws EE_Error
3642
-     */
3643
-    public function caps_where_conditions($context = self::caps_read)
3644
-    {
3645
-        EEM_Base::verify_is_valid_cap_context($context);
3646
-        $cap_where_conditions = array();
3647
-        $cap_restrictions = $this->caps_missing($context);
3648
-        /**
3649
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3650
-         */
3651
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3652
-            $cap_where_conditions = array_replace_recursive(
3653
-                $cap_where_conditions,
3654
-                $restriction_if_no_cap->get_default_where_conditions()
3655
-            );
3656
-        }
3657
-        return apply_filters(
3658
-            'FHEE__EEM_Base__caps_where_conditions__return',
3659
-            $cap_where_conditions,
3660
-            $this,
3661
-            $context,
3662
-            $cap_restrictions
3663
-        );
3664
-    }
3665
-
3666
-
3667
-
3668
-    /**
3669
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3670
-     * otherwise throws an exception
3671
-     *
3672
-     * @param string $should_be_order_string
3673
-     * @return string either ASC, asc, DESC or desc
3674
-     * @throws EE_Error
3675
-     */
3676
-    private function _extract_order($should_be_order_string)
3677
-    {
3678
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3679
-            return $should_be_order_string;
3680
-        }
3681
-        throw new EE_Error(
3682
-            sprintf(
3683
-                __(
3684
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3685
-                    "event_espresso"
3686
-                ),
3687
-                get_class($this),
3688
-                $should_be_order_string
3689
-            )
3690
-        );
3691
-    }
3692
-
3693
-
3694
-
3695
-    /**
3696
-     * Looks at all the models which are included in this query, and asks each
3697
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3698
-     * so they can be merged
3699
-     *
3700
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3701
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3702
-     *                                                                  'none' means NO default where conditions will
3703
-     *                                                                  be used AT ALL during this query.
3704
-     *                                                                  'other_models_only' means default where
3705
-     *                                                                  conditions from other models will be used, but
3706
-     *                                                                  not for this primary model. 'all', the default,
3707
-     *                                                                  means default where conditions will apply as
3708
-     *                                                                  normal
3709
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3710
-     * @throws EE_Error
3711
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3712
-     */
3713
-    private function _get_default_where_conditions_for_models_in_query(
3714
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3715
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3716
-        $where_query_params = array()
3717
-    ) {
3718
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3719
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3720
-            throw new EE_Error(sprintf(
3721
-                __(
3722
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3723
-                    "event_espresso"
3724
-                ),
3725
-                $use_default_where_conditions,
3726
-                implode(", ", $allowed_used_default_where_conditions_values)
3727
-            ));
3728
-        }
3729
-        $universal_query_params = array();
3730
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3731
-            $universal_query_params = $this->_get_default_where_conditions();
3732
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3733
-            $universal_query_params = $this->_get_minimum_where_conditions();
3734
-        }
3735
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3736
-            $related_model = $this->get_related_model_obj($model_name);
3737
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3738
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3739
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3740
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3741
-            } else {
3742
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3743
-                continue;
3744
-            }
3745
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3746
-                $related_model_universal_where_params,
3747
-                $where_query_params,
3748
-                $related_model,
3749
-                $model_relation_path
3750
-            );
3751
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3752
-                $universal_query_params,
3753
-                $overrides
3754
-            );
3755
-        }
3756
-        return $universal_query_params;
3757
-    }
3758
-
3759
-
3760
-
3761
-    /**
3762
-     * Determines whether or not we should use default where conditions for the model in question
3763
-     * (this model, or other related models).
3764
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3765
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3766
-     * We should use default where conditions on related models when they requested to use default where conditions
3767
-     * on all models, or specifically just on other related models
3768
-     * @param      $default_where_conditions_value
3769
-     * @param bool $for_this_model false means this is for OTHER related models
3770
-     * @return bool
3771
-     */
3772
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3773
-    {
3774
-        return (
3775
-                   $for_this_model
3776
-                   && in_array(
3777
-                       $default_where_conditions_value,
3778
-                       array(
3779
-                           EEM_Base::default_where_conditions_all,
3780
-                           EEM_Base::default_where_conditions_this_only,
3781
-                           EEM_Base::default_where_conditions_minimum_others,
3782
-                       ),
3783
-                       true
3784
-                   )
3785
-               )
3786
-               || (
3787
-                   ! $for_this_model
3788
-                   && in_array(
3789
-                       $default_where_conditions_value,
3790
-                       array(
3791
-                           EEM_Base::default_where_conditions_all,
3792
-                           EEM_Base::default_where_conditions_others_only,
3793
-                       ),
3794
-                       true
3795
-                   )
3796
-               );
3797
-    }
3798
-
3799
-    /**
3800
-     * Determines whether or not we should use default minimum conditions for the model in question
3801
-     * (this model, or other related models).
3802
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3803
-     * where conditions.
3804
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3805
-     * on this model or others
3806
-     * @param      $default_where_conditions_value
3807
-     * @param bool $for_this_model false means this is for OTHER related models
3808
-     * @return bool
3809
-     */
3810
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3811
-    {
3812
-        return (
3813
-                   $for_this_model
3814
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3815
-               )
3816
-               || (
3817
-                   ! $for_this_model
3818
-                   && in_array(
3819
-                       $default_where_conditions_value,
3820
-                       array(
3821
-                           EEM_Base::default_where_conditions_minimum_others,
3822
-                           EEM_Base::default_where_conditions_minimum_all,
3823
-                       ),
3824
-                       true
3825
-                   )
3826
-               );
3827
-    }
3828
-
3829
-
3830
-    /**
3831
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3832
-     * then we also add a special where condition which allows for that model's primary key
3833
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3834
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3835
-     *
3836
-     * @param array    $default_where_conditions
3837
-     * @param array    $provided_where_conditions
3838
-     * @param EEM_Base $model
3839
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3840
-     * @return array like EEM_Base::get_all's $query_params[0]
3841
-     * @throws EE_Error
3842
-     */
3843
-    private function _override_defaults_or_make_null_friendly(
3844
-        $default_where_conditions,
3845
-        $provided_where_conditions,
3846
-        $model,
3847
-        $model_relation_path
3848
-    ) {
3849
-        $null_friendly_where_conditions = array();
3850
-        $none_overridden = true;
3851
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3852
-        foreach ($default_where_conditions as $key => $val) {
3853
-            if (isset($provided_where_conditions[ $key ])) {
3854
-                $none_overridden = false;
3855
-            } else {
3856
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3857
-            }
3858
-        }
3859
-        if ($none_overridden && $default_where_conditions) {
3860
-            if ($model->has_primary_key_field()) {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3862
-                                                                                . "."
3863
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3864
-            }/*else{
37
+	/**
38
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
41
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
+	 *
43
+	 * @var boolean
44
+	 */
45
+	private $_values_already_prepared_by_model_object = 0;
46
+
47
+	/**
48
+	 * when $_values_already_prepared_by_model_object equals this, we assume
49
+	 * the data is just like form input that needs to have the model fields'
50
+	 * prepare_for_set and prepare_for_use_in_db called on it
51
+	 */
52
+	const not_prepared_by_model_object = 0;
53
+
54
+	/**
55
+	 * when $_values_already_prepared_by_model_object equals this, we
56
+	 * assume this value is coming from a model object and doesn't need to have
57
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
58
+	 */
59
+	const prepared_by_model_object = 1;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the values are already to be used in the database (ie no processing is done
64
+	 * on them by the model's fields)
65
+	 */
66
+	const prepared_for_use_in_db = 2;
67
+
68
+
69
+	protected $singular_item = 'Item';
70
+
71
+	protected $plural_item   = 'Items';
72
+
73
+	/**
74
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
+	 */
76
+	protected $_tables;
77
+
78
+	/**
79
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
+	 *
83
+	 * @var \EE_Model_Field_Base[][] $_fields
84
+	 */
85
+	protected $_fields;
86
+
87
+	/**
88
+	 * array of different kinds of relations
89
+	 *
90
+	 * @var \EE_Model_Relation_Base[] $_model_relations
91
+	 */
92
+	protected $_model_relations;
93
+
94
+	/**
95
+	 * @var \EE_Index[] $_indexes
96
+	 */
97
+	protected $_indexes = array();
98
+
99
+	/**
100
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
101
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
+	 * by setting the same columns as used in these queries in the query yourself.
103
+	 *
104
+	 * @var EE_Default_Where_Conditions
105
+	 */
106
+	protected $_default_where_conditions_strategy;
107
+
108
+	/**
109
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
+	 * This is particularly useful when you want something between 'none' and 'default'
111
+	 *
112
+	 * @var EE_Default_Where_Conditions
113
+	 */
114
+	protected $_minimum_where_conditions_strategy;
115
+
116
+	/**
117
+	 * String describing how to find the "owner" of this model's objects.
118
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
+	 * But when there isn't, this indicates which related model, or transiently-related model,
120
+	 * has the foreign key to the wp_users table.
121
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
+	 * related to events, and events have a foreign key to wp_users.
123
+	 * On EEM_Transaction, this would be 'Transaction.Event'
124
+	 *
125
+	 * @var string
126
+	 */
127
+	protected $_model_chain_to_wp_user = '';
128
+
129
+	/**
130
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
+	 * don't need it (particularly CPT models)
132
+	 *
133
+	 * @var bool
134
+	 */
135
+	protected $_ignore_where_strategy = false;
136
+
137
+	/**
138
+	 * String used in caps relating to this model. Eg, if the caps relating to this
139
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
+	 *
141
+	 * @var string. If null it hasn't been initialized yet. If false then we
142
+	 * have indicated capabilities don't apply to this
143
+	 */
144
+	protected $_caps_slug = null;
145
+
146
+	/**
147
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
+	 * and next-level keys are capability names, and each's value is a
149
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
151
+	 * and then each capability in the corresponding sub-array that they're missing
152
+	 * adds the where conditions onto the query.
153
+	 *
154
+	 * @var array
155
+	 */
156
+	protected $_cap_restrictions = array(
157
+		self::caps_read       => array(),
158
+		self::caps_read_admin => array(),
159
+		self::caps_edit       => array(),
160
+		self::caps_delete     => array(),
161
+	);
162
+
163
+	/**
164
+	 * Array defining which cap restriction generators to use to create default
165
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
166
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
+	 * automatically set this to false (not just null).
169
+	 *
170
+	 * @var EE_Restriction_Generator_Base[]
171
+	 */
172
+	protected $_cap_restriction_generators = array();
173
+
174
+	/**
175
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
+	 */
177
+	const caps_read       = 'read';
178
+
179
+	const caps_read_admin = 'read_admin';
180
+
181
+	const caps_edit       = 'edit';
182
+
183
+	const caps_delete     = 'delete';
184
+
185
+	/**
186
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
+	 * maps to 'read' because when looking for relevant permissions we're going to use
189
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
190
+	 *
191
+	 * @var array
192
+	 */
193
+	protected $_cap_contexts_to_cap_action_map = array(
194
+		self::caps_read       => 'read',
195
+		self::caps_read_admin => 'read',
196
+		self::caps_edit       => 'edit',
197
+		self::caps_delete     => 'delete',
198
+	);
199
+
200
+	/**
201
+	 * Timezone
202
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
+	 * EE_Datetime_Field data type will have access to it.
206
+	 *
207
+	 * @var string
208
+	 */
209
+	protected $_timezone;
210
+
211
+
212
+	/**
213
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
+	 * multisite.
215
+	 *
216
+	 * @var int
217
+	 */
218
+	protected static $_model_query_blog_id;
219
+
220
+	/**
221
+	 * A copy of _fields, except the array keys are the model names pointed to by
222
+	 * the field
223
+	 *
224
+	 * @var EE_Model_Field_Base[]
225
+	 */
226
+	private $_cache_foreign_key_to_fields = array();
227
+
228
+	/**
229
+	 * Cached list of all the fields on the model, indexed by their name
230
+	 *
231
+	 * @var EE_Model_Field_Base[]
232
+	 */
233
+	private $_cached_fields = null;
234
+
235
+	/**
236
+	 * Cached list of all the fields on the model, except those that are
237
+	 * marked as only pertinent to the database
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cached_fields_non_db_only = null;
242
+
243
+	/**
244
+	 * A cached reference to the primary key for quick lookup
245
+	 *
246
+	 * @var EE_Model_Field_Base
247
+	 */
248
+	private $_primary_key_field = null;
249
+
250
+	/**
251
+	 * Flag indicating whether this model has a primary key or not
252
+	 *
253
+	 * @var boolean
254
+	 */
255
+	protected $_has_primary_key_field = null;
256
+
257
+	/**
258
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
259
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
+	 * This should be true for models that deal with data that should exist independent of EE.
261
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
263
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
265
+	 * @var boolean
266
+	 */
267
+	protected $_wp_core_model = false;
268
+
269
+	/**
270
+	 *    List of valid operators that can be used for querying.
271
+	 * The keys are all operators we'll accept, the values are the real SQL
272
+	 * operators used
273
+	 *
274
+	 * @var array
275
+	 */
276
+	protected $_valid_operators = array(
277
+		'='           => '=',
278
+		'<='          => '<=',
279
+		'<'           => '<',
280
+		'>='          => '>=',
281
+		'>'           => '>',
282
+		'!='          => '!=',
283
+		'LIKE'        => 'LIKE',
284
+		'like'        => 'LIKE',
285
+		'NOT_LIKE'    => 'NOT LIKE',
286
+		'not_like'    => 'NOT LIKE',
287
+		'NOT LIKE'    => 'NOT LIKE',
288
+		'not like'    => 'NOT LIKE',
289
+		'IN'          => 'IN',
290
+		'in'          => 'IN',
291
+		'NOT_IN'      => 'NOT IN',
292
+		'not_in'      => 'NOT IN',
293
+		'NOT IN'      => 'NOT IN',
294
+		'not in'      => 'NOT IN',
295
+		'between'     => 'BETWEEN',
296
+		'BETWEEN'     => 'BETWEEN',
297
+		'IS_NOT_NULL' => 'IS NOT NULL',
298
+		'is_not_null' => 'IS NOT NULL',
299
+		'IS NOT NULL' => 'IS NOT NULL',
300
+		'is not null' => 'IS NOT NULL',
301
+		'IS_NULL'     => 'IS NULL',
302
+		'is_null'     => 'IS NULL',
303
+		'IS NULL'     => 'IS NULL',
304
+		'is null'     => 'IS NULL',
305
+		'REGEXP'      => 'REGEXP',
306
+		'regexp'      => 'REGEXP',
307
+		'NOT_REGEXP'  => 'NOT REGEXP',
308
+		'not_regexp'  => 'NOT REGEXP',
309
+		'NOT REGEXP'  => 'NOT REGEXP',
310
+		'not regexp'  => 'NOT REGEXP',
311
+	);
312
+
313
+	/**
314
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
+	 *
316
+	 * @var array
317
+	 */
318
+	protected $_in_style_operators = array('IN', 'NOT IN');
319
+
320
+	/**
321
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
+	 * '12-31-2012'"
323
+	 *
324
+	 * @var array
325
+	 */
326
+	protected $_between_style_operators = array('BETWEEN');
327
+
328
+	/**
329
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
+	 * @var array
331
+	 */
332
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
+	/**
334
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
+	 * on a join table.
336
+	 *
337
+	 * @var array
338
+	 */
339
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
+
341
+	/**
342
+	 * Allowed values for $query_params['order'] for ordering in queries
343
+	 *
344
+	 * @var array
345
+	 */
346
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
+
348
+	/**
349
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
351
+	 *
352
+	 * @var array
353
+	 */
354
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
+
356
+	/**
357
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
359
+	 *
360
+	 * @var array
361
+	 */
362
+	private $_allowed_query_params = array(
363
+		0,
364
+		'limit',
365
+		'order_by',
366
+		'group_by',
367
+		'having',
368
+		'force_join',
369
+		'order',
370
+		'on_join_limit',
371
+		'default_where_conditions',
372
+		'caps',
373
+		'extra_selects'
374
+	);
375
+
376
+	/**
377
+	 * All the data types that can be used in $wpdb->prepare statements.
378
+	 *
379
+	 * @var array
380
+	 */
381
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
+
383
+	/**
384
+	 * @var EE_Registry $EE
385
+	 */
386
+	protected $EE = null;
387
+
388
+
389
+	/**
390
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
+	 *
392
+	 * @var int
393
+	 */
394
+	protected $_show_next_x_db_queries = 0;
395
+
396
+	/**
397
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
+	 * WHERE, GROUP_BY, etc.
400
+	 *
401
+	 * @var CustomSelects
402
+	 */
403
+	protected $_custom_selections = array();
404
+
405
+	/**
406
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
+	 * caches every model object we've fetched from the DB on this request
408
+	 *
409
+	 * @var array
410
+	 */
411
+	protected $_entity_map;
412
+
413
+	/**
414
+	 * @var LoaderInterface $loader
415
+	 */
416
+	private static $loader;
417
+
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error(
520
+				sprintf(
521
+					__(
522
+						'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.',
523
+						'event_espresso'
524
+					),
525
+					get_class($this)
526
+				)
527
+			);
528
+		}
529
+		/**
530
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
531
+		 */
532
+		if (empty(EEM_Base::$_model_query_blog_id)) {
533
+			EEM_Base::set_model_query_blog_id();
534
+		}
535
+		/**
536
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
537
+		 * just use EE_Register_Model_Extension
538
+		 *
539
+		 * @var EE_Table_Base[] $_tables
540
+		 */
541
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
542
+		foreach ($this->_tables as $table_alias => $table_obj) {
543
+			/** @var $table_obj EE_Table_Base */
544
+			$table_obj->_construct_finalize_with_alias($table_alias);
545
+			if ($table_obj instanceof EE_Secondary_Table) {
546
+				/** @var $table_obj EE_Secondary_Table */
547
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
548
+			}
549
+		}
550
+		/**
551
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
552
+		 * EE_Register_Model_Extension
553
+		 *
554
+		 * @param EE_Model_Field_Base[] $_fields
555
+		 */
556
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
557
+		$this->_invalidate_field_caches();
558
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
559
+			if (! array_key_exists($table_alias, $this->_tables)) {
560
+				throw new EE_Error(sprintf(__(
561
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
562
+					'event_espresso'
563
+				), $table_alias, implode(",", $this->_fields)));
564
+			}
565
+			foreach ($fields_for_table as $field_name => $field_obj) {
566
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
+				// primary key field base has a slightly different _construct_finalize
568
+				/** @var $field_obj EE_Model_Field_Base */
569
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
+			}
571
+		}
572
+		// everything is related to Extra_Meta
573
+		if (get_class($this) !== 'EEM_Extra_Meta') {
574
+			// make extra meta related to everything, but don't block deleting things just
575
+			// because they have related extra meta info. For now just orphan those extra meta
576
+			// in the future we should automatically delete them
577
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		// and change logs
580
+		if (get_class($this) !== 'EEM_Change_Log') {
581
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
+		}
583
+		/**
584
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
+		 * EE_Register_Model_Extension
586
+		 *
587
+		 * @param EE_Model_Relation_Base[] $_model_relations
588
+		 */
589
+		$this->_model_relations = (array) apply_filters(
590
+			'FHEE__' . get_class($this) . '__construct__model_relations',
591
+			$this->_model_relations
592
+		);
593
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
594
+			/** @var $relation_obj EE_Model_Relation_Base */
595
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
596
+		}
597
+		foreach ($this->_indexes as $index_name => $index_obj) {
598
+			/** @var $index_obj EE_Index */
599
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
600
+		}
601
+		$this->set_timezone($timezone);
602
+		// finalize default where condition strategy, or set default
603
+		if (! $this->_default_where_conditions_strategy) {
604
+			// nothing was set during child constructor, so set default
605
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
606
+		}
607
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
608
+		if (! $this->_minimum_where_conditions_strategy) {
609
+			// nothing was set during child constructor, so set default
610
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
611
+		}
612
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
613
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
614
+		// to indicate to NOT set it, set it to the logical default
615
+		if ($this->_caps_slug === null) {
616
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
617
+		}
618
+		// initialize the standard cap restriction generators if none were specified by the child constructor
619
+		if ($this->_cap_restriction_generators !== false) {
620
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
621
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
622
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
623
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
624
+						new EE_Restriction_Generator_Protected(),
625
+						$cap_context,
626
+						$this
627
+					);
628
+				}
629
+			}
630
+		}
631
+		// if there are cap restriction generators, use them to make the default cap restrictions
632
+		if ($this->_cap_restriction_generators !== false) {
633
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
634
+				if (! $generator_object) {
635
+					continue;
636
+				}
637
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
638
+					throw new EE_Error(
639
+						sprintf(
640
+							__(
641
+								'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.',
642
+								'event_espresso'
643
+							),
644
+							$context,
645
+							$this->get_this_model_name()
646
+						)
647
+					);
648
+				}
649
+				$action = $this->cap_action_for_context($context);
650
+				if (! $generator_object->construction_finalized()) {
651
+					$generator_object->_construct_finalize($this, $action);
652
+				}
653
+			}
654
+		}
655
+		do_action('AHEE__' . get_class($this) . '__construct__end');
656
+	}
657
+
658
+
659
+
660
+	/**
661
+	 * Used to set the $_model_query_blog_id static property.
662
+	 *
663
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
664
+	 *                      value for get_current_blog_id() will be used.
665
+	 */
666
+	public static function set_model_query_blog_id($blog_id = 0)
667
+	{
668
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
669
+	}
670
+
671
+
672
+
673
+	/**
674
+	 * Returns whatever is set as the internal $model_query_blog_id.
675
+	 *
676
+	 * @return int
677
+	 */
678
+	public static function get_model_query_blog_id()
679
+	{
680
+		return EEM_Base::$_model_query_blog_id;
681
+	}
682
+
683
+
684
+
685
+	/**
686
+	 * This function is a singleton method used to instantiate the Espresso_model object
687
+	 *
688
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
689
+	 *                                (and any incoming timezone data that gets saved).
690
+	 *                                Note this just sends the timezone info to the date time model field objects.
691
+	 *                                Default is NULL
692
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
693
+	 * @return static (as in the concrete child class)
694
+	 * @throws EE_Error
695
+	 * @throws InvalidArgumentException
696
+	 * @throws InvalidDataTypeException
697
+	 * @throws InvalidInterfaceException
698
+	 */
699
+	public static function instance($timezone = null)
700
+	{
701
+		// check if instance of Espresso_model already exists
702
+		if (! static::$_instance instanceof static) {
703
+			// instantiate Espresso_model
704
+			static::$_instance = new static(
705
+				$timezone,
706
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
707
+			);
708
+		}
709
+		// we might have a timezone set, let set_timezone decide what to do with it
710
+		static::$_instance->set_timezone($timezone);
711
+		// Espresso_model object
712
+		return static::$_instance;
713
+	}
714
+
715
+
716
+
717
+	/**
718
+	 * resets the model and returns it
719
+	 *
720
+	 * @param null | string $timezone
721
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
722
+	 * all its properties reset; if it wasn't instantiated, returns null)
723
+	 * @throws EE_Error
724
+	 * @throws ReflectionException
725
+	 * @throws InvalidArgumentException
726
+	 * @throws InvalidDataTypeException
727
+	 * @throws InvalidInterfaceException
728
+	 */
729
+	public static function reset($timezone = null)
730
+	{
731
+		if (static::$_instance instanceof EEM_Base) {
732
+			// let's try to NOT swap out the current instance for a new one
733
+			// because if someone has a reference to it, we can't remove their reference
734
+			// so it's best to keep using the same reference, but change the original object
735
+			// reset all its properties to their original values as defined in the class
736
+			$r = new ReflectionClass(get_class(static::$_instance));
737
+			$static_properties = $r->getStaticProperties();
738
+			foreach ($r->getDefaultProperties() as $property => $value) {
739
+				// don't set instance to null like it was originally,
740
+				// but it's static anyways, and we're ignoring static properties (for now at least)
741
+				if (! isset($static_properties[ $property ])) {
742
+					static::$_instance->{$property} = $value;
743
+				}
744
+			}
745
+			// and then directly call its constructor again, like we would if we were creating a new one
746
+			static::$_instance->__construct(
747
+				$timezone,
748
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
749
+			);
750
+			return self::instance();
751
+		}
752
+		return null;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * @return LoaderInterface
759
+	 * @throws InvalidArgumentException
760
+	 * @throws InvalidDataTypeException
761
+	 * @throws InvalidInterfaceException
762
+	 */
763
+	private static function getLoader()
764
+	{
765
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
766
+			EEM_Base::$loader = LoaderFactory::getLoader();
767
+		}
768
+		return EEM_Base::$loader;
769
+	}
770
+
771
+
772
+
773
+	/**
774
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
775
+	 *
776
+	 * @param  boolean $translated return localized strings or JUST the array.
777
+	 * @return array
778
+	 * @throws EE_Error
779
+	 * @throws InvalidArgumentException
780
+	 * @throws InvalidDataTypeException
781
+	 * @throws InvalidInterfaceException
782
+	 */
783
+	public function status_array($translated = false)
784
+	{
785
+		if (! array_key_exists('Status', $this->_model_relations)) {
786
+			return array();
787
+		}
788
+		$model_name = $this->get_this_model_name();
789
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
790
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
791
+		$status_array = array();
792
+		foreach ($stati as $status) {
793
+			$status_array[ $status->ID() ] = $status->get('STS_code');
794
+		}
795
+		return $translated
796
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
797
+			: $status_array;
798
+	}
799
+
800
+
801
+
802
+	/**
803
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
804
+	 *
805
+	 * @param array $query_params             {
806
+	 * @var array $0 (where) array {
807
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
808
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
809
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
810
+	 *                                        conditions based on related models (and even
811
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
812
+	 *                                        name. Eg,
813
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
814
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
815
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
816
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
817
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
818
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
819
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
820
+	 *                                        to Venues (even when each of those models actually consisted of two
821
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
822
+	 *                                        just having
823
+	 *                                        "Venue.VNU_ID", you could have
824
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
825
+	 *                                        events are related to Registrations, which are related to Attendees). You
826
+	 *                                        can take it even further with
827
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
828
+	 *                                        (from the default of '='), change the value to an numerically-indexed
829
+	 *                                        array, where the first item in the list is the operator. eg: array(
830
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
831
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
832
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
833
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
834
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
835
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
836
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
837
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
838
+	 *                                        the value is a field, simply provide a third array item (true) to the
839
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
840
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
841
+	 *                                        Note: you can also use related model field names like you would any other
842
+	 *                                        field name. eg:
843
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
844
+	 *                                        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__>' =>
845
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
846
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
847
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
848
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
849
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
850
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
851
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
852
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
853
+	 *                                        "stick" until you specify an AND. eg
854
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
855
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
856
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
857
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
858
+	 *                                        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 >>
859
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
860
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
861
+	 *                                        too, eg:
862
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
863
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
864
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
865
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
866
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
867
+	 *                                        the OFFSET, the 2nd is the LIMIT
868
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
869
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
870
+	 *                                        following format array('on_join_limit'
871
+	 *                                        => array( 'table_alias', array(1,2) ) ).
872
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
873
+	 *                                        values are either 'ASC' or 'DESC'.
874
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
875
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
876
+	 *                                        DESC..." respectively. Like the
877
+	 *                                        'where' conditions, these fields can be on related models. Eg
878
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
879
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
880
+	 *                                        Attendee, Price, Datetime, etc.)
881
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
882
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
883
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
884
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
885
+	 *                                        order by the primary key. Eg,
886
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
887
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
888
+	 *                                        DTT_EVT_start) or
889
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
890
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
891
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
892
+	 *                                        'group_by'=>'VNU_ID', or
893
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
894
+	 *                                        if no
895
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
896
+	 *                                        model's primary key (or combined primary keys). This avoids some
897
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
898
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
899
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
900
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
901
+	 *                                        results)
902
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
903
+	 *                                        array where values are models to be joined in the query.Eg
904
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
905
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
906
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
907
+	 *                                        related models which belongs to the current model
908
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
909
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
910
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
911
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
912
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
913
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
914
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
915
+	 *                                        this model's default where conditions added to the query, use
916
+	 *                                        'this_model_only'. If you want to use all default where conditions
917
+	 *                                        (default), set to 'all'.
918
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
919
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
920
+	 *                                        everything? Or should we only show the current user items they should be
921
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
922
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
923
+	 *                                        }
924
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
925
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
926
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
927
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
928
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
929
+	 *                                        array( array(
930
+	 *                                        'OR'=>array(
931
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
932
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
933
+	 *                                        )
934
+	 *                                        ),
935
+	 *                                        'limit'=>10,
936
+	 *                                        'group_by'=>'TXN_ID'
937
+	 *                                        ));
938
+	 *                                        get all the answers to the question titled "shirt size" for event with id
939
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
940
+	 *                                        'Question.QST_display_text'=>'shirt size',
941
+	 *                                        'Registration.Event.EVT_ID'=>12
942
+	 *                                        ),
943
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
944
+	 *                                        ));
945
+	 * @throws EE_Error
946
+	 */
947
+	public function get_all($query_params = array())
948
+	{
949
+		if (isset($query_params['limit'])
950
+			&& ! isset($query_params['group_by'])
951
+		) {
952
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
953
+		}
954
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
955
+	}
956
+
957
+
958
+
959
+	/**
960
+	 * Modifies the query parameters so we only get back model objects
961
+	 * that "belong" to the current user
962
+	 *
963
+	 * @param array $query_params @see EEM_Base::get_all()
964
+	 * @return array like EEM_Base::get_all
965
+	 */
966
+	public function alter_query_params_to_only_include_mine($query_params = array())
967
+	{
968
+		$wp_user_field_name = $this->wp_user_field_name();
969
+		if ($wp_user_field_name) {
970
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
971
+		}
972
+		return $query_params;
973
+	}
974
+
975
+
976
+
977
+	/**
978
+	 * Returns the name of the field's name that points to the WP_User table
979
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
980
+	 * foreign key to the WP_User table)
981
+	 *
982
+	 * @return string|boolean string on success, boolean false when there is no
983
+	 * foreign key to the WP_User table
984
+	 */
985
+	public function wp_user_field_name()
986
+	{
987
+		try {
988
+			if (! empty($this->_model_chain_to_wp_user)) {
989
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
990
+				$last_model_name = end($models_to_follow_to_wp_users);
991
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
992
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
993
+			} else {
994
+				$model_with_fk_to_wp_users = $this;
995
+				$model_chain_to_wp_user = '';
996
+			}
997
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
998
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
999
+		} catch (EE_Error $e) {
1000
+			return false;
1001
+		}
1002
+	}
1003
+
1004
+
1005
+
1006
+	/**
1007
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
1008
+	 * (or transiently-related model) has a foreign key to the wp_users table;
1009
+	 * useful for finding if model objects of this type are 'owned' by the current user.
1010
+	 * This is an empty string when the foreign key is on this model and when it isn't,
1011
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
1012
+	 * (or transiently-related model)
1013
+	 *
1014
+	 * @return string
1015
+	 */
1016
+	public function model_chain_to_wp_user()
1017
+	{
1018
+		return $this->_model_chain_to_wp_user;
1019
+	}
1020
+
1021
+
1022
+
1023
+	/**
1024
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1025
+	 * like how registrations don't have a foreign key to wp_users, but the
1026
+	 * events they are for are), or is unrelated to wp users.
1027
+	 * generally available
1028
+	 *
1029
+	 * @return boolean
1030
+	 */
1031
+	public function is_owned()
1032
+	{
1033
+		if ($this->model_chain_to_wp_user()) {
1034
+			return true;
1035
+		}
1036
+		try {
1037
+			$this->get_foreign_key_to('WP_User');
1038
+			return true;
1039
+		} catch (EE_Error $e) {
1040
+			return false;
1041
+		}
1042
+	}
1043
+
1044
+
1045
+	/**
1046
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1047
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1048
+	 * the model)
1049
+	 *
1050
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1051
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1052
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1053
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1054
+	 *                                  override this and set the select to "*", or a specific column name, like
1055
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1056
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1057
+	 *                                  the aliases used to refer to this selection, and values are to be
1058
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1059
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1060
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1061
+	 * @throws EE_Error
1062
+	 * @throws InvalidArgumentException
1063
+	 */
1064
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1065
+	{
1066
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1067
+		;
1068
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1069
+		$select_expressions = $columns_to_select === null
1070
+			? $this->_construct_default_select_sql($model_query_info)
1071
+			: '';
1072
+		if ($this->_custom_selections instanceof CustomSelects) {
1073
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1074
+			$select_expressions .= $select_expressions
1075
+				? ', ' . $custom_expressions
1076
+				: $custom_expressions;
1077
+		}
1078
+
1079
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1080
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1081
+	}
1082
+
1083
+
1084
+	/**
1085
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1086
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1087
+	 * method of including extra select information.
1088
+	 *
1089
+	 * @param array             $query_params
1090
+	 * @param null|array|string $columns_to_select
1091
+	 * @return null|CustomSelects
1092
+	 * @throws InvalidArgumentException
1093
+	 */
1094
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1095
+	{
1096
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1097
+			return null;
1098
+		}
1099
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1100
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1101
+		return new CustomSelects($selects);
1102
+	}
1103
+
1104
+
1105
+
1106
+	/**
1107
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1108
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1109
+	 * take care of joins, field preparation etc.
1110
+	 *
1111
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1112
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1113
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1114
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1115
+	 *                                  override this and set the select to "*", or a specific column name, like
1116
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1117
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1118
+	 *                                  the aliases used to refer to this selection, and values are to be
1119
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1120
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1121
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1122
+	 * @throws EE_Error
1123
+	 */
1124
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1125
+	{
1126
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1127
+	}
1128
+
1129
+
1130
+
1131
+	/**
1132
+	 * For creating a custom select statement
1133
+	 *
1134
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1135
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1136
+	 *                                 SQL, and 1=>is the datatype
1137
+	 * @throws EE_Error
1138
+	 * @return string
1139
+	 */
1140
+	private function _construct_select_from_input($columns_to_select)
1141
+	{
1142
+		if (is_array($columns_to_select)) {
1143
+			$select_sql_array = array();
1144
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1145
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1146
+					throw new EE_Error(
1147
+						sprintf(
1148
+							__(
1149
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1150
+								'event_espresso'
1151
+							),
1152
+							$selection_and_datatype,
1153
+							$alias
1154
+						)
1155
+					);
1156
+				}
1157
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1158
+					throw new EE_Error(
1159
+						sprintf(
1160
+							esc_html__(
1161
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1162
+								'event_espresso'
1163
+							),
1164
+							$selection_and_datatype[1],
1165
+							$selection_and_datatype[0],
1166
+							$alias,
1167
+							implode(', ', $this->_valid_wpdb_data_types)
1168
+						)
1169
+					);
1170
+				}
1171
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1172
+			}
1173
+			$columns_to_select_string = implode(', ', $select_sql_array);
1174
+		} else {
1175
+			$columns_to_select_string = $columns_to_select;
1176
+		}
1177
+		return $columns_to_select_string;
1178
+	}
1179
+
1180
+
1181
+
1182
+	/**
1183
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1184
+	 *
1185
+	 * @return string
1186
+	 * @throws EE_Error
1187
+	 */
1188
+	public function primary_key_name()
1189
+	{
1190
+		return $this->get_primary_key_field()->get_name();
1191
+	}
1192
+
1193
+
1194
+
1195
+	/**
1196
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1197
+	 * If there is no primary key on this model, $id is treated as primary key string
1198
+	 *
1199
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1200
+	 * @return EE_Base_Class
1201
+	 */
1202
+	public function get_one_by_ID($id)
1203
+	{
1204
+		if ($this->get_from_entity_map($id)) {
1205
+			return $this->get_from_entity_map($id);
1206
+		}
1207
+		return $this->get_one(
1208
+			$this->alter_query_params_to_restrict_by_ID(
1209
+				$id,
1210
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1211
+			)
1212
+		);
1213
+	}
1214
+
1215
+
1216
+
1217
+	/**
1218
+	 * Alters query parameters to only get items with this ID are returned.
1219
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1220
+	 * or could just be a simple primary key ID
1221
+	 *
1222
+	 * @param int   $id
1223
+	 * @param array $query_params
1224
+	 * @return array of normal query params, @see EEM_Base::get_all
1225
+	 * @throws EE_Error
1226
+	 */
1227
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1228
+	{
1229
+		if (! isset($query_params[0])) {
1230
+			$query_params[0] = array();
1231
+		}
1232
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1233
+		if ($conditions_from_id === null) {
1234
+			$query_params[0][ $this->primary_key_name() ] = $id;
1235
+		} else {
1236
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1237
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1238
+		}
1239
+		return $query_params;
1240
+	}
1241
+
1242
+
1243
+
1244
+	/**
1245
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1246
+	 * array. If no item is found, null is returned.
1247
+	 *
1248
+	 * @param array $query_params like EEM_Base's $query_params variable.
1249
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1250
+	 * @throws EE_Error
1251
+	 */
1252
+	public function get_one($query_params = array())
1253
+	{
1254
+		if (! is_array($query_params)) {
1255
+			EE_Error::doing_it_wrong(
1256
+				'EEM_Base::get_one',
1257
+				sprintf(
1258
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1259
+					gettype($query_params)
1260
+				),
1261
+				'4.6.0'
1262
+			);
1263
+			$query_params = array();
1264
+		}
1265
+		$query_params['limit'] = 1;
1266
+		$items = $this->get_all($query_params);
1267
+		if (empty($items)) {
1268
+			return null;
1269
+		}
1270
+		return array_shift($items);
1271
+	}
1272
+
1273
+
1274
+
1275
+	/**
1276
+	 * Returns the next x number of items in sequence from the given value as
1277
+	 * found in the database matching the given query conditions.
1278
+	 *
1279
+	 * @param mixed $current_field_value    Value used for the reference point.
1280
+	 * @param null  $field_to_order_by      What field is used for the
1281
+	 *                                      reference point.
1282
+	 * @param int   $limit                  How many to return.
1283
+	 * @param array $query_params           Extra conditions on the query.
1284
+	 * @param null  $columns_to_select      If left null, then an array of
1285
+	 *                                      EE_Base_Class objects is returned,
1286
+	 *                                      otherwise you can indicate just the
1287
+	 *                                      columns you want returned.
1288
+	 * @return EE_Base_Class[]|array
1289
+	 * @throws EE_Error
1290
+	 */
1291
+	public function next_x(
1292
+		$current_field_value,
1293
+		$field_to_order_by = null,
1294
+		$limit = 1,
1295
+		$query_params = array(),
1296
+		$columns_to_select = null
1297
+	) {
1298
+		return $this->_get_consecutive(
1299
+			$current_field_value,
1300
+			'>',
1301
+			$field_to_order_by,
1302
+			$limit,
1303
+			$query_params,
1304
+			$columns_to_select
1305
+		);
1306
+	}
1307
+
1308
+
1309
+
1310
+	/**
1311
+	 * Returns the previous x number of items in sequence from the given value
1312
+	 * as found in the database matching the given query conditions.
1313
+	 *
1314
+	 * @param mixed $current_field_value    Value used for the reference point.
1315
+	 * @param null  $field_to_order_by      What field is used for the
1316
+	 *                                      reference point.
1317
+	 * @param int   $limit                  How many to return.
1318
+	 * @param array $query_params           Extra conditions on the query.
1319
+	 * @param null  $columns_to_select      If left null, then an array of
1320
+	 *                                      EE_Base_Class objects is returned,
1321
+	 *                                      otherwise you can indicate just the
1322
+	 *                                      columns you want returned.
1323
+	 * @return EE_Base_Class[]|array
1324
+	 * @throws EE_Error
1325
+	 */
1326
+	public function previous_x(
1327
+		$current_field_value,
1328
+		$field_to_order_by = null,
1329
+		$limit = 1,
1330
+		$query_params = array(),
1331
+		$columns_to_select = null
1332
+	) {
1333
+		return $this->_get_consecutive(
1334
+			$current_field_value,
1335
+			'<',
1336
+			$field_to_order_by,
1337
+			$limit,
1338
+			$query_params,
1339
+			$columns_to_select
1340
+		);
1341
+	}
1342
+
1343
+
1344
+
1345
+	/**
1346
+	 * Returns the next item in sequence from the given value as found in the
1347
+	 * database matching the given query conditions.
1348
+	 *
1349
+	 * @param mixed $current_field_value    Value used for the reference point.
1350
+	 * @param null  $field_to_order_by      What field is used for the
1351
+	 *                                      reference point.
1352
+	 * @param array $query_params           Extra conditions on the query.
1353
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1354
+	 *                                      object is returned, otherwise you
1355
+	 *                                      can indicate just the columns you
1356
+	 *                                      want and a single array indexed by
1357
+	 *                                      the columns will be returned.
1358
+	 * @return EE_Base_Class|null|array()
1359
+	 * @throws EE_Error
1360
+	 */
1361
+	public function next(
1362
+		$current_field_value,
1363
+		$field_to_order_by = null,
1364
+		$query_params = array(),
1365
+		$columns_to_select = null
1366
+	) {
1367
+		$results = $this->_get_consecutive(
1368
+			$current_field_value,
1369
+			'>',
1370
+			$field_to_order_by,
1371
+			1,
1372
+			$query_params,
1373
+			$columns_to_select
1374
+		);
1375
+		return empty($results) ? null : reset($results);
1376
+	}
1377
+
1378
+
1379
+
1380
+	/**
1381
+	 * Returns the previous item in sequence from the given value as found in
1382
+	 * the database matching the given query conditions.
1383
+	 *
1384
+	 * @param mixed $current_field_value    Value used for the reference point.
1385
+	 * @param null  $field_to_order_by      What field is used for the
1386
+	 *                                      reference point.
1387
+	 * @param array $query_params           Extra conditions on the query.
1388
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1389
+	 *                                      object is returned, otherwise you
1390
+	 *                                      can indicate just the columns you
1391
+	 *                                      want and a single array indexed by
1392
+	 *                                      the columns will be returned.
1393
+	 * @return EE_Base_Class|null|array()
1394
+	 * @throws EE_Error
1395
+	 */
1396
+	public function previous(
1397
+		$current_field_value,
1398
+		$field_to_order_by = null,
1399
+		$query_params = array(),
1400
+		$columns_to_select = null
1401
+	) {
1402
+		$results = $this->_get_consecutive(
1403
+			$current_field_value,
1404
+			'<',
1405
+			$field_to_order_by,
1406
+			1,
1407
+			$query_params,
1408
+			$columns_to_select
1409
+		);
1410
+		return empty($results) ? null : reset($results);
1411
+	}
1412
+
1413
+
1414
+
1415
+	/**
1416
+	 * Returns the a consecutive number of items in sequence from the given
1417
+	 * value as found in the database matching the given query conditions.
1418
+	 *
1419
+	 * @param mixed  $current_field_value   Value used for the reference point.
1420
+	 * @param string $operand               What operand is used for the sequence.
1421
+	 * @param string $field_to_order_by     What field is used for the reference point.
1422
+	 * @param int    $limit                 How many to return.
1423
+	 * @param array  $query_params          Extra conditions on the query.
1424
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1425
+	 *                                      otherwise you can indicate just the columns you want returned.
1426
+	 * @return EE_Base_Class[]|array
1427
+	 * @throws EE_Error
1428
+	 */
1429
+	protected function _get_consecutive(
1430
+		$current_field_value,
1431
+		$operand = '>',
1432
+		$field_to_order_by = null,
1433
+		$limit = 1,
1434
+		$query_params = array(),
1435
+		$columns_to_select = null
1436
+	) {
1437
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1438
+		if (empty($field_to_order_by)) {
1439
+			if ($this->has_primary_key_field()) {
1440
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1441
+			} else {
1442
+				if (WP_DEBUG) {
1443
+					throw new EE_Error(__(
1444
+						'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).',
1445
+						'event_espresso'
1446
+					));
1447
+				}
1448
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1449
+				return array();
1450
+			}
1451
+		}
1452
+		if (! is_array($query_params)) {
1453
+			EE_Error::doing_it_wrong(
1454
+				'EEM_Base::_get_consecutive',
1455
+				sprintf(
1456
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1457
+					gettype($query_params)
1458
+				),
1459
+				'4.6.0'
1460
+			);
1461
+			$query_params = array();
1462
+		}
1463
+		// let's add the where query param for consecutive look up.
1464
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1465
+		$query_params['limit'] = $limit;
1466
+		// set direction
1467
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1468
+		$query_params['order_by'] = $operand === '>'
1469
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1470
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1471
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1472
+		if (empty($columns_to_select)) {
1473
+			return $this->get_all($query_params);
1474
+		}
1475
+		// getting just the fields
1476
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1477
+	}
1478
+
1479
+
1480
+
1481
+	/**
1482
+	 * This sets the _timezone property after model object has been instantiated.
1483
+	 *
1484
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1485
+	 */
1486
+	public function set_timezone($timezone)
1487
+	{
1488
+		if ($timezone !== null) {
1489
+			$this->_timezone = $timezone;
1490
+		}
1491
+		// note we need to loop through relations and set the timezone on those objects as well.
1492
+		foreach ($this->_model_relations as $relation) {
1493
+			$relation->set_timezone($timezone);
1494
+		}
1495
+		// and finally we do the same for any datetime fields
1496
+		foreach ($this->_fields as $field) {
1497
+			if ($field instanceof EE_Datetime_Field) {
1498
+				$field->set_timezone($timezone);
1499
+			}
1500
+		}
1501
+	}
1502
+
1503
+
1504
+
1505
+	/**
1506
+	 * This just returns whatever is set for the current timezone.
1507
+	 *
1508
+	 * @access public
1509
+	 * @return string
1510
+	 */
1511
+	public function get_timezone()
1512
+	{
1513
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1514
+		if (empty($this->_timezone)) {
1515
+			foreach ($this->_fields as $field) {
1516
+				if ($field instanceof EE_Datetime_Field) {
1517
+					$this->set_timezone($field->get_timezone());
1518
+					break;
1519
+				}
1520
+			}
1521
+		}
1522
+		// if timezone STILL empty then return the default timezone for the site.
1523
+		if (empty($this->_timezone)) {
1524
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1525
+		}
1526
+		return $this->_timezone;
1527
+	}
1528
+
1529
+
1530
+
1531
+	/**
1532
+	 * This returns the date formats set for the given field name and also ensures that
1533
+	 * $this->_timezone property is set correctly.
1534
+	 *
1535
+	 * @since 4.6.x
1536
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1537
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1538
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1539
+	 * @return array formats in an array with the date format first, and the time format last.
1540
+	 */
1541
+	public function get_formats_for($field_name, $pretty = false)
1542
+	{
1543
+		$field_settings = $this->field_settings_for($field_name);
1544
+		// if not a valid EE_Datetime_Field then throw error
1545
+		if (! $field_settings instanceof EE_Datetime_Field) {
1546
+			throw new EE_Error(sprintf(__(
1547
+				'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.',
1548
+				'event_espresso'
1549
+			), $field_name));
1550
+		}
1551
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1552
+		// the field.
1553
+		$this->_timezone = $field_settings->get_timezone();
1554
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1555
+	}
1556
+
1557
+
1558
+
1559
+	/**
1560
+	 * This returns the current time in a format setup for a query on this model.
1561
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1562
+	 * it will return:
1563
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1564
+	 *  NOW
1565
+	 *  - or a unix timestamp (equivalent to time())
1566
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1567
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1568
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1569
+	 * @since 4.6.x
1570
+	 * @param string $field_name       The field the current time is needed for.
1571
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1572
+	 *                                 formatted string matching the set format for the field in the set timezone will
1573
+	 *                                 be returned.
1574
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1575
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1576
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1577
+	 *                                 exception is triggered.
1578
+	 */
1579
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1580
+	{
1581
+		$formats = $this->get_formats_for($field_name);
1582
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1583
+		if ($timestamp) {
1584
+			return $DateTime->format('U');
1585
+		}
1586
+		// not returning timestamp, so return formatted string in timezone.
1587
+		switch ($what) {
1588
+			case 'time':
1589
+				return $DateTime->format($formats[1]);
1590
+				break;
1591
+			case 'date':
1592
+				return $DateTime->format($formats[0]);
1593
+				break;
1594
+			default:
1595
+				return $DateTime->format(implode(' ', $formats));
1596
+				break;
1597
+		}
1598
+	}
1599
+
1600
+
1601
+
1602
+	/**
1603
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1604
+	 * for the model are.  Returns a DateTime object.
1605
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1606
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1607
+	 * ignored.
1608
+	 *
1609
+	 * @param string $field_name      The field being setup.
1610
+	 * @param string $timestring      The date time string being used.
1611
+	 * @param string $incoming_format The format for the time string.
1612
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1613
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1614
+	 *                                format is
1615
+	 *                                'U', this is ignored.
1616
+	 * @return DateTime
1617
+	 * @throws EE_Error
1618
+	 */
1619
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1620
+	{
1621
+		// just using this to ensure the timezone is set correctly internally
1622
+		$this->get_formats_for($field_name);
1623
+		// load EEH_DTT_Helper
1624
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1625
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1626
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1627
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1628
+	}
1629
+
1630
+
1631
+
1632
+	/**
1633
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1634
+	 *
1635
+	 * @return EE_Table_Base[]
1636
+	 */
1637
+	public function get_tables()
1638
+	{
1639
+		return $this->_tables;
1640
+	}
1641
+
1642
+
1643
+
1644
+	/**
1645
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1646
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1647
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1648
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1649
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1650
+	 * model object with EVT_ID = 1
1651
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1652
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1653
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1654
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1655
+	 * are not specified)
1656
+	 *
1657
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1658
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1659
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1660
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1661
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1662
+	 *                                         ID=34, we'd use this method as follows:
1663
+	 *                                         EEM_Transaction::instance()->update(
1664
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1665
+	 *                                         array(array('TXN_ID'=>34)));
1666
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1667
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1668
+	 *                                         consider updating Question's QST_admin_label field is of type
1669
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1670
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1671
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1672
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1673
+	 *                                         TRUE, it is assumed that you've already called
1674
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1675
+	 *                                         malicious javascript. However, if
1676
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1677
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1678
+	 *                                         and every other field, before insertion. We provide this parameter
1679
+	 *                                         because model objects perform their prepare_for_set function on all
1680
+	 *                                         their values, and so don't need to be called again (and in many cases,
1681
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1682
+	 *                                         prepare_for_set method...)
1683
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1684
+	 *                                         in this model's entity map according to $fields_n_values that match
1685
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1686
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1687
+	 *                                         could get out-of-sync with the database
1688
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1689
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1690
+	 *                                         bad)
1691
+	 * @throws EE_Error
1692
+	 */
1693
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1694
+	{
1695
+		if (! is_array($query_params)) {
1696
+			EE_Error::doing_it_wrong(
1697
+				'EEM_Base::update',
1698
+				sprintf(
1699
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1700
+					gettype($query_params)
1701
+				),
1702
+				'4.6.0'
1703
+			);
1704
+			$query_params = array();
1705
+		}
1706
+		/**
1707
+		 * Action called before a model update call has been made.
1708
+		 *
1709
+		 * @param EEM_Base $model
1710
+		 * @param array    $fields_n_values the updated fields and their new values
1711
+		 * @param array    $query_params    @see EEM_Base::get_all()
1712
+		 */
1713
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1714
+		/**
1715
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1716
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1717
+		 *
1718
+		 * @param array    $fields_n_values fields and their new values
1719
+		 * @param EEM_Base $model           the model being queried
1720
+		 * @param array    $query_params    see EEM_Base::get_all()
1721
+		 */
1722
+		$fields_n_values = (array) apply_filters(
1723
+			'FHEE__EEM_Base__update__fields_n_values',
1724
+			$fields_n_values,
1725
+			$this,
1726
+			$query_params
1727
+		);
1728
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1729
+		// to do that, for each table, verify that it's PK isn't null.
1730
+		$tables = $this->get_tables();
1731
+		// 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
1732
+		// NOTE: we should make this code more efficient by NOT querying twice
1733
+		// before the real update, but that needs to first go through ALPHA testing
1734
+		// as it's dangerous. says Mike August 8 2014
1735
+		// we want to make sure the default_where strategy is ignored
1736
+		$this->_ignore_where_strategy = true;
1737
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1738
+		foreach ($wpdb_select_results as $wpdb_result) {
1739
+			// type cast stdClass as array
1740
+			$wpdb_result = (array) $wpdb_result;
1741
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1742
+			if ($this->has_primary_key_field()) {
1743
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1744
+			} else {
1745
+				// 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)
1746
+				$main_table_pk_value = null;
1747
+			}
1748
+			// 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
1749
+			// 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
1750
+			if (count($tables) > 1) {
1751
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1752
+				// in that table, and so we'll want to insert one
1753
+				foreach ($tables as $table_obj) {
1754
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1755
+					// if there is no private key for this table on the results, it means there's no entry
1756
+					// in this table, right? so insert a row in the current table, using any fields available
1757
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1758
+						   && $wpdb_result[ $this_table_pk_column ])
1759
+					) {
1760
+						$success = $this->_insert_into_specific_table(
1761
+							$table_obj,
1762
+							$fields_n_values,
1763
+							$main_table_pk_value
1764
+						);
1765
+						// if we died here, report the error
1766
+						if (! $success) {
1767
+							return false;
1768
+						}
1769
+					}
1770
+				}
1771
+			}
1772
+			//              //and now check that if we have cached any models by that ID on the model, that
1773
+			//              //they also get updated properly
1774
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1775
+			//              if( $model_object ){
1776
+			//                  foreach( $fields_n_values as $field => $value ){
1777
+			//                      $model_object->set($field, $value);
1778
+			// let's make sure default_where strategy is followed now
1779
+			$this->_ignore_where_strategy = false;
1780
+		}
1781
+		// if we want to keep model objects in sync, AND
1782
+		// if this wasn't called from a model object (to update itself)
1783
+		// then we want to make sure we keep all the existing
1784
+		// model objects in sync with the db
1785
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1786
+			if ($this->has_primary_key_field()) {
1787
+				$model_objs_affected_ids = $this->get_col($query_params);
1788
+			} else {
1789
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1790
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1791
+				$model_objs_affected_ids = array();
1792
+				foreach ($models_affected_key_columns as $row) {
1793
+					$combined_index_key = $this->get_index_primary_key_string($row);
1794
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1795
+				}
1796
+			}
1797
+			if (! $model_objs_affected_ids) {
1798
+				// wait wait wait- if nothing was affected let's stop here
1799
+				return 0;
1800
+			}
1801
+			foreach ($model_objs_affected_ids as $id) {
1802
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1803
+				if ($model_obj_in_entity_map) {
1804
+					foreach ($fields_n_values as $field => $new_value) {
1805
+						$model_obj_in_entity_map->set($field, $new_value);
1806
+					}
1807
+				}
1808
+			}
1809
+			// if there is a primary key on this model, we can now do a slight optimization
1810
+			if ($this->has_primary_key_field()) {
1811
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1812
+				$query_params = array(
1813
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1814
+					'limit'                    => count($model_objs_affected_ids),
1815
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1816
+				);
1817
+			}
1818
+		}
1819
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1820
+		$SQL = "UPDATE "
1821
+			   . $model_query_info->get_full_join_sql()
1822
+			   . " SET "
1823
+			   . $this->_construct_update_sql($fields_n_values)
1824
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1825
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1826
+		/**
1827
+		 * Action called after a model update call has been made.
1828
+		 *
1829
+		 * @param EEM_Base $model
1830
+		 * @param array    $fields_n_values the updated fields and their new values
1831
+		 * @param array    $query_params    @see EEM_Base::get_all()
1832
+		 * @param int      $rows_affected
1833
+		 */
1834
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1835
+		return $rows_affected;// how many supposedly got updated
1836
+	}
1837
+
1838
+
1839
+
1840
+	/**
1841
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1842
+	 * are teh values of the field specified (or by default the primary key field)
1843
+	 * that matched the query params. Note that you should pass the name of the
1844
+	 * model FIELD, not the database table's column name.
1845
+	 *
1846
+	 * @param array  $query_params @see EEM_Base::get_all()
1847
+	 * @param string $field_to_select
1848
+	 * @return array just like $wpdb->get_col()
1849
+	 * @throws EE_Error
1850
+	 */
1851
+	public function get_col($query_params = array(), $field_to_select = null)
1852
+	{
1853
+		if ($field_to_select) {
1854
+			$field = $this->field_settings_for($field_to_select);
1855
+		} elseif ($this->has_primary_key_field()) {
1856
+			$field = $this->get_primary_key_field();
1857
+		} else {
1858
+			// no primary key, just grab the first column
1859
+			$field = reset($this->field_settings());
1860
+		}
1861
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1862
+		$select_expressions = $field->get_qualified_column();
1863
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1864
+		return $this->_do_wpdb_query('get_col', array($SQL));
1865
+	}
1866
+
1867
+
1868
+
1869
+	/**
1870
+	 * Returns a single column value for a single row from the database
1871
+	 *
1872
+	 * @param array  $query_params    @see EEM_Base::get_all()
1873
+	 * @param string $field_to_select @see EEM_Base::get_col()
1874
+	 * @return string
1875
+	 * @throws EE_Error
1876
+	 */
1877
+	public function get_var($query_params = array(), $field_to_select = null)
1878
+	{
1879
+		$query_params['limit'] = 1;
1880
+		$col = $this->get_col($query_params, $field_to_select);
1881
+		if (! empty($col)) {
1882
+			return reset($col);
1883
+		}
1884
+		return null;
1885
+	}
1886
+
1887
+
1888
+
1889
+	/**
1890
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1891
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1892
+	 * injection, but currently no further filtering is done
1893
+	 *
1894
+	 * @global      $wpdb
1895
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1896
+	 *                               be updated to in the DB
1897
+	 * @return string of SQL
1898
+	 * @throws EE_Error
1899
+	 */
1900
+	public function _construct_update_sql($fields_n_values)
1901
+	{
1902
+		/** @type WPDB $wpdb */
1903
+		global $wpdb;
1904
+		$cols_n_values = array();
1905
+		foreach ($fields_n_values as $field_name => $value) {
1906
+			$field_obj = $this->field_settings_for($field_name);
1907
+			// if the value is NULL, we want to assign the value to that.
1908
+			// wpdb->prepare doesn't really handle that properly
1909
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1910
+			$value_sql = $prepared_value === null ? 'NULL'
1911
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1912
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1913
+		}
1914
+		return implode(",", $cols_n_values);
1915
+	}
1916
+
1917
+
1918
+
1919
+	/**
1920
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1921
+	 * Performs a HARD delete, meaning the database row should always be removed,
1922
+	 * not just have a flag field on it switched
1923
+	 * Wrapper for EEM_Base::delete_permanently()
1924
+	 *
1925
+	 * @param mixed $id
1926
+	 * @param boolean $allow_blocking
1927
+	 * @return int the number of rows deleted
1928
+	 * @throws EE_Error
1929
+	 */
1930
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1931
+	{
1932
+		return $this->delete_permanently(
1933
+			array(
1934
+				array($this->get_primary_key_field()->get_name() => $id),
1935
+				'limit' => 1,
1936
+			),
1937
+			$allow_blocking
1938
+		);
1939
+	}
1940
+
1941
+
1942
+
1943
+	/**
1944
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1945
+	 * Wrapper for EEM_Base::delete()
1946
+	 *
1947
+	 * @param mixed $id
1948
+	 * @param boolean $allow_blocking
1949
+	 * @return int the number of rows deleted
1950
+	 * @throws EE_Error
1951
+	 */
1952
+	public function delete_by_ID($id, $allow_blocking = true)
1953
+	{
1954
+		return $this->delete(
1955
+			array(
1956
+				array($this->get_primary_key_field()->get_name() => $id),
1957
+				'limit' => 1,
1958
+			),
1959
+			$allow_blocking
1960
+		);
1961
+	}
1962
+
1963
+
1964
+
1965
+	/**
1966
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1967
+	 * meaning if the model has a field that indicates its been "trashed" or
1968
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1969
+	 *
1970
+	 * @see EEM_Base::delete_permanently
1971
+	 * @param array   $query_params
1972
+	 * @param boolean $allow_blocking
1973
+	 * @return int how many rows got deleted
1974
+	 * @throws EE_Error
1975
+	 */
1976
+	public function delete($query_params, $allow_blocking = true)
1977
+	{
1978
+		return $this->delete_permanently($query_params, $allow_blocking);
1979
+	}
1980
+
1981
+
1982
+
1983
+	/**
1984
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1985
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1986
+	 * as archived, not actually deleted
1987
+	 *
1988
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1989
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1990
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1991
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1992
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1993
+	 *                                DB
1994
+	 * @return int how many rows got deleted
1995
+	 * @throws EE_Error
1996
+	 */
1997
+	public function delete_permanently($query_params, $allow_blocking = true)
1998
+	{
1999
+		/**
2000
+		 * Action called just before performing a real deletion query. You can use the
2001
+		 * model and its $query_params to find exactly which items will be deleted
2002
+		 *
2003
+		 * @param EEM_Base $model
2004
+		 * @param array    $query_params   @see EEM_Base::get_all()
2005
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
2006
+		 *                                 to block (prevent) this deletion
2007
+		 */
2008
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
2009
+		// some MySQL databases may be running safe mode, which may restrict
2010
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
2011
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
2012
+		// to delete them
2013
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
2014
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2015
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
2016
+			$columns_and_ids_for_deleting
2017
+		);
2018
+		/**
2019
+		 * Allows client code to act on the items being deleted before the query is actually executed.
2020
+		 *
2021
+		 * @param EEM_Base $this  The model instance being acted on.
2022
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2023
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
2024
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
2025
+		 *                                                  derived from the incoming query parameters.
2026
+		 *                                                  @see details on the structure of this array in the phpdocs
2027
+		 *                                                  for the `_get_ids_for_delete_method`
2028
+		 *
2029
+		 */
2030
+		do_action(
2031
+			'AHEE__EEM_Base__delete__before_query',
2032
+			$this,
2033
+			$query_params,
2034
+			$allow_blocking,
2035
+			$columns_and_ids_for_deleting
2036
+		);
2037
+		if ($deletion_where_query_part) {
2038
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2039
+			$table_aliases = array_keys($this->_tables);
2040
+			$SQL = "DELETE "
2041
+				   . implode(", ", $table_aliases)
2042
+				   . " FROM "
2043
+				   . $model_query_info->get_full_join_sql()
2044
+				   . " WHERE "
2045
+				   . $deletion_where_query_part;
2046
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2047
+		} else {
2048
+			$rows_deleted = 0;
2049
+		}
2050
+
2051
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2052
+		// there was no error with the delete query.
2053
+		if ($this->has_primary_key_field()
2054
+			&& $rows_deleted !== false
2055
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2056
+		) {
2057
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2058
+			foreach ($ids_for_removal as $id) {
2059
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2060
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2061
+				}
2062
+			}
2063
+
2064
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2065
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2066
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2067
+			// (although it is possible).
2068
+			// Note this can be skipped by using the provided filter and returning false.
2069
+			if (apply_filters(
2070
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2071
+				! $this instanceof EEM_Extra_Meta,
2072
+				$this
2073
+			)) {
2074
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2075
+					0 => array(
2076
+						'EXM_type' => $this->get_this_model_name(),
2077
+						'OBJ_ID'   => array(
2078
+							'IN',
2079
+							$ids_for_removal
2080
+						)
2081
+					)
2082
+				));
2083
+			}
2084
+		}
2085
+
2086
+		/**
2087
+		 * Action called just after performing a real deletion query. Although at this point the
2088
+		 * items should have been deleted
2089
+		 *
2090
+		 * @param EEM_Base $model
2091
+		 * @param array    $query_params @see EEM_Base::get_all()
2092
+		 * @param int      $rows_deleted
2093
+		 */
2094
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2095
+		return $rows_deleted;// how many supposedly got deleted
2096
+	}
2097
+
2098
+
2099
+
2100
+	/**
2101
+	 * Checks all the relations that throw error messages when there are blocking related objects
2102
+	 * for related model objects. If there are any related model objects on those relations,
2103
+	 * adds an EE_Error, and return true
2104
+	 *
2105
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2106
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2107
+	 *                                                 should be ignored when determining whether there are related
2108
+	 *                                                 model objects which block this model object's deletion. Useful
2109
+	 *                                                 if you know A is related to B and are considering deleting A,
2110
+	 *                                                 but want to see if A has any other objects blocking its deletion
2111
+	 *                                                 before removing the relation between A and B
2112
+	 * @return boolean
2113
+	 * @throws EE_Error
2114
+	 */
2115
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2116
+	{
2117
+		// first, if $ignore_this_model_obj was supplied, get its model
2118
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2119
+			$ignored_model = $ignore_this_model_obj->get_model();
2120
+		} else {
2121
+			$ignored_model = null;
2122
+		}
2123
+		// now check all the relations of $this_model_obj_or_id and see if there
2124
+		// are any related model objects blocking it?
2125
+		$is_blocked = false;
2126
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2127
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2128
+				// if $ignore_this_model_obj was supplied, then for the query
2129
+				// on that model needs to be told to ignore $ignore_this_model_obj
2130
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2131
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2132
+						array(
2133
+							$ignored_model->get_primary_key_field()->get_name() => array(
2134
+								'!=',
2135
+								$ignore_this_model_obj->ID(),
2136
+							),
2137
+						),
2138
+					));
2139
+				} else {
2140
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2141
+				}
2142
+				if ($related_model_objects) {
2143
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2144
+					$is_blocked = true;
2145
+				}
2146
+			}
2147
+		}
2148
+		return $is_blocked;
2149
+	}
2150
+
2151
+
2152
+	/**
2153
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2154
+	 * @param array $row_results_for_deleting
2155
+	 * @param bool  $allow_blocking
2156
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2157
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2158
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2159
+	 *                 deleted. Example:
2160
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2161
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2162
+	 *                 where each element is a group of columns and values that get deleted. Example:
2163
+	 *                      array(
2164
+	 *                          0 => array(
2165
+	 *                              'Term_Relationship.object_id' => 1
2166
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2167
+	 *                          ),
2168
+	 *                          1 => array(
2169
+	 *                              'Term_Relationship.object_id' => 1
2170
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2171
+	 *                          )
2172
+	 *                      )
2173
+	 * @throws EE_Error
2174
+	 */
2175
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2176
+	{
2177
+		$ids_to_delete_indexed_by_column = array();
2178
+		if ($this->has_primary_key_field()) {
2179
+			$primary_table = $this->_get_main_table();
2180
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2181
+			$other_tables = $this->_get_other_tables();
2182
+			$ids_to_delete_indexed_by_column = $query = array();
2183
+			foreach ($row_results_for_deleting as $item_to_delete) {
2184
+				// before we mark this item for deletion,
2185
+				// make sure there's no related entities blocking its deletion (if we're checking)
2186
+				if ($allow_blocking
2187
+					&& $this->delete_is_blocked_by_related_models(
2188
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2189
+					)
2190
+				) {
2191
+					continue;
2192
+				}
2193
+				// primary table deletes
2194
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2195
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2196
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2197
+				}
2198
+			}
2199
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2200
+			$fields = $this->get_combined_primary_key_fields();
2201
+			foreach ($row_results_for_deleting as $item_to_delete) {
2202
+				$ids_to_delete_indexed_by_column_for_row = array();
2203
+				foreach ($fields as $cpk_field) {
2204
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2205
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2206
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2207
+					}
2208
+				}
2209
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2210
+			}
2211
+		} else {
2212
+			// so there's no primary key and no combined key...
2213
+			// sorry, can't help you
2214
+			throw new EE_Error(
2215
+				sprintf(
2216
+					__(
2217
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2218
+						"event_espresso"
2219
+					),
2220
+					get_class($this)
2221
+				)
2222
+			);
2223
+		}
2224
+		return $ids_to_delete_indexed_by_column;
2225
+	}
2226
+
2227
+
2228
+	/**
2229
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2230
+	 * the corresponding query_part for the query performing the delete.
2231
+	 *
2232
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2233
+	 * @return string
2234
+	 * @throws EE_Error
2235
+	 */
2236
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2237
+	{
2238
+		$query_part = '';
2239
+		if (empty($ids_to_delete_indexed_by_column)) {
2240
+			return $query_part;
2241
+		} elseif ($this->has_primary_key_field()) {
2242
+			$query = array();
2243
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2244
+				// make sure we have unique $ids
2245
+				$ids = array_unique($ids);
2246
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2247
+			}
2248
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2249
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2250
+			$ways_to_identify_a_row = array();
2251
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2252
+				$values_for_each_combined_primary_key_for_a_row = array();
2253
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2254
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2255
+				}
2256
+				$ways_to_identify_a_row[] = '('
2257
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2258
+											. ')';
2259
+			}
2260
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2261
+		}
2262
+		return $query_part;
2263
+	}
2264
+
2265
+
2266
+
2267
+	/**
2268
+	 * Gets the model field by the fully qualified name
2269
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2270
+	 * @return EE_Model_Field_Base
2271
+	 */
2272
+	public function get_field_by_column($qualified_column_name)
2273
+	{
2274
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2275
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2276
+				return $field_obj;
2277
+			}
2278
+		}
2279
+		throw new EE_Error(
2280
+			sprintf(
2281
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2282
+				$this->get_this_model_name(),
2283
+				$qualified_column_name
2284
+			)
2285
+		);
2286
+	}
2287
+
2288
+
2289
+
2290
+	/**
2291
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2292
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2293
+	 * column
2294
+	 *
2295
+	 * @param array  $query_params   like EEM_Base::get_all's
2296
+	 * @param string $field_to_count field on model to count by (not column name)
2297
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2298
+	 *                               that by the setting $distinct to TRUE;
2299
+	 * @return int
2300
+	 * @throws EE_Error
2301
+	 */
2302
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2303
+	{
2304
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2305
+		if ($field_to_count) {
2306
+			$field_obj = $this->field_settings_for($field_to_count);
2307
+			$column_to_count = $field_obj->get_qualified_column();
2308
+		} elseif ($this->has_primary_key_field()) {
2309
+			$pk_field_obj = $this->get_primary_key_field();
2310
+			$column_to_count = $pk_field_obj->get_qualified_column();
2311
+		} else {
2312
+			// there's no primary key
2313
+			// if we're counting distinct items, and there's no primary key,
2314
+			// we need to list out the columns for distinction;
2315
+			// otherwise we can just use star
2316
+			if ($distinct) {
2317
+				$columns_to_use = array();
2318
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2319
+					$columns_to_use[] = $field_obj->get_qualified_column();
2320
+				}
2321
+				$column_to_count = implode(',', $columns_to_use);
2322
+			} else {
2323
+				$column_to_count = '*';
2324
+			}
2325
+		}
2326
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2327
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2328
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2329
+	}
2330
+
2331
+
2332
+
2333
+	/**
2334
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2335
+	 *
2336
+	 * @param array  $query_params like EEM_Base::get_all
2337
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2338
+	 * @return float
2339
+	 * @throws EE_Error
2340
+	 */
2341
+	public function sum($query_params, $field_to_sum = null)
2342
+	{
2343
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2344
+		if ($field_to_sum) {
2345
+			$field_obj = $this->field_settings_for($field_to_sum);
2346
+		} else {
2347
+			$field_obj = $this->get_primary_key_field();
2348
+		}
2349
+		$column_to_count = $field_obj->get_qualified_column();
2350
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2351
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2352
+		$data_type = $field_obj->get_wpdb_data_type();
2353
+		if ($data_type === '%d' || $data_type === '%s') {
2354
+			return (float) $return_value;
2355
+		}
2356
+		// must be %f
2357
+		return (float) $return_value;
2358
+	}
2359
+
2360
+
2361
+
2362
+	/**
2363
+	 * Just calls the specified method on $wpdb with the given arguments
2364
+	 * Consolidates a little extra error handling code
2365
+	 *
2366
+	 * @param string $wpdb_method
2367
+	 * @param array  $arguments_to_provide
2368
+	 * @throws EE_Error
2369
+	 * @global wpdb  $wpdb
2370
+	 * @return mixed
2371
+	 */
2372
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2373
+	{
2374
+		// if we're in maintenance mode level 2, DON'T run any queries
2375
+		// because level 2 indicates the database needs updating and
2376
+		// is probably out of sync with the code
2377
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2378
+			throw new EE_Error(sprintf(__(
2379
+				"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.",
2380
+				"event_espresso"
2381
+			)));
2382
+		}
2383
+		/** @type WPDB $wpdb */
2384
+		global $wpdb;
2385
+		if (! method_exists($wpdb, $wpdb_method)) {
2386
+			throw new EE_Error(sprintf(__(
2387
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2388
+				'event_espresso'
2389
+			), $wpdb_method));
2390
+		}
2391
+		if (WP_DEBUG) {
2392
+			$old_show_errors_value = $wpdb->show_errors;
2393
+			$wpdb->show_errors(false);
2394
+		}
2395
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2396
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2397
+		if (WP_DEBUG) {
2398
+			$wpdb->show_errors($old_show_errors_value);
2399
+			if (! empty($wpdb->last_error)) {
2400
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2401
+			}
2402
+			if ($result === false) {
2403
+				throw new EE_Error(sprintf(__(
2404
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2405
+					'event_espresso'
2406
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2407
+			}
2408
+		} elseif ($result === false) {
2409
+			EE_Error::add_error(
2410
+				sprintf(
2411
+					__(
2412
+						'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"',
2413
+						'event_espresso'
2414
+					),
2415
+					$wpdb_method,
2416
+					var_export($arguments_to_provide, true),
2417
+					$wpdb->last_error
2418
+				),
2419
+				__FILE__,
2420
+				__FUNCTION__,
2421
+				__LINE__
2422
+			);
2423
+		}
2424
+		return $result;
2425
+	}
2426
+
2427
+
2428
+
2429
+	/**
2430
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2431
+	 * and if there's an error tries to verify the DB is correct. Uses
2432
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2433
+	 * we should try to fix the EE core db, the addons, or just give up
2434
+	 *
2435
+	 * @param string $wpdb_method
2436
+	 * @param array  $arguments_to_provide
2437
+	 * @return mixed
2438
+	 */
2439
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2440
+	{
2441
+		/** @type WPDB $wpdb */
2442
+		global $wpdb;
2443
+		$wpdb->last_error = null;
2444
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2445
+		// was there an error running the query? but we don't care on new activations
2446
+		// (we're going to setup the DB anyway on new activations)
2447
+		if (($result === false || ! empty($wpdb->last_error))
2448
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2449
+		) {
2450
+			switch (EEM_Base::$_db_verification_level) {
2451
+				case EEM_Base::db_verified_none:
2452
+					// let's double-check core's DB
2453
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2454
+					break;
2455
+				case EEM_Base::db_verified_core:
2456
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2457
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2458
+					break;
2459
+				case EEM_Base::db_verified_addons:
2460
+					// ummmm... you in trouble
2461
+					return $result;
2462
+					break;
2463
+			}
2464
+			if (! empty($error_message)) {
2465
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2466
+				trigger_error($error_message);
2467
+			}
2468
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2469
+		}
2470
+		return $result;
2471
+	}
2472
+
2473
+
2474
+
2475
+	/**
2476
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2477
+	 * EEM_Base::$_db_verification_level
2478
+	 *
2479
+	 * @param string $wpdb_method
2480
+	 * @param array  $arguments_to_provide
2481
+	 * @return string
2482
+	 */
2483
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2484
+	{
2485
+		/** @type WPDB $wpdb */
2486
+		global $wpdb;
2487
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2488
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2489
+		$error_message = sprintf(
2490
+			__(
2491
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2492
+				'event_espresso'
2493
+			),
2494
+			$wpdb->last_error,
2495
+			$wpdb_method,
2496
+			wp_json_encode($arguments_to_provide)
2497
+		);
2498
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2499
+		return $error_message;
2500
+	}
2501
+
2502
+
2503
+
2504
+	/**
2505
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2506
+	 * EEM_Base::$_db_verification_level
2507
+	 *
2508
+	 * @param $wpdb_method
2509
+	 * @param $arguments_to_provide
2510
+	 * @return string
2511
+	 */
2512
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2513
+	{
2514
+		/** @type WPDB $wpdb */
2515
+		global $wpdb;
2516
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2517
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2518
+		$error_message = sprintf(
2519
+			__(
2520
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2521
+				'event_espresso'
2522
+			),
2523
+			$wpdb->last_error,
2524
+			$wpdb_method,
2525
+			wp_json_encode($arguments_to_provide)
2526
+		);
2527
+		EE_System::instance()->initialize_addons();
2528
+		return $error_message;
2529
+	}
2530
+
2531
+
2532
+
2533
+	/**
2534
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2535
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2536
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2537
+	 * ..."
2538
+	 *
2539
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2540
+	 * @return string
2541
+	 */
2542
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2543
+	{
2544
+		return " FROM " . $model_query_info->get_full_join_sql() .
2545
+			   $model_query_info->get_where_sql() .
2546
+			   $model_query_info->get_group_by_sql() .
2547
+			   $model_query_info->get_having_sql() .
2548
+			   $model_query_info->get_order_by_sql() .
2549
+			   $model_query_info->get_limit_sql();
2550
+	}
2551
+
2552
+
2553
+
2554
+	/**
2555
+	 * Set to easily debug the next X queries ran from this model.
2556
+	 *
2557
+	 * @param int $count
2558
+	 */
2559
+	public function show_next_x_db_queries($count = 1)
2560
+	{
2561
+		$this->_show_next_x_db_queries = $count;
2562
+	}
2563
+
2564
+
2565
+
2566
+	/**
2567
+	 * @param $sql_query
2568
+	 */
2569
+	public function show_db_query_if_previously_requested($sql_query)
2570
+	{
2571
+		if ($this->_show_next_x_db_queries > 0) {
2572
+			echo $sql_query;
2573
+			$this->_show_next_x_db_queries--;
2574
+		}
2575
+	}
2576
+
2577
+
2578
+
2579
+	/**
2580
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2581
+	 * There are the 3 cases:
2582
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2583
+	 * $otherModelObject has no ID, it is first saved.
2584
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2585
+	 * has no ID, it is first saved.
2586
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2587
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2588
+	 * join table
2589
+	 *
2590
+	 * @param        EE_Base_Class                     /int $thisModelObject
2591
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2592
+	 * @param string $relationName                     , key in EEM_Base::_relations
2593
+	 *                                                 an attendee to a group, you also want to specify which role they
2594
+	 *                                                 will have in that group. So you would use this parameter to
2595
+	 *                                                 specify array('role-column-name'=>'role-id')
2596
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2597
+	 *                                                 to for relation to methods that allow you to further specify
2598
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2599
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2600
+	 *                                                 because these will be inserted in any new rows created as well.
2601
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2602
+	 * @throws EE_Error
2603
+	 */
2604
+	public function add_relationship_to(
2605
+		$id_or_obj,
2606
+		$other_model_id_or_obj,
2607
+		$relationName,
2608
+		$extra_join_model_fields_n_values = array()
2609
+	) {
2610
+		$relation_obj = $this->related_settings_for($relationName);
2611
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2612
+	}
2613
+
2614
+
2615
+
2616
+	/**
2617
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2618
+	 * There are the 3 cases:
2619
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2620
+	 * error
2621
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2622
+	 * an error
2623
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2624
+	 *
2625
+	 * @param        EE_Base_Class /int $id_or_obj
2626
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2627
+	 * @param string $relationName key in EEM_Base::_relations
2628
+	 * @return boolean of success
2629
+	 * @throws EE_Error
2630
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2631
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2632
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2633
+	 *                             because these will be inserted in any new rows created as well.
2634
+	 */
2635
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2636
+	{
2637
+		$relation_obj = $this->related_settings_for($relationName);
2638
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2639
+	}
2640
+
2641
+
2642
+
2643
+	/**
2644
+	 * @param mixed           $id_or_obj
2645
+	 * @param string          $relationName
2646
+	 * @param array           $where_query_params
2647
+	 * @param EE_Base_Class[] objects to which relations were removed
2648
+	 * @return \EE_Base_Class[]
2649
+	 * @throws EE_Error
2650
+	 */
2651
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2652
+	{
2653
+		$relation_obj = $this->related_settings_for($relationName);
2654
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2655
+	}
2656
+
2657
+
2658
+
2659
+	/**
2660
+	 * Gets all the related items of the specified $model_name, using $query_params.
2661
+	 * Note: by default, we remove the "default query params"
2662
+	 * because we want to get even deleted items etc.
2663
+	 *
2664
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2665
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2666
+	 * @param array  $query_params like EEM_Base::get_all
2667
+	 * @return EE_Base_Class[]
2668
+	 * @throws EE_Error
2669
+	 */
2670
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2671
+	{
2672
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2673
+		$relation_settings = $this->related_settings_for($model_name);
2674
+		return $relation_settings->get_all_related($model_obj, $query_params);
2675
+	}
2676
+
2677
+
2678
+
2679
+	/**
2680
+	 * Deletes all the model objects across the relation indicated by $model_name
2681
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2682
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2683
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2684
+	 *
2685
+	 * @param EE_Base_Class|int|string $id_or_obj
2686
+	 * @param string                   $model_name
2687
+	 * @param array                    $query_params
2688
+	 * @return int how many deleted
2689
+	 * @throws EE_Error
2690
+	 */
2691
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2692
+	{
2693
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2694
+		$relation_settings = $this->related_settings_for($model_name);
2695
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2696
+	}
2697
+
2698
+
2699
+
2700
+	/**
2701
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2702
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2703
+	 * the model objects can't be hard deleted because of blocking related model objects,
2704
+	 * just does a soft-delete on them instead.
2705
+	 *
2706
+	 * @param EE_Base_Class|int|string $id_or_obj
2707
+	 * @param string                   $model_name
2708
+	 * @param array                    $query_params
2709
+	 * @return int how many deleted
2710
+	 * @throws EE_Error
2711
+	 */
2712
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2713
+	{
2714
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2715
+		$relation_settings = $this->related_settings_for($model_name);
2716
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2717
+	}
2718
+
2719
+
2720
+
2721
+	/**
2722
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2723
+	 * unless otherwise specified in the $query_params
2724
+	 *
2725
+	 * @param        int             /EE_Base_Class $id_or_obj
2726
+	 * @param string $model_name     like 'Event', or 'Registration'
2727
+	 * @param array  $query_params   like EEM_Base::get_all's
2728
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2729
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2730
+	 *                               that by the setting $distinct to TRUE;
2731
+	 * @return int
2732
+	 * @throws EE_Error
2733
+	 */
2734
+	public function count_related(
2735
+		$id_or_obj,
2736
+		$model_name,
2737
+		$query_params = array(),
2738
+		$field_to_count = null,
2739
+		$distinct = false
2740
+	) {
2741
+		$related_model = $this->get_related_model_obj($model_name);
2742
+		// we're just going to use the query params on the related model's normal get_all query,
2743
+		// except add a condition to say to match the current mod
2744
+		if (! isset($query_params['default_where_conditions'])) {
2745
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2746
+		}
2747
+		$this_model_name = $this->get_this_model_name();
2748
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2749
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2750
+		return $related_model->count($query_params, $field_to_count, $distinct);
2751
+	}
2752
+
2753
+
2754
+
2755
+	/**
2756
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2757
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2758
+	 *
2759
+	 * @param        int           /EE_Base_Class $id_or_obj
2760
+	 * @param string $model_name   like 'Event', or 'Registration'
2761
+	 * @param array  $query_params like EEM_Base::get_all's
2762
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2763
+	 * @return float
2764
+	 * @throws EE_Error
2765
+	 */
2766
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2767
+	{
2768
+		$related_model = $this->get_related_model_obj($model_name);
2769
+		if (! is_array($query_params)) {
2770
+			EE_Error::doing_it_wrong(
2771
+				'EEM_Base::sum_related',
2772
+				sprintf(
2773
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2774
+					gettype($query_params)
2775
+				),
2776
+				'4.6.0'
2777
+			);
2778
+			$query_params = array();
2779
+		}
2780
+		// we're just going to use the query params on the related model's normal get_all query,
2781
+		// except add a condition to say to match the current mod
2782
+		if (! isset($query_params['default_where_conditions'])) {
2783
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2784
+		}
2785
+		$this_model_name = $this->get_this_model_name();
2786
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2787
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2788
+		return $related_model->sum($query_params, $field_to_sum);
2789
+	}
2790
+
2791
+
2792
+
2793
+	/**
2794
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2795
+	 * $modelObject
2796
+	 *
2797
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2798
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2799
+	 * @param array               $query_params     like EEM_Base::get_all's
2800
+	 * @return EE_Base_Class
2801
+	 * @throws EE_Error
2802
+	 */
2803
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2804
+	{
2805
+		$query_params['limit'] = 1;
2806
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2807
+		if ($results) {
2808
+			return array_shift($results);
2809
+		}
2810
+		return null;
2811
+	}
2812
+
2813
+
2814
+
2815
+	/**
2816
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2817
+	 *
2818
+	 * @return string
2819
+	 */
2820
+	public function get_this_model_name()
2821
+	{
2822
+		return str_replace("EEM_", "", get_class($this));
2823
+	}
2824
+
2825
+
2826
+
2827
+	/**
2828
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2829
+	 *
2830
+	 * @return EE_Any_Foreign_Model_Name_Field
2831
+	 * @throws EE_Error
2832
+	 */
2833
+	public function get_field_containing_related_model_name()
2834
+	{
2835
+		foreach ($this->field_settings(true) as $field) {
2836
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2837
+				$field_with_model_name = $field;
2838
+			}
2839
+		}
2840
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2841
+			throw new EE_Error(sprintf(
2842
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2843
+				$this->get_this_model_name()
2844
+			));
2845
+		}
2846
+		return $field_with_model_name;
2847
+	}
2848
+
2849
+
2850
+
2851
+	/**
2852
+	 * Inserts a new entry into the database, for each table.
2853
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2854
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2855
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2856
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2857
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2858
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2859
+	 *
2860
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2861
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2862
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2863
+	 *                              of EEM_Base)
2864
+	 * @return int new primary key on main table that got inserted
2865
+	 * @throws EE_Error
2866
+	 */
2867
+	public function insert($field_n_values)
2868
+	{
2869
+		/**
2870
+		 * Filters the fields and their values before inserting an item using the models
2871
+		 *
2872
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2873
+		 * @param EEM_Base $model           the model used
2874
+		 */
2875
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2876
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2877
+			$main_table = $this->_get_main_table();
2878
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2879
+			if ($new_id !== false) {
2880
+				foreach ($this->_get_other_tables() as $other_table) {
2881
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2882
+				}
2883
+			}
2884
+			/**
2885
+			 * Done just after attempting to insert a new model object
2886
+			 *
2887
+			 * @param EEM_Base   $model           used
2888
+			 * @param array      $fields_n_values fields and their values
2889
+			 * @param int|string the              ID of the newly-inserted model object
2890
+			 */
2891
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2892
+			return $new_id;
2893
+		}
2894
+		return false;
2895
+	}
2896
+
2897
+
2898
+
2899
+	/**
2900
+	 * Checks that the result would satisfy the unique indexes on this model
2901
+	 *
2902
+	 * @param array  $field_n_values
2903
+	 * @param string $action
2904
+	 * @return boolean
2905
+	 * @throws EE_Error
2906
+	 */
2907
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2908
+	{
2909
+		foreach ($this->unique_indexes() as $index_name => $index) {
2910
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2911
+			if ($this->exists(array($uniqueness_where_params))) {
2912
+				EE_Error::add_error(
2913
+					sprintf(
2914
+						__(
2915
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2916
+							"event_espresso"
2917
+						),
2918
+						$action,
2919
+						$this->_get_class_name(),
2920
+						$index_name,
2921
+						implode(",", $index->field_names()),
2922
+						http_build_query($uniqueness_where_params)
2923
+					),
2924
+					__FILE__,
2925
+					__FUNCTION__,
2926
+					__LINE__
2927
+				);
2928
+				return false;
2929
+			}
2930
+		}
2931
+		return true;
2932
+	}
2933
+
2934
+
2935
+
2936
+	/**
2937
+	 * Checks the database for an item that conflicts (ie, if this item were
2938
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2939
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2940
+	 * can be either an EE_Base_Class or an array of fields n values
2941
+	 *
2942
+	 * @param EE_Base_Class|array $obj_or_fields_array
2943
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2944
+	 *                                                 when looking for conflicts
2945
+	 *                                                 (ie, if false, we ignore the model object's primary key
2946
+	 *                                                 when finding "conflicts". If true, it's also considered).
2947
+	 *                                                 Only works for INT primary key,
2948
+	 *                                                 STRING primary keys cannot be ignored
2949
+	 * @throws EE_Error
2950
+	 * @return EE_Base_Class|array
2951
+	 */
2952
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2953
+	{
2954
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2955
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2956
+		} elseif (is_array($obj_or_fields_array)) {
2957
+			$fields_n_values = $obj_or_fields_array;
2958
+		} else {
2959
+			throw new EE_Error(
2960
+				sprintf(
2961
+					__(
2962
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2963
+						"event_espresso"
2964
+					),
2965
+					get_class($this),
2966
+					$obj_or_fields_array
2967
+				)
2968
+			);
2969
+		}
2970
+		$query_params = array();
2971
+		if ($this->has_primary_key_field()
2972
+			&& ($include_primary_key
2973
+				|| $this->get_primary_key_field()
2974
+				   instanceof
2975
+				   EE_Primary_Key_String_Field)
2976
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2977
+		) {
2978
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2979
+		}
2980
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2981
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2982
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2983
+		}
2984
+		// if there is nothing to base this search on, then we shouldn't find anything
2985
+		if (empty($query_params)) {
2986
+			return array();
2987
+		}
2988
+		return $this->get_one($query_params);
2989
+	}
2990
+
2991
+
2992
+
2993
+	/**
2994
+	 * Like count, but is optimized and returns a boolean instead of an int
2995
+	 *
2996
+	 * @param array $query_params
2997
+	 * @return boolean
2998
+	 * @throws EE_Error
2999
+	 */
3000
+	public function exists($query_params)
3001
+	{
3002
+		$query_params['limit'] = 1;
3003
+		return $this->count($query_params) > 0;
3004
+	}
3005
+
3006
+
3007
+
3008
+	/**
3009
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
3010
+	 *
3011
+	 * @param int|string $id
3012
+	 * @return boolean
3013
+	 * @throws EE_Error
3014
+	 */
3015
+	public function exists_by_ID($id)
3016
+	{
3017
+		return $this->exists(
3018
+			array(
3019
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3020
+				array(
3021
+					$this->primary_key_name() => $id,
3022
+				),
3023
+			)
3024
+		);
3025
+	}
3026
+
3027
+
3028
+
3029
+	/**
3030
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3031
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3032
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3033
+	 * on the main table)
3034
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3035
+	 * cases where we want to call it directly rather than via insert().
3036
+	 *
3037
+	 * @access   protected
3038
+	 * @param EE_Table_Base $table
3039
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3040
+	 *                                       float
3041
+	 * @param int           $new_id          for now we assume only int keys
3042
+	 * @throws EE_Error
3043
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3044
+	 * @return int ID of new row inserted, or FALSE on failure
3045
+	 */
3046
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3047
+	{
3048
+		global $wpdb;
3049
+		$insertion_col_n_values = array();
3050
+		$format_for_insertion = array();
3051
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
3052
+		foreach ($fields_on_table as $field_name => $field_obj) {
3053
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3054
+			if ($field_obj->is_auto_increment()) {
3055
+				continue;
3056
+			}
3057
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3058
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3059
+			if ($prepared_value !== null) {
3060
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3061
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
3062
+			}
3063
+		}
3064
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3065
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3066
+			// so add the fk to the main table as a column
3067
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3068
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3069
+		}
3070
+		// insert the new entry
3071
+		$result = $this->_do_wpdb_query(
3072
+			'insert',
3073
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3074
+		);
3075
+		if ($result === false) {
3076
+			return false;
3077
+		}
3078
+		// ok, now what do we return for the ID of the newly-inserted thing?
3079
+		if ($this->has_primary_key_field()) {
3080
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3081
+				return $wpdb->insert_id;
3082
+			}
3083
+			// it's not an auto-increment primary key, so
3084
+			// it must have been supplied
3085
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3086
+		}
3087
+		// we can't return a  primary key because there is none. instead return
3088
+		// a unique string indicating this model
3089
+		return $this->get_index_primary_key_string($fields_n_values);
3090
+	}
3091
+
3092
+
3093
+
3094
+	/**
3095
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3096
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3097
+	 * and there is no default, we pass it along. WPDB will take care of it)
3098
+	 *
3099
+	 * @param EE_Model_Field_Base $field_obj
3100
+	 * @param array               $fields_n_values
3101
+	 * @return mixed string|int|float depending on what the table column will be expecting
3102
+	 * @throws EE_Error
3103
+	 */
3104
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3105
+	{
3106
+		// if this field doesn't allow nullable, don't allow it
3107
+		if (! $field_obj->is_nullable()
3108
+			&& (
3109
+				! isset($fields_n_values[ $field_obj->get_name() ])
3110
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3111
+			)
3112
+		) {
3113
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3114
+		}
3115
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3116
+			? $fields_n_values[ $field_obj->get_name() ]
3117
+			: null;
3118
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3119
+	}
3120
+
3121
+
3122
+
3123
+	/**
3124
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3125
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3126
+	 * the field's prepare_for_set() method.
3127
+	 *
3128
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3129
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3130
+	 *                                   top of file)
3131
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3132
+	 *                                   $value is a custom selection
3133
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3134
+	 */
3135
+	private function _prepare_value_for_use_in_db($value, $field)
3136
+	{
3137
+		if ($field && $field instanceof EE_Model_Field_Base) {
3138
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3139
+			switch ($this->_values_already_prepared_by_model_object) {
3140
+				/** @noinspection PhpMissingBreakStatementInspection */
3141
+				case self::not_prepared_by_model_object:
3142
+					$value = $field->prepare_for_set($value);
3143
+				// purposefully left out "return"
3144
+				case self::prepared_by_model_object:
3145
+					/** @noinspection SuspiciousAssignmentsInspection */
3146
+					$value = $field->prepare_for_use_in_db($value);
3147
+				case self::prepared_for_use_in_db:
3148
+					// leave the value alone
3149
+			}
3150
+			return $value;
3151
+			// phpcs:enable
3152
+		}
3153
+		return $value;
3154
+	}
3155
+
3156
+
3157
+
3158
+	/**
3159
+	 * Returns the main table on this model
3160
+	 *
3161
+	 * @return EE_Primary_Table
3162
+	 * @throws EE_Error
3163
+	 */
3164
+	protected function _get_main_table()
3165
+	{
3166
+		foreach ($this->_tables as $table) {
3167
+			if ($table instanceof EE_Primary_Table) {
3168
+				return $table;
3169
+			}
3170
+		}
3171
+		throw new EE_Error(sprintf(__(
3172
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3173
+			'event_espresso'
3174
+		), get_class($this)));
3175
+	}
3176
+
3177
+
3178
+
3179
+	/**
3180
+	 * table
3181
+	 * returns EE_Primary_Table table name
3182
+	 *
3183
+	 * @return string
3184
+	 * @throws EE_Error
3185
+	 */
3186
+	public function table()
3187
+	{
3188
+		return $this->_get_main_table()->get_table_name();
3189
+	}
3190
+
3191
+
3192
+
3193
+	/**
3194
+	 * table
3195
+	 * returns first EE_Secondary_Table table name
3196
+	 *
3197
+	 * @return string
3198
+	 */
3199
+	public function second_table()
3200
+	{
3201
+		// grab second table from tables array
3202
+		$second_table = end($this->_tables);
3203
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3204
+	}
3205
+
3206
+
3207
+
3208
+	/**
3209
+	 * get_table_obj_by_alias
3210
+	 * returns table name given it's alias
3211
+	 *
3212
+	 * @param string $table_alias
3213
+	 * @return EE_Primary_Table | EE_Secondary_Table
3214
+	 */
3215
+	public function get_table_obj_by_alias($table_alias = '')
3216
+	{
3217
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3218
+	}
3219
+
3220
+
3221
+
3222
+	/**
3223
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3224
+	 *
3225
+	 * @return EE_Secondary_Table[]
3226
+	 */
3227
+	protected function _get_other_tables()
3228
+	{
3229
+		$other_tables = array();
3230
+		foreach ($this->_tables as $table_alias => $table) {
3231
+			if ($table instanceof EE_Secondary_Table) {
3232
+				$other_tables[ $table_alias ] = $table;
3233
+			}
3234
+		}
3235
+		return $other_tables;
3236
+	}
3237
+
3238
+
3239
+
3240
+	/**
3241
+	 * Finds all the fields that correspond to the given table
3242
+	 *
3243
+	 * @param string $table_alias , array key in EEM_Base::_tables
3244
+	 * @return EE_Model_Field_Base[]
3245
+	 */
3246
+	public function _get_fields_for_table($table_alias)
3247
+	{
3248
+		return $this->_fields[ $table_alias ];
3249
+	}
3250
+
3251
+
3252
+
3253
+	/**
3254
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3255
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3256
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3257
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3258
+	 * related Registration, Transaction, and Payment models.
3259
+	 *
3260
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3261
+	 * @return EE_Model_Query_Info_Carrier
3262
+	 * @throws EE_Error
3263
+	 */
3264
+	public function _extract_related_models_from_query($query_params)
3265
+	{
3266
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3267
+		if (array_key_exists(0, $query_params)) {
3268
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3269
+		}
3270
+		if (array_key_exists('group_by', $query_params)) {
3271
+			if (is_array($query_params['group_by'])) {
3272
+				$this->_extract_related_models_from_sub_params_array_values(
3273
+					$query_params['group_by'],
3274
+					$query_info_carrier,
3275
+					'group_by'
3276
+				);
3277
+			} elseif (! empty($query_params['group_by'])) {
3278
+				$this->_extract_related_model_info_from_query_param(
3279
+					$query_params['group_by'],
3280
+					$query_info_carrier,
3281
+					'group_by'
3282
+				);
3283
+			}
3284
+		}
3285
+		if (array_key_exists('having', $query_params)) {
3286
+			$this->_extract_related_models_from_sub_params_array_keys(
3287
+				$query_params[0],
3288
+				$query_info_carrier,
3289
+				'having'
3290
+			);
3291
+		}
3292
+		if (array_key_exists('order_by', $query_params)) {
3293
+			if (is_array($query_params['order_by'])) {
3294
+				$this->_extract_related_models_from_sub_params_array_keys(
3295
+					$query_params['order_by'],
3296
+					$query_info_carrier,
3297
+					'order_by'
3298
+				);
3299
+			} elseif (! empty($query_params['order_by'])) {
3300
+				$this->_extract_related_model_info_from_query_param(
3301
+					$query_params['order_by'],
3302
+					$query_info_carrier,
3303
+					'order_by'
3304
+				);
3305
+			}
3306
+		}
3307
+		if (array_key_exists('force_join', $query_params)) {
3308
+			$this->_extract_related_models_from_sub_params_array_values(
3309
+				$query_params['force_join'],
3310
+				$query_info_carrier,
3311
+				'force_join'
3312
+			);
3313
+		}
3314
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3315
+		return $query_info_carrier;
3316
+	}
3317
+
3318
+
3319
+
3320
+	/**
3321
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3322
+	 *
3323
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3324
+	 *                                                      $query_params['having']
3325
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3326
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3327
+	 * @throws EE_Error
3328
+	 * @return \EE_Model_Query_Info_Carrier
3329
+	 */
3330
+	private function _extract_related_models_from_sub_params_array_keys(
3331
+		$sub_query_params,
3332
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3333
+		$query_param_type
3334
+	) {
3335
+		if (! empty($sub_query_params)) {
3336
+			$sub_query_params = (array) $sub_query_params;
3337
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3338
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3339
+				$this->_extract_related_model_info_from_query_param(
3340
+					$param,
3341
+					$model_query_info_carrier,
3342
+					$query_param_type
3343
+				);
3344
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3345
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3346
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3347
+				// of array('Registration.TXN_ID'=>23)
3348
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3349
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3350
+					if (! is_array($possibly_array_of_params)) {
3351
+						throw new EE_Error(sprintf(
3352
+							__(
3353
+								"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'))",
3354
+								"event_espresso"
3355
+							),
3356
+							$param,
3357
+							$possibly_array_of_params
3358
+						));
3359
+					}
3360
+					$this->_extract_related_models_from_sub_params_array_keys(
3361
+						$possibly_array_of_params,
3362
+						$model_query_info_carrier,
3363
+						$query_param_type
3364
+					);
3365
+				} elseif ($query_param_type === 0 // ie WHERE
3366
+						  && is_array($possibly_array_of_params)
3367
+						  && isset($possibly_array_of_params[2])
3368
+						  && $possibly_array_of_params[2] == true
3369
+				) {
3370
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3371
+					// indicating that $possible_array_of_params[1] is actually a field name,
3372
+					// from which we should extract query parameters!
3373
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3374
+						throw new EE_Error(sprintf(__(
3375
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3376
+							"event_espresso"
3377
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3378
+					}
3379
+					$this->_extract_related_model_info_from_query_param(
3380
+						$possibly_array_of_params[1],
3381
+						$model_query_info_carrier,
3382
+						$query_param_type
3383
+					);
3384
+				}
3385
+			}
3386
+		}
3387
+		return $model_query_info_carrier;
3388
+	}
3389
+
3390
+
3391
+
3392
+	/**
3393
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3394
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3395
+	 *
3396
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3397
+	 *                                                      $query_params['having']
3398
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3399
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3400
+	 * @throws EE_Error
3401
+	 * @return \EE_Model_Query_Info_Carrier
3402
+	 */
3403
+	private function _extract_related_models_from_sub_params_array_values(
3404
+		$sub_query_params,
3405
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3406
+		$query_param_type
3407
+	) {
3408
+		if (! empty($sub_query_params)) {
3409
+			if (! is_array($sub_query_params)) {
3410
+				throw new EE_Error(sprintf(
3411
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3412
+					$sub_query_params
3413
+				));
3414
+			}
3415
+			foreach ($sub_query_params as $param) {
3416
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3417
+				$this->_extract_related_model_info_from_query_param(
3418
+					$param,
3419
+					$model_query_info_carrier,
3420
+					$query_param_type
3421
+				);
3422
+			}
3423
+		}
3424
+		return $model_query_info_carrier;
3425
+	}
3426
+
3427
+
3428
+
3429
+	/**
3430
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3431
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3432
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3433
+	 * but use them in a different order. Eg, we need to know what models we are querying
3434
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3435
+	 * other models before we can finalize the where clause SQL.
3436
+	 *
3437
+	 * @param array $query_params
3438
+	 * @throws EE_Error
3439
+	 * @return EE_Model_Query_Info_Carrier
3440
+	 */
3441
+	public function _create_model_query_info_carrier($query_params)
3442
+	{
3443
+		if (! is_array($query_params)) {
3444
+			EE_Error::doing_it_wrong(
3445
+				'EEM_Base::_create_model_query_info_carrier',
3446
+				sprintf(
3447
+					__(
3448
+						'$query_params should be an array, you passed a variable of type %s',
3449
+						'event_espresso'
3450
+					),
3451
+					gettype($query_params)
3452
+				),
3453
+				'4.6.0'
3454
+			);
3455
+			$query_params = array();
3456
+		}
3457
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3458
+		// first check if we should alter the query to account for caps or not
3459
+		// because the caps might require us to do extra joins
3460
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3461
+			$query_params[0] = $where_query_params = array_replace_recursive(
3462
+				$where_query_params,
3463
+				$this->caps_where_conditions(
3464
+					$query_params['caps']
3465
+				)
3466
+			);
3467
+		}
3468
+		$query_object = $this->_extract_related_models_from_query($query_params);
3469
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3470
+		foreach ($where_query_params as $key => $value) {
3471
+			if (is_int($key)) {
3472
+				throw new EE_Error(
3473
+					sprintf(
3474
+						__(
3475
+							"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.",
3476
+							"event_espresso"
3477
+						),
3478
+						$key,
3479
+						var_export($value, true),
3480
+						var_export($query_params, true),
3481
+						get_class($this)
3482
+					)
3483
+				);
3484
+			}
3485
+		}
3486
+		if (array_key_exists('default_where_conditions', $query_params)
3487
+			&& ! empty($query_params['default_where_conditions'])
3488
+		) {
3489
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3490
+		} else {
3491
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3492
+		}
3493
+		$where_query_params = array_merge(
3494
+			$this->_get_default_where_conditions_for_models_in_query(
3495
+				$query_object,
3496
+				$use_default_where_conditions,
3497
+				$where_query_params
3498
+			),
3499
+			$where_query_params
3500
+		);
3501
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3502
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3503
+		// So we need to setup a subquery and use that for the main join.
3504
+		// Note for now this only works on the primary table for the model.
3505
+		// So for instance, you could set the limit array like this:
3506
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3507
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3508
+			$query_object->set_main_model_join_sql(
3509
+				$this->_construct_limit_join_select(
3510
+					$query_params['on_join_limit'][0],
3511
+					$query_params['on_join_limit'][1]
3512
+				)
3513
+			);
3514
+		}
3515
+		// set limit
3516
+		if (array_key_exists('limit', $query_params)) {
3517
+			if (is_array($query_params['limit'])) {
3518
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3519
+					$e = sprintf(
3520
+						__(
3521
+							"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)",
3522
+							"event_espresso"
3523
+						),
3524
+						http_build_query($query_params['limit'])
3525
+					);
3526
+					throw new EE_Error($e . "|" . $e);
3527
+				}
3528
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3529
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3530
+			} elseif (! empty($query_params['limit'])) {
3531
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3532
+			}
3533
+		}
3534
+		// set order by
3535
+		if (array_key_exists('order_by', $query_params)) {
3536
+			if (is_array($query_params['order_by'])) {
3537
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3538
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3539
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3540
+				if (array_key_exists('order', $query_params)) {
3541
+					throw new EE_Error(
3542
+						sprintf(
3543
+							__(
3544
+								"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 ",
3545
+								"event_espresso"
3546
+							),
3547
+							get_class($this),
3548
+							implode(", ", array_keys($query_params['order_by'])),
3549
+							implode(", ", $query_params['order_by']),
3550
+							$query_params['order']
3551
+						)
3552
+					);
3553
+				}
3554
+				$this->_extract_related_models_from_sub_params_array_keys(
3555
+					$query_params['order_by'],
3556
+					$query_object,
3557
+					'order_by'
3558
+				);
3559
+				// assume it's an array of fields to order by
3560
+				$order_array = array();
3561
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3562
+					$order = $this->_extract_order($order);
3563
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3564
+				}
3565
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3566
+			} elseif (! empty($query_params['order_by'])) {
3567
+				$this->_extract_related_model_info_from_query_param(
3568
+					$query_params['order_by'],
3569
+					$query_object,
3570
+					'order',
3571
+					$query_params['order_by']
3572
+				);
3573
+				$order = isset($query_params['order'])
3574
+					? $this->_extract_order($query_params['order'])
3575
+					: 'DESC';
3576
+				$query_object->set_order_by_sql(
3577
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3578
+				);
3579
+			}
3580
+		}
3581
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3582
+		if (! array_key_exists('order_by', $query_params)
3583
+			&& array_key_exists('order', $query_params)
3584
+			&& ! empty($query_params['order'])
3585
+		) {
3586
+			$pk_field = $this->get_primary_key_field();
3587
+			$order = $this->_extract_order($query_params['order']);
3588
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3589
+		}
3590
+		// set group by
3591
+		if (array_key_exists('group_by', $query_params)) {
3592
+			if (is_array($query_params['group_by'])) {
3593
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3594
+				$group_by_array = array();
3595
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3596
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3597
+				}
3598
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3599
+			} elseif (! empty($query_params['group_by'])) {
3600
+				$query_object->set_group_by_sql(
3601
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3602
+				);
3603
+			}
3604
+		}
3605
+		// set having
3606
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3607
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3608
+		}
3609
+		// now, just verify they didn't pass anything wack
3610
+		foreach ($query_params as $query_key => $query_value) {
3611
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3612
+				throw new EE_Error(
3613
+					sprintf(
3614
+						__(
3615
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3616
+							'event_espresso'
3617
+						),
3618
+						$query_key,
3619
+						get_class($this),
3620
+						//                      print_r( $this->_allowed_query_params, TRUE )
3621
+						implode(',', $this->_allowed_query_params)
3622
+					)
3623
+				);
3624
+			}
3625
+		}
3626
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3627
+		if (empty($main_model_join_sql)) {
3628
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3629
+		}
3630
+		return $query_object;
3631
+	}
3632
+
3633
+
3634
+
3635
+	/**
3636
+	 * Gets the where conditions that should be imposed on the query based on the
3637
+	 * context (eg reading frontend, backend, edit or delete).
3638
+	 *
3639
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3640
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3641
+	 * @throws EE_Error
3642
+	 */
3643
+	public function caps_where_conditions($context = self::caps_read)
3644
+	{
3645
+		EEM_Base::verify_is_valid_cap_context($context);
3646
+		$cap_where_conditions = array();
3647
+		$cap_restrictions = $this->caps_missing($context);
3648
+		/**
3649
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3650
+		 */
3651
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3652
+			$cap_where_conditions = array_replace_recursive(
3653
+				$cap_where_conditions,
3654
+				$restriction_if_no_cap->get_default_where_conditions()
3655
+			);
3656
+		}
3657
+		return apply_filters(
3658
+			'FHEE__EEM_Base__caps_where_conditions__return',
3659
+			$cap_where_conditions,
3660
+			$this,
3661
+			$context,
3662
+			$cap_restrictions
3663
+		);
3664
+	}
3665
+
3666
+
3667
+
3668
+	/**
3669
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3670
+	 * otherwise throws an exception
3671
+	 *
3672
+	 * @param string $should_be_order_string
3673
+	 * @return string either ASC, asc, DESC or desc
3674
+	 * @throws EE_Error
3675
+	 */
3676
+	private function _extract_order($should_be_order_string)
3677
+	{
3678
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3679
+			return $should_be_order_string;
3680
+		}
3681
+		throw new EE_Error(
3682
+			sprintf(
3683
+				__(
3684
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3685
+					"event_espresso"
3686
+				),
3687
+				get_class($this),
3688
+				$should_be_order_string
3689
+			)
3690
+		);
3691
+	}
3692
+
3693
+
3694
+
3695
+	/**
3696
+	 * Looks at all the models which are included in this query, and asks each
3697
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3698
+	 * so they can be merged
3699
+	 *
3700
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3701
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3702
+	 *                                                                  'none' means NO default where conditions will
3703
+	 *                                                                  be used AT ALL during this query.
3704
+	 *                                                                  'other_models_only' means default where
3705
+	 *                                                                  conditions from other models will be used, but
3706
+	 *                                                                  not for this primary model. 'all', the default,
3707
+	 *                                                                  means default where conditions will apply as
3708
+	 *                                                                  normal
3709
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3710
+	 * @throws EE_Error
3711
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3712
+	 */
3713
+	private function _get_default_where_conditions_for_models_in_query(
3714
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3715
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3716
+		$where_query_params = array()
3717
+	) {
3718
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3719
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3720
+			throw new EE_Error(sprintf(
3721
+				__(
3722
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3723
+					"event_espresso"
3724
+				),
3725
+				$use_default_where_conditions,
3726
+				implode(", ", $allowed_used_default_where_conditions_values)
3727
+			));
3728
+		}
3729
+		$universal_query_params = array();
3730
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3731
+			$universal_query_params = $this->_get_default_where_conditions();
3732
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3733
+			$universal_query_params = $this->_get_minimum_where_conditions();
3734
+		}
3735
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3736
+			$related_model = $this->get_related_model_obj($model_name);
3737
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3738
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3739
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3740
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3741
+			} else {
3742
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3743
+				continue;
3744
+			}
3745
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3746
+				$related_model_universal_where_params,
3747
+				$where_query_params,
3748
+				$related_model,
3749
+				$model_relation_path
3750
+			);
3751
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3752
+				$universal_query_params,
3753
+				$overrides
3754
+			);
3755
+		}
3756
+		return $universal_query_params;
3757
+	}
3758
+
3759
+
3760
+
3761
+	/**
3762
+	 * Determines whether or not we should use default where conditions for the model in question
3763
+	 * (this model, or other related models).
3764
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3765
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3766
+	 * We should use default where conditions on related models when they requested to use default where conditions
3767
+	 * on all models, or specifically just on other related models
3768
+	 * @param      $default_where_conditions_value
3769
+	 * @param bool $for_this_model false means this is for OTHER related models
3770
+	 * @return bool
3771
+	 */
3772
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3773
+	{
3774
+		return (
3775
+				   $for_this_model
3776
+				   && in_array(
3777
+					   $default_where_conditions_value,
3778
+					   array(
3779
+						   EEM_Base::default_where_conditions_all,
3780
+						   EEM_Base::default_where_conditions_this_only,
3781
+						   EEM_Base::default_where_conditions_minimum_others,
3782
+					   ),
3783
+					   true
3784
+				   )
3785
+			   )
3786
+			   || (
3787
+				   ! $for_this_model
3788
+				   && in_array(
3789
+					   $default_where_conditions_value,
3790
+					   array(
3791
+						   EEM_Base::default_where_conditions_all,
3792
+						   EEM_Base::default_where_conditions_others_only,
3793
+					   ),
3794
+					   true
3795
+				   )
3796
+			   );
3797
+	}
3798
+
3799
+	/**
3800
+	 * Determines whether or not we should use default minimum conditions for the model in question
3801
+	 * (this model, or other related models).
3802
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3803
+	 * where conditions.
3804
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3805
+	 * on this model or others
3806
+	 * @param      $default_where_conditions_value
3807
+	 * @param bool $for_this_model false means this is for OTHER related models
3808
+	 * @return bool
3809
+	 */
3810
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3811
+	{
3812
+		return (
3813
+				   $for_this_model
3814
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3815
+			   )
3816
+			   || (
3817
+				   ! $for_this_model
3818
+				   && in_array(
3819
+					   $default_where_conditions_value,
3820
+					   array(
3821
+						   EEM_Base::default_where_conditions_minimum_others,
3822
+						   EEM_Base::default_where_conditions_minimum_all,
3823
+					   ),
3824
+					   true
3825
+				   )
3826
+			   );
3827
+	}
3828
+
3829
+
3830
+	/**
3831
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3832
+	 * then we also add a special where condition which allows for that model's primary key
3833
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3834
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3835
+	 *
3836
+	 * @param array    $default_where_conditions
3837
+	 * @param array    $provided_where_conditions
3838
+	 * @param EEM_Base $model
3839
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3840
+	 * @return array like EEM_Base::get_all's $query_params[0]
3841
+	 * @throws EE_Error
3842
+	 */
3843
+	private function _override_defaults_or_make_null_friendly(
3844
+		$default_where_conditions,
3845
+		$provided_where_conditions,
3846
+		$model,
3847
+		$model_relation_path
3848
+	) {
3849
+		$null_friendly_where_conditions = array();
3850
+		$none_overridden = true;
3851
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3852
+		foreach ($default_where_conditions as $key => $val) {
3853
+			if (isset($provided_where_conditions[ $key ])) {
3854
+				$none_overridden = false;
3855
+			} else {
3856
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3857
+			}
3858
+		}
3859
+		if ($none_overridden && $default_where_conditions) {
3860
+			if ($model->has_primary_key_field()) {
3861
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3862
+																				. "."
3863
+																				. $model->primary_key_name() ] = array('IS NULL');
3864
+			}/*else{
3865 3865
                 //@todo NO PK, use other defaults
3866 3866
             }*/
3867
-        }
3868
-        return $null_friendly_where_conditions;
3869
-    }
3870
-
3871
-
3872
-
3873
-    /**
3874
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3875
-     * default where conditions on all get_all, update, and delete queries done by this model.
3876
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3877
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3878
-     *
3879
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3880
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3881
-     */
3882
-    private function _get_default_where_conditions($model_relation_path = null)
3883
-    {
3884
-        if ($this->_ignore_where_strategy) {
3885
-            return array();
3886
-        }
3887
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3888
-    }
3889
-
3890
-
3891
-
3892
-    /**
3893
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3894
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3895
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3896
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3897
-     * Similar to _get_default_where_conditions
3898
-     *
3899
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3900
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3901
-     */
3902
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3903
-    {
3904
-        if ($this->_ignore_where_strategy) {
3905
-            return array();
3906
-        }
3907
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3908
-    }
3909
-
3910
-
3911
-
3912
-    /**
3913
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3914
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3915
-     *
3916
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3917
-     * @return string
3918
-     * @throws EE_Error
3919
-     */
3920
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3921
-    {
3922
-        $selects = $this->_get_columns_to_select_for_this_model();
3923
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3924
-            $name_of_other_model_included) {
3925
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3926
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3927
-            foreach ($other_model_selects as $key => $value) {
3928
-                $selects[] = $value;
3929
-            }
3930
-        }
3931
-        return implode(", ", $selects);
3932
-    }
3933
-
3934
-
3935
-
3936
-    /**
3937
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3938
-     * So that's going to be the columns for all the fields on the model
3939
-     *
3940
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3941
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3942
-     */
3943
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3944
-    {
3945
-        $fields = $this->field_settings();
3946
-        $selects = array();
3947
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3948
-            $model_relation_chain,
3949
-            $this->get_this_model_name()
3950
-        );
3951
-        foreach ($fields as $field_obj) {
3952
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3953
-                         . $field_obj->get_table_alias()
3954
-                         . "."
3955
-                         . $field_obj->get_table_column()
3956
-                         . " AS '"
3957
-                         . $table_alias_with_model_relation_chain_prefix
3958
-                         . $field_obj->get_table_alias()
3959
-                         . "."
3960
-                         . $field_obj->get_table_column()
3961
-                         . "'";
3962
-        }
3963
-        // make sure we are also getting the PKs of each table
3964
-        $tables = $this->get_tables();
3965
-        if (count($tables) > 1) {
3966
-            foreach ($tables as $table_obj) {
3967
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3968
-                                       . $table_obj->get_fully_qualified_pk_column();
3969
-                if (! in_array($qualified_pk_column, $selects)) {
3970
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3971
-                }
3972
-            }
3973
-        }
3974
-        return $selects;
3975
-    }
3976
-
3977
-
3978
-
3979
-    /**
3980
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3981
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3982
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3983
-     * SQL for joining, and the data types
3984
-     *
3985
-     * @param null|string                 $original_query_param
3986
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3987
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3988
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3989
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3990
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3991
-     *                                                          or 'Registration's
3992
-     * @param string                      $original_query_param what it originally was (eg
3993
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3994
-     *                                                          matches $query_param
3995
-     * @throws EE_Error
3996
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3997
-     */
3998
-    private function _extract_related_model_info_from_query_param(
3999
-        $query_param,
4000
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4001
-        $query_param_type,
4002
-        $original_query_param = null
4003
-    ) {
4004
-        if ($original_query_param === null) {
4005
-            $original_query_param = $query_param;
4006
-        }
4007
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4008
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
4009
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
4010
-        $allow_fields = in_array(
4011
-            $query_param_type,
4012
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
4013
-            true
4014
-        );
4015
-        // check to see if we have a field on this model
4016
-        $this_model_fields = $this->field_settings(true);
4017
-        if (array_key_exists($query_param, $this_model_fields)) {
4018
-            if ($allow_fields) {
4019
-                return;
4020
-            }
4021
-            throw new EE_Error(
4022
-                sprintf(
4023
-                    __(
4024
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4025
-                        "event_espresso"
4026
-                    ),
4027
-                    $query_param,
4028
-                    get_class($this),
4029
-                    $query_param_type,
4030
-                    $original_query_param
4031
-                )
4032
-            );
4033
-        }
4034
-        // check if this is a special logic query param
4035
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4036
-            if ($allow_logic_query_params) {
4037
-                return;
4038
-            }
4039
-            throw new EE_Error(
4040
-                sprintf(
4041
-                    __(
4042
-                        'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4043
-                        'event_espresso'
4044
-                    ),
4045
-                    implode('", "', $this->_logic_query_param_keys),
4046
-                    $query_param,
4047
-                    get_class($this),
4048
-                    '<br />',
4049
-                    "\t"
4050
-                    . ' $passed_in_query_info = <pre>'
4051
-                    . print_r($passed_in_query_info, true)
4052
-                    . '</pre>'
4053
-                    . "\n\t"
4054
-                    . ' $query_param_type = '
4055
-                    . $query_param_type
4056
-                    . "\n\t"
4057
-                    . ' $original_query_param = '
4058
-                    . $original_query_param
4059
-                )
4060
-            );
4061
-        }
4062
-        // check if it's a custom selection
4063
-        if ($this->_custom_selections instanceof CustomSelects
4064
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4065
-        ) {
4066
-            return;
4067
-        }
4068
-        // check if has a model name at the beginning
4069
-        // and
4070
-        // check if it's a field on a related model
4071
-        if ($this->extractJoinModelFromQueryParams(
4072
-            $passed_in_query_info,
4073
-            $query_param,
4074
-            $original_query_param,
4075
-            $query_param_type
4076
-        )) {
4077
-            return;
4078
-        }
4079
-
4080
-        // ok so $query_param didn't start with a model name
4081
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4082
-        // it's wack, that's what it is
4083
-        throw new EE_Error(
4084
-            sprintf(
4085
-                esc_html__(
4086
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4087
-                    "event_espresso"
4088
-                ),
4089
-                $query_param,
4090
-                get_class($this),
4091
-                $query_param_type,
4092
-                $original_query_param
4093
-            )
4094
-        );
4095
-    }
4096
-
4097
-
4098
-    /**
4099
-     * Extracts any possible join model information from the provided possible_join_string.
4100
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4101
-     * parts that should be added to the query.
4102
-     *
4103
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4104
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4105
-     * @param null|string                 $original_query_param
4106
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4107
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4108
-     * @return bool  returns true if a join was added and false if not.
4109
-     * @throws EE_Error
4110
-     */
4111
-    private function extractJoinModelFromQueryParams(
4112
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4113
-        $possible_join_string,
4114
-        $original_query_param,
4115
-        $query_parameter_type
4116
-    ) {
4117
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4118
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4119
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4120
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4121
-                if ($possible_join_string === '') {
4122
-                    // nothing left to $query_param
4123
-                    // we should actually end in a field name, not a model like this!
4124
-                    throw new EE_Error(
4125
-                        sprintf(
4126
-                            esc_html__(
4127
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4128
-                                "event_espresso"
4129
-                            ),
4130
-                            $possible_join_string,
4131
-                            $query_parameter_type,
4132
-                            get_class($this),
4133
-                            $valid_related_model_name
4134
-                        )
4135
-                    );
4136
-                }
4137
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4138
-                $related_model_obj->_extract_related_model_info_from_query_param(
4139
-                    $possible_join_string,
4140
-                    $query_info_carrier,
4141
-                    $query_parameter_type,
4142
-                    $original_query_param
4143
-                );
4144
-                return true;
4145
-            }
4146
-            if ($possible_join_string === $valid_related_model_name) {
4147
-                $this->_add_join_to_model(
4148
-                    $valid_related_model_name,
4149
-                    $query_info_carrier,
4150
-                    $original_query_param
4151
-                );
4152
-                return true;
4153
-            }
4154
-        }
4155
-        return false;
4156
-    }
4157
-
4158
-
4159
-    /**
4160
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4161
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4162
-     * @throws EE_Error
4163
-     */
4164
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4165
-    {
4166
-        if ($this->_custom_selections instanceof CustomSelects
4167
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4168
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4169
-            )
4170
-        ) {
4171
-            $original_selects = $this->_custom_selections->originalSelects();
4172
-            foreach ($original_selects as $alias => $select_configuration) {
4173
-                $this->extractJoinModelFromQueryParams(
4174
-                    $query_info_carrier,
4175
-                    $select_configuration[0],
4176
-                    $select_configuration[0],
4177
-                    'custom_selects'
4178
-                );
4179
-            }
4180
-        }
4181
-    }
4182
-
4183
-
4184
-
4185
-    /**
4186
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4187
-     * and store it on $passed_in_query_info
4188
-     *
4189
-     * @param string                      $model_name
4190
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4191
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4192
-     *                                                          model and $model_name. Eg, if we are querying Event,
4193
-     *                                                          and are adding a join to 'Payment' with the original
4194
-     *                                                          query param key
4195
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4196
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4197
-     *                                                          Payment wants to add default query params so that it
4198
-     *                                                          will know what models to prepend onto its default query
4199
-     *                                                          params or in case it wants to rename tables (in case
4200
-     *                                                          there are multiple joins to the same table)
4201
-     * @return void
4202
-     * @throws EE_Error
4203
-     */
4204
-    private function _add_join_to_model(
4205
-        $model_name,
4206
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4207
-        $original_query_param
4208
-    ) {
4209
-        $relation_obj = $this->related_settings_for($model_name);
4210
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4211
-        // check if the relation is HABTM, because then we're essentially doing two joins
4212
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4213
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4214
-            $join_model_obj = $relation_obj->get_join_model();
4215
-            // replace the model specified with the join model for this relation chain, whi
4216
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4217
-                $model_name,
4218
-                $join_model_obj->get_this_model_name(),
4219
-                $model_relation_chain
4220
-            );
4221
-            $passed_in_query_info->merge(
4222
-                new EE_Model_Query_Info_Carrier(
4223
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4224
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4225
-                )
4226
-            );
4227
-        }
4228
-        // now just join to the other table pointed to by the relation object, and add its data types
4229
-        $passed_in_query_info->merge(
4230
-            new EE_Model_Query_Info_Carrier(
4231
-                array($model_relation_chain => $model_name),
4232
-                $relation_obj->get_join_statement($model_relation_chain)
4233
-            )
4234
-        );
4235
-    }
4236
-
4237
-
4238
-
4239
-    /**
4240
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4241
-     *
4242
-     * @param array $where_params like EEM_Base::get_all
4243
-     * @return string of SQL
4244
-     * @throws EE_Error
4245
-     */
4246
-    private function _construct_where_clause($where_params)
4247
-    {
4248
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4249
-        if ($SQL) {
4250
-            return " WHERE " . $SQL;
4251
-        }
4252
-        return '';
4253
-    }
4254
-
4255
-
4256
-
4257
-    /**
4258
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4259
-     * and should be passed HAVING parameters, not WHERE parameters
4260
-     *
4261
-     * @param array $having_params
4262
-     * @return string
4263
-     * @throws EE_Error
4264
-     */
4265
-    private function _construct_having_clause($having_params)
4266
-    {
4267
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4268
-        if ($SQL) {
4269
-            return " HAVING " . $SQL;
4270
-        }
4271
-        return '';
4272
-    }
4273
-
4274
-
4275
-    /**
4276
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4277
-     * Event_Meta.meta_value = 'foo'))"
4278
-     *
4279
-     * @param array  $where_params see EEM_Base::get_all for documentation
4280
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4281
-     * @throws EE_Error
4282
-     * @return string of SQL
4283
-     */
4284
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4285
-    {
4286
-        $where_clauses = array();
4287
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4288
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4289
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4290
-                switch ($query_param) {
4291
-                    case 'not':
4292
-                    case 'NOT':
4293
-                        $where_clauses[] = "! ("
4294
-                                           . $this->_construct_condition_clause_recursive(
4295
-                                               $op_and_value_or_sub_condition,
4296
-                                               $glue
4297
-                                           )
4298
-                                           . ")";
4299
-                        break;
4300
-                    case 'and':
4301
-                    case 'AND':
4302
-                        $where_clauses[] = " ("
4303
-                                           . $this->_construct_condition_clause_recursive(
4304
-                                               $op_and_value_or_sub_condition,
4305
-                                               ' AND '
4306
-                                           )
4307
-                                           . ")";
4308
-                        break;
4309
-                    case 'or':
4310
-                    case 'OR':
4311
-                        $where_clauses[] = " ("
4312
-                                           . $this->_construct_condition_clause_recursive(
4313
-                                               $op_and_value_or_sub_condition,
4314
-                                               ' OR '
4315
-                                           )
4316
-                                           . ")";
4317
-                        break;
4318
-                }
4319
-            } else {
4320
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4321
-                // if it's not a normal field, maybe it's a custom selection?
4322
-                if (! $field_obj) {
4323
-                    if ($this->_custom_selections instanceof CustomSelects) {
4324
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4325
-                    } else {
4326
-                        throw new EE_Error(sprintf(__(
4327
-                            "%s is neither a valid model field name, nor a custom selection",
4328
-                            "event_espresso"
4329
-                        ), $query_param));
4330
-                    }
4331
-                }
4332
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4333
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4334
-            }
4335
-        }
4336
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4337
-    }
4338
-
4339
-
4340
-
4341
-    /**
4342
-     * Takes the input parameter and extract the table name (alias) and column name
4343
-     *
4344
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4345
-     * @throws EE_Error
4346
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4347
-     */
4348
-    private function _deduce_column_name_from_query_param($query_param)
4349
-    {
4350
-        $field = $this->_deduce_field_from_query_param($query_param);
4351
-        if ($field) {
4352
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4353
-                $field->get_model_name(),
4354
-                $query_param
4355
-            );
4356
-            return $table_alias_prefix . $field->get_qualified_column();
4357
-        }
4358
-        if ($this->_custom_selections instanceof CustomSelects
4359
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4360
-        ) {
4361
-            // maybe it's custom selection item?
4362
-            // if so, just use it as the "column name"
4363
-            return $query_param;
4364
-        }
4365
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4366
-            ? implode(',', $this->_custom_selections->columnAliases())
4367
-            : '';
4368
-        throw new EE_Error(
4369
-            sprintf(
4370
-                __(
4371
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4372
-                    "event_espresso"
4373
-                ),
4374
-                $query_param,
4375
-                $custom_select_aliases
4376
-            )
4377
-        );
4378
-    }
4379
-
4380
-
4381
-
4382
-    /**
4383
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4384
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4385
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4386
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4387
-     *
4388
-     * @param string $condition_query_param_key
4389
-     * @return string
4390
-     */
4391
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4392
-    {
4393
-        $pos_of_star = strpos($condition_query_param_key, '*');
4394
-        if ($pos_of_star === false) {
4395
-            return $condition_query_param_key;
4396
-        }
4397
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4398
-        return $condition_query_param_sans_star;
4399
-    }
4400
-
4401
-
4402
-
4403
-    /**
4404
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4405
-     *
4406
-     * @param                            mixed      array | string    $op_and_value
4407
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4408
-     * @throws EE_Error
4409
-     * @return string
4410
-     */
4411
-    private function _construct_op_and_value($op_and_value, $field_obj)
4412
-    {
4413
-        if (is_array($op_and_value)) {
4414
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4415
-            if (! $operator) {
4416
-                $php_array_like_string = array();
4417
-                foreach ($op_and_value as $key => $value) {
4418
-                    $php_array_like_string[] = "$key=>$value";
4419
-                }
4420
-                throw new EE_Error(
4421
-                    sprintf(
4422
-                        __(
4423
-                            "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))",
4424
-                            "event_espresso"
4425
-                        ),
4426
-                        implode(",", $php_array_like_string)
4427
-                    )
4428
-                );
4429
-            }
4430
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4431
-        } else {
4432
-            $operator = '=';
4433
-            $value = $op_and_value;
4434
-        }
4435
-        // check to see if the value is actually another field
4436
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4437
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4438
-        }
4439
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4440
-            // in this case, the value should be an array, or at least a comma-separated list
4441
-            // it will need to handle a little differently
4442
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4443
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4444
-            return $operator . SP . $cleaned_value;
4445
-        }
4446
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4447
-            // the value should be an array with count of two.
4448
-            if (count($value) !== 2) {
4449
-                throw new EE_Error(
4450
-                    sprintf(
4451
-                        __(
4452
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4453
-                            'event_espresso'
4454
-                        ),
4455
-                        "BETWEEN"
4456
-                    )
4457
-                );
4458
-            }
4459
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4460
-            return $operator . SP . $cleaned_value;
4461
-        }
4462
-        if (in_array($operator, $this->valid_null_style_operators())) {
4463
-            if ($value !== null) {
4464
-                throw new EE_Error(
4465
-                    sprintf(
4466
-                        __(
4467
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4468
-                            "event_espresso"
4469
-                        ),
4470
-                        $value,
4471
-                        $operator
4472
-                    )
4473
-                );
4474
-            }
4475
-            return $operator;
4476
-        }
4477
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4478
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4479
-            // remove other junk. So just treat it as a string.
4480
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4481
-        }
4482
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4483
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4484
-        }
4485
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4486
-            throw new EE_Error(
4487
-                sprintf(
4488
-                    __(
4489
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4490
-                        'event_espresso'
4491
-                    ),
4492
-                    $operator,
4493
-                    $operator
4494
-                )
4495
-            );
4496
-        }
4497
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4498
-            throw new EE_Error(
4499
-                sprintf(
4500
-                    __(
4501
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4502
-                        'event_espresso'
4503
-                    ),
4504
-                    $operator,
4505
-                    $operator
4506
-                )
4507
-            );
4508
-        }
4509
-        throw new EE_Error(
4510
-            sprintf(
4511
-                __(
4512
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4513
-                    "event_espresso"
4514
-                ),
4515
-                http_build_query($op_and_value)
4516
-            )
4517
-        );
4518
-    }
4519
-
4520
-
4521
-
4522
-    /**
4523
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4524
-     *
4525
-     * @param array                      $values
4526
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4527
-     *                                              '%s'
4528
-     * @return string
4529
-     * @throws EE_Error
4530
-     */
4531
-    public function _construct_between_value($values, $field_obj)
4532
-    {
4533
-        $cleaned_values = array();
4534
-        foreach ($values as $value) {
4535
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4536
-        }
4537
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4538
-    }
4539
-
4540
-
4541
-
4542
-    /**
4543
-     * Takes an array or a comma-separated list of $values and cleans them
4544
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4545
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4546
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4547
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4548
-     *
4549
-     * @param mixed                      $values    array or comma-separated string
4550
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4551
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4552
-     * @throws EE_Error
4553
-     */
4554
-    public function _construct_in_value($values, $field_obj)
4555
-    {
4556
-        // check if the value is a CSV list
4557
-        if (is_string($values)) {
4558
-            // in which case, turn it into an array
4559
-            $values = explode(",", $values);
4560
-        }
4561
-        $cleaned_values = array();
4562
-        foreach ($values as $value) {
4563
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4564
-        }
4565
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4566
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4567
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4568
-        if (empty($cleaned_values)) {
4569
-            $all_fields = $this->field_settings();
4570
-            $a_field = array_shift($all_fields);
4571
-            $main_table = $this->_get_main_table();
4572
-            $cleaned_values[] = "SELECT "
4573
-                                . $a_field->get_table_column()
4574
-                                . " FROM "
4575
-                                . $main_table->get_table_name()
4576
-                                . " WHERE FALSE";
4577
-        }
4578
-        return "(" . implode(",", $cleaned_values) . ")";
4579
-    }
4580
-
4581
-
4582
-
4583
-    /**
4584
-     * @param mixed                      $value
4585
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4586
-     * @throws EE_Error
4587
-     * @return false|null|string
4588
-     */
4589
-    private function _wpdb_prepare_using_field($value, $field_obj)
4590
-    {
4591
-        /** @type WPDB $wpdb */
4592
-        global $wpdb;
4593
-        if ($field_obj instanceof EE_Model_Field_Base) {
4594
-            return $wpdb->prepare(
4595
-                $field_obj->get_wpdb_data_type(),
4596
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4597
-            );
4598
-        } //$field_obj should really just be a data type
4599
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4600
-            throw new EE_Error(
4601
-                sprintf(
4602
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4603
-                    $field_obj,
4604
-                    implode(",", $this->_valid_wpdb_data_types)
4605
-                )
4606
-            );
4607
-        }
4608
-        return $wpdb->prepare($field_obj, $value);
4609
-    }
4610
-
4611
-
4612
-
4613
-    /**
4614
-     * Takes the input parameter and finds the model field that it indicates.
4615
-     *
4616
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4617
-     * @throws EE_Error
4618
-     * @return EE_Model_Field_Base
4619
-     */
4620
-    protected function _deduce_field_from_query_param($query_param_name)
4621
-    {
4622
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4623
-        // which will help us find the database table and column
4624
-        $query_param_parts = explode(".", $query_param_name);
4625
-        if (empty($query_param_parts)) {
4626
-            throw new EE_Error(sprintf(__(
4627
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4628
-                'event_espresso'
4629
-            ), $query_param_name));
4630
-        }
4631
-        $number_of_parts = count($query_param_parts);
4632
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4633
-        if ($number_of_parts === 1) {
4634
-            $field_name = $last_query_param_part;
4635
-            $model_obj = $this;
4636
-        } else {// $number_of_parts >= 2
4637
-            // the last part is the column name, and there are only 2parts. therefore...
4638
-            $field_name = $last_query_param_part;
4639
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4640
-        }
4641
-        try {
4642
-            return $model_obj->field_settings_for($field_name);
4643
-        } catch (EE_Error $e) {
4644
-            return null;
4645
-        }
4646
-    }
4647
-
4648
-
4649
-
4650
-    /**
4651
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4652
-     * alias and column which corresponds to it
4653
-     *
4654
-     * @param string $field_name
4655
-     * @throws EE_Error
4656
-     * @return string
4657
-     */
4658
-    public function _get_qualified_column_for_field($field_name)
4659
-    {
4660
-        $all_fields = $this->field_settings();
4661
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4662
-        if ($field) {
4663
-            return $field->get_qualified_column();
4664
-        }
4665
-        throw new EE_Error(
4666
-            sprintf(
4667
-                __(
4668
-                    "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.",
4669
-                    'event_espresso'
4670
-                ),
4671
-                $field_name,
4672
-                get_class($this)
4673
-            )
4674
-        );
4675
-    }
4676
-
4677
-
4678
-
4679
-    /**
4680
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4681
-     * Example usage:
4682
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4683
-     *      array(),
4684
-     *      ARRAY_A,
4685
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4686
-     *  );
4687
-     * is equivalent to
4688
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4689
-     * and
4690
-     *  EEM_Event::instance()->get_all_wpdb_results(
4691
-     *      array(
4692
-     *          array(
4693
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4694
-     *          ),
4695
-     *          ARRAY_A,
4696
-     *          implode(
4697
-     *              ', ',
4698
-     *              array_merge(
4699
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4700
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4701
-     *              )
4702
-     *          )
4703
-     *      )
4704
-     *  );
4705
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4706
-     *
4707
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4708
-     *                                            and the one whose fields you are selecting for example: when querying
4709
-     *                                            tickets model and selecting fields from the tickets model you would
4710
-     *                                            leave this parameter empty, because no models are needed to join
4711
-     *                                            between the queried model and the selected one. Likewise when
4712
-     *                                            querying the datetime model and selecting fields from the tickets
4713
-     *                                            model, it would also be left empty, because there is a direct
4714
-     *                                            relation from datetimes to tickets, so no model is needed to join
4715
-     *                                            them together. However, when querying from the event model and
4716
-     *                                            selecting fields from the ticket model, you should provide the string
4717
-     *                                            'Datetime', indicating that the event model must first join to the
4718
-     *                                            datetime model in order to find its relation to ticket model.
4719
-     *                                            Also, when querying from the venue model and selecting fields from
4720
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4721
-     *                                            indicating you need to join the venue model to the event model,
4722
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4723
-     *                                            This string is used to deduce the prefix that gets added onto the
4724
-     *                                            models' tables qualified columns
4725
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4726
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4727
-     *                                            qualified column names
4728
-     * @return array|string
4729
-     */
4730
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4731
-    {
4732
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4733
-        $qualified_columns = array();
4734
-        foreach ($this->field_settings() as $field_name => $field) {
4735
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4736
-        }
4737
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4738
-    }
4739
-
4740
-
4741
-
4742
-    /**
4743
-     * constructs the select use on special limit joins
4744
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4745
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4746
-     * (as that is typically where the limits would be set).
4747
-     *
4748
-     * @param  string       $table_alias The table the select is being built for
4749
-     * @param  mixed|string $limit       The limit for this select
4750
-     * @return string                The final select join element for the query.
4751
-     */
4752
-    public function _construct_limit_join_select($table_alias, $limit)
4753
-    {
4754
-        $SQL = '';
4755
-        foreach ($this->_tables as $table_obj) {
4756
-            if ($table_obj instanceof EE_Primary_Table) {
4757
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4758
-                    ? $table_obj->get_select_join_limit($limit)
4759
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4760
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4761
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4762
-                    ? $table_obj->get_select_join_limit_join($limit)
4763
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4764
-            }
4765
-        }
4766
-        return $SQL;
4767
-    }
4768
-
4769
-
4770
-
4771
-    /**
4772
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4773
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4774
-     *
4775
-     * @return string SQL
4776
-     * @throws EE_Error
4777
-     */
4778
-    public function _construct_internal_join()
4779
-    {
4780
-        $SQL = $this->_get_main_table()->get_table_sql();
4781
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4782
-        return $SQL;
4783
-    }
4784
-
4785
-
4786
-
4787
-    /**
4788
-     * Constructs the SQL for joining all the tables on this model.
4789
-     * Normally $alias should be the primary table's alias, but in cases where
4790
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4791
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4792
-     * alias, this will construct SQL like:
4793
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4794
-     * With $alias being a secondary table's alias, this will construct SQL like:
4795
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4796
-     *
4797
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4798
-     * @return string
4799
-     */
4800
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4801
-    {
4802
-        $SQL = '';
4803
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4804
-        foreach ($this->_tables as $table_obj) {
4805
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4806
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4807
-                    // so we're joining to this table, meaning the table is already in
4808
-                    // the FROM statement, BUT the primary table isn't. So we want
4809
-                    // to add the inverse join sql
4810
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4811
-                } else {
4812
-                    // just add a regular JOIN to this table from the primary table
4813
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4814
-                }
4815
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4816
-        }
4817
-        return $SQL;
4818
-    }
4819
-
4820
-
4821
-
4822
-    /**
4823
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4824
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4825
-     * their data type (eg, '%s', '%d', etc)
4826
-     *
4827
-     * @return array
4828
-     */
4829
-    public function _get_data_types()
4830
-    {
4831
-        $data_types = array();
4832
-        foreach ($this->field_settings() as $field_obj) {
4833
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4834
-            /** @var $field_obj EE_Model_Field_Base */
4835
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4836
-        }
4837
-        return $data_types;
4838
-    }
4839
-
4840
-
4841
-
4842
-    /**
4843
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4844
-     *
4845
-     * @param string $model_name
4846
-     * @throws EE_Error
4847
-     * @return EEM_Base
4848
-     */
4849
-    public function get_related_model_obj($model_name)
4850
-    {
4851
-        $model_classname = "EEM_" . $model_name;
4852
-        if (! class_exists($model_classname)) {
4853
-            throw new EE_Error(sprintf(__(
4854
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4855
-                'event_espresso'
4856
-            ), $model_name, $model_classname));
4857
-        }
4858
-        return call_user_func($model_classname . "::instance");
4859
-    }
4860
-
4861
-
4862
-
4863
-    /**
4864
-     * Returns the array of EE_ModelRelations for this model.
4865
-     *
4866
-     * @return EE_Model_Relation_Base[]
4867
-     */
4868
-    public function relation_settings()
4869
-    {
4870
-        return $this->_model_relations;
4871
-    }
4872
-
4873
-
4874
-
4875
-    /**
4876
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4877
-     * because without THOSE models, this model probably doesn't have much purpose.
4878
-     * (Eg, without an event, datetimes have little purpose.)
4879
-     *
4880
-     * @return EE_Belongs_To_Relation[]
4881
-     */
4882
-    public function belongs_to_relations()
4883
-    {
4884
-        $belongs_to_relations = array();
4885
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4886
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4887
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4888
-            }
4889
-        }
4890
-        return $belongs_to_relations;
4891
-    }
4892
-
4893
-
4894
-
4895
-    /**
4896
-     * Returns the specified EE_Model_Relation, or throws an exception
4897
-     *
4898
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4899
-     * @throws EE_Error
4900
-     * @return EE_Model_Relation_Base
4901
-     */
4902
-    public function related_settings_for($relation_name)
4903
-    {
4904
-        $relatedModels = $this->relation_settings();
4905
-        if (! array_key_exists($relation_name, $relatedModels)) {
4906
-            throw new EE_Error(
4907
-                sprintf(
4908
-                    __(
4909
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4910
-                        'event_espresso'
4911
-                    ),
4912
-                    $relation_name,
4913
-                    $this->_get_class_name(),
4914
-                    implode(', ', array_keys($relatedModels))
4915
-                )
4916
-            );
4917
-        }
4918
-        return $relatedModels[ $relation_name ];
4919
-    }
4920
-
4921
-
4922
-
4923
-    /**
4924
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4925
-     * fields
4926
-     *
4927
-     * @param string $fieldName
4928
-     * @param boolean $include_db_only_fields
4929
-     * @throws EE_Error
4930
-     * @return EE_Model_Field_Base
4931
-     */
4932
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4933
-    {
4934
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4935
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4936
-            throw new EE_Error(sprintf(
4937
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4938
-                $fieldName,
4939
-                get_class($this)
4940
-            ));
4941
-        }
4942
-        return $fieldSettings[ $fieldName ];
4943
-    }
4944
-
4945
-
4946
-
4947
-    /**
4948
-     * Checks if this field exists on this model
4949
-     *
4950
-     * @param string $fieldName a key in the model's _field_settings array
4951
-     * @return boolean
4952
-     */
4953
-    public function has_field($fieldName)
4954
-    {
4955
-        $fieldSettings = $this->field_settings(true);
4956
-        if (isset($fieldSettings[ $fieldName ])) {
4957
-            return true;
4958
-        }
4959
-        return false;
4960
-    }
4961
-
4962
-
4963
-
4964
-    /**
4965
-     * Returns whether or not this model has a relation to the specified model
4966
-     *
4967
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4968
-     * @return boolean
4969
-     */
4970
-    public function has_relation($relation_name)
4971
-    {
4972
-        $relations = $this->relation_settings();
4973
-        if (isset($relations[ $relation_name ])) {
4974
-            return true;
4975
-        }
4976
-        return false;
4977
-    }
4978
-
4979
-
4980
-
4981
-    /**
4982
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4983
-     * Eg, on EE_Answer that would be ANS_ID field object
4984
-     *
4985
-     * @param $field_obj
4986
-     * @return boolean
4987
-     */
4988
-    public function is_primary_key_field($field_obj)
4989
-    {
4990
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4991
-    }
4992
-
4993
-
4994
-
4995
-    /**
4996
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4997
-     * Eg, on EE_Answer that would be ANS_ID field object
4998
-     *
4999
-     * @return EE_Model_Field_Base
5000
-     * @throws EE_Error
5001
-     */
5002
-    public function get_primary_key_field()
5003
-    {
5004
-        if ($this->_primary_key_field === null) {
5005
-            foreach ($this->field_settings(true) as $field_obj) {
5006
-                if ($this->is_primary_key_field($field_obj)) {
5007
-                    $this->_primary_key_field = $field_obj;
5008
-                    break;
5009
-                }
5010
-            }
5011
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5012
-                throw new EE_Error(sprintf(
5013
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
5014
-                    get_class($this)
5015
-                ));
5016
-            }
5017
-        }
5018
-        return $this->_primary_key_field;
5019
-    }
5020
-
5021
-
5022
-
5023
-    /**
5024
-     * Returns whether or not not there is a primary key on this model.
5025
-     * Internally does some caching.
5026
-     *
5027
-     * @return boolean
5028
-     */
5029
-    public function has_primary_key_field()
5030
-    {
5031
-        if ($this->_has_primary_key_field === null) {
5032
-            try {
5033
-                $this->get_primary_key_field();
5034
-                $this->_has_primary_key_field = true;
5035
-            } catch (EE_Error $e) {
5036
-                $this->_has_primary_key_field = false;
5037
-            }
5038
-        }
5039
-        return $this->_has_primary_key_field;
5040
-    }
5041
-
5042
-
5043
-
5044
-    /**
5045
-     * Finds the first field of type $field_class_name.
5046
-     *
5047
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5048
-     *                                 EE_Foreign_Key_Field, etc
5049
-     * @return EE_Model_Field_Base or null if none is found
5050
-     */
5051
-    public function get_a_field_of_type($field_class_name)
5052
-    {
5053
-        foreach ($this->field_settings() as $field) {
5054
-            if ($field instanceof $field_class_name) {
5055
-                return $field;
5056
-            }
5057
-        }
5058
-        return null;
5059
-    }
5060
-
5061
-
5062
-
5063
-    /**
5064
-     * Gets a foreign key field pointing to model.
5065
-     *
5066
-     * @param string $model_name eg Event, Registration, not EEM_Event
5067
-     * @return EE_Foreign_Key_Field_Base
5068
-     * @throws EE_Error
5069
-     */
5070
-    public function get_foreign_key_to($model_name)
5071
-    {
5072
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5073
-            foreach ($this->field_settings() as $field) {
5074
-                if ($field instanceof EE_Foreign_Key_Field_Base
5075
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5076
-                ) {
5077
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5078
-                    break;
5079
-                }
5080
-            }
5081
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5082
-                throw new EE_Error(sprintf(__(
5083
-                    "There is no foreign key field pointing to model %s on model %s",
5084
-                    'event_espresso'
5085
-                ), $model_name, get_class($this)));
5086
-            }
5087
-        }
5088
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5089
-    }
5090
-
5091
-
5092
-
5093
-    /**
5094
-     * Gets the table name (including $wpdb->prefix) for the table alias
5095
-     *
5096
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5097
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5098
-     *                            Either one works
5099
-     * @return string
5100
-     */
5101
-    public function get_table_for_alias($table_alias)
5102
-    {
5103
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5104
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5105
-    }
5106
-
5107
-
5108
-
5109
-    /**
5110
-     * Returns a flat array of all field son this model, instead of organizing them
5111
-     * by table_alias as they are in the constructor.
5112
-     *
5113
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5114
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5115
-     */
5116
-    public function field_settings($include_db_only_fields = false)
5117
-    {
5118
-        if ($include_db_only_fields) {
5119
-            if ($this->_cached_fields === null) {
5120
-                $this->_cached_fields = array();
5121
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5122
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5123
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5124
-                    }
5125
-                }
5126
-            }
5127
-            return $this->_cached_fields;
5128
-        }
5129
-        if ($this->_cached_fields_non_db_only === null) {
5130
-            $this->_cached_fields_non_db_only = array();
5131
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5132
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5133
-                    /** @var $field_obj EE_Model_Field_Base */
5134
-                    if (! $field_obj->is_db_only_field()) {
5135
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5136
-                    }
5137
-                }
5138
-            }
5139
-        }
5140
-        return $this->_cached_fields_non_db_only;
5141
-    }
5142
-
5143
-
5144
-
5145
-    /**
5146
-     *        cycle though array of attendees and create objects out of each item
5147
-     *
5148
-     * @access        private
5149
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5150
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5151
-     *                           numerically indexed)
5152
-     * @throws EE_Error
5153
-     */
5154
-    protected function _create_objects($rows = array())
5155
-    {
5156
-        $array_of_objects = array();
5157
-        if (empty($rows)) {
5158
-            return array();
5159
-        }
5160
-        $count_if_model_has_no_primary_key = 0;
5161
-        $has_primary_key = $this->has_primary_key_field();
5162
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5163
-        foreach ((array) $rows as $row) {
5164
-            if (empty($row)) {
5165
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5166
-                return array();
5167
-            }
5168
-            // check if we've already set this object in the results array,
5169
-            // in which case there's no need to process it further (again)
5170
-            if ($has_primary_key) {
5171
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5172
-                    $row,
5173
-                    $primary_key_field->get_qualified_column(),
5174
-                    $primary_key_field->get_table_column()
5175
-                );
5176
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5177
-                    continue;
5178
-                }
5179
-            }
5180
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5181
-            if (! $classInstance) {
5182
-                throw new EE_Error(
5183
-                    sprintf(
5184
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5185
-                        $this->get_this_model_name(),
5186
-                        http_build_query($row)
5187
-                    )
5188
-                );
5189
-            }
5190
-            // set the timezone on the instantiated objects
5191
-            $classInstance->set_timezone($this->_timezone);
5192
-            // make sure if there is any timezone setting present that we set the timezone for the object
5193
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5194
-            $array_of_objects[ $key ] = $classInstance;
5195
-            // also, for all the relations of type BelongsTo, see if we can cache
5196
-            // those related models
5197
-            // (we could do this for other relations too, but if there are conditions
5198
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5199
-            // so it requires a little more thought than just caching them immediately...)
5200
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5201
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5202
-                    // check if this model's INFO is present. If so, cache it on the model
5203
-                    $other_model = $relation_obj->get_other_model();
5204
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5205
-                    // if we managed to make a model object from the results, cache it on the main model object
5206
-                    if ($other_model_obj_maybe) {
5207
-                        // set timezone on these other model objects if they are present
5208
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5209
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5210
-                    }
5211
-                }
5212
-            }
5213
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5214
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5215
-            // the field in the CustomSelects object
5216
-            if ($this->_custom_selections instanceof CustomSelects) {
5217
-                $classInstance->setCustomSelectsValues(
5218
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5219
-                );
5220
-            }
5221
-        }
5222
-        return $array_of_objects;
5223
-    }
5224
-
5225
-
5226
-    /**
5227
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5228
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5229
-     *
5230
-     * @param array $db_results_row
5231
-     * @return array
5232
-     */
5233
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5234
-    {
5235
-        $results = array();
5236
-        if ($this->_custom_selections instanceof CustomSelects) {
5237
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5238
-                if (isset($db_results_row[ $alias ])) {
5239
-                    $results[ $alias ] = $this->convertValueToDataType(
5240
-                        $db_results_row[ $alias ],
5241
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5242
-                    );
5243
-                }
5244
-            }
5245
-        }
5246
-        return $results;
5247
-    }
5248
-
5249
-
5250
-    /**
5251
-     * This will set the value for the given alias
5252
-     * @param string $value
5253
-     * @param string $datatype (one of %d, %s, %f)
5254
-     * @return int|string|float (int for %d, string for %s, float for %f)
5255
-     */
5256
-    protected function convertValueToDataType($value, $datatype)
5257
-    {
5258
-        switch ($datatype) {
5259
-            case '%f':
5260
-                return (float) $value;
5261
-            case '%d':
5262
-                return (int) $value;
5263
-            default:
5264
-                return (string) $value;
5265
-        }
5266
-    }
5267
-
5268
-
5269
-    /**
5270
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5271
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5272
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5273
-     * object (as set in the model_field!).
5274
-     *
5275
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5276
-     */
5277
-    public function create_default_object()
5278
-    {
5279
-        $this_model_fields_and_values = array();
5280
-        // setup the row using default values;
5281
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5282
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5283
-        }
5284
-        $className = $this->_get_class_name();
5285
-        $classInstance = EE_Registry::instance()
5286
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5287
-        return $classInstance;
5288
-    }
5289
-
5290
-
5291
-
5292
-    /**
5293
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5294
-     *                             or an stdClass where each property is the name of a column,
5295
-     * @return EE_Base_Class
5296
-     * @throws EE_Error
5297
-     */
5298
-    public function instantiate_class_from_array_or_object($cols_n_values)
5299
-    {
5300
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5301
-            $cols_n_values = get_object_vars($cols_n_values);
5302
-        }
5303
-        $primary_key = null;
5304
-        // make sure the array only has keys that are fields/columns on this model
5305
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5306
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5307
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5308
-        }
5309
-        $className = $this->_get_class_name();
5310
-        // check we actually found results that we can use to build our model object
5311
-        // if not, return null
5312
-        if ($this->has_primary_key_field()) {
5313
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5314
-                return null;
5315
-            }
5316
-        } elseif ($this->unique_indexes()) {
5317
-            $first_column = reset($this_model_fields_n_values);
5318
-            if (empty($first_column)) {
5319
-                return null;
5320
-            }
5321
-        }
5322
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5323
-        if ($primary_key) {
5324
-            $classInstance = $this->get_from_entity_map($primary_key);
5325
-            if (! $classInstance) {
5326
-                $classInstance = EE_Registry::instance()
5327
-                                            ->load_class(
5328
-                                                $className,
5329
-                                                array($this_model_fields_n_values, $this->_timezone),
5330
-                                                true,
5331
-                                                false
5332
-                                            );
5333
-                // add this new object to the entity map
5334
-                $classInstance = $this->add_to_entity_map($classInstance);
5335
-            }
5336
-        } else {
5337
-            $classInstance = EE_Registry::instance()
5338
-                                        ->load_class(
5339
-                                            $className,
5340
-                                            array($this_model_fields_n_values, $this->_timezone),
5341
-                                            true,
5342
-                                            false
5343
-                                        );
5344
-        }
5345
-        return $classInstance;
5346
-    }
5347
-
5348
-
5349
-
5350
-    /**
5351
-     * Gets the model object from the  entity map if it exists
5352
-     *
5353
-     * @param int|string $id the ID of the model object
5354
-     * @return EE_Base_Class
5355
-     */
5356
-    public function get_from_entity_map($id)
5357
-    {
5358
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5359
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5360
-    }
5361
-
5362
-
5363
-
5364
-    /**
5365
-     * add_to_entity_map
5366
-     * Adds the object to the model's entity mappings
5367
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5368
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5369
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5370
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5371
-     *        then this method should be called immediately after the update query
5372
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5373
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5374
-     *
5375
-     * @param    EE_Base_Class $object
5376
-     * @throws EE_Error
5377
-     * @return \EE_Base_Class
5378
-     */
5379
-    public function add_to_entity_map(EE_Base_Class $object)
5380
-    {
5381
-        $className = $this->_get_class_name();
5382
-        if (! $object instanceof $className) {
5383
-            throw new EE_Error(sprintf(
5384
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5385
-                is_object($object) ? get_class($object) : $object,
5386
-                $className
5387
-            ));
5388
-        }
5389
-        /** @var $object EE_Base_Class */
5390
-        if (! $object->ID()) {
5391
-            throw new EE_Error(sprintf(__(
5392
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5393
-                "event_espresso"
5394
-            ), get_class($this)));
5395
-        }
5396
-        // double check it's not already there
5397
-        $classInstance = $this->get_from_entity_map($object->ID());
5398
-        if ($classInstance) {
5399
-            return $classInstance;
5400
-        }
5401
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5402
-        return $object;
5403
-    }
5404
-
5405
-
5406
-
5407
-    /**
5408
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5409
-     * if no identifier is provided, then the entire entity map is emptied
5410
-     *
5411
-     * @param int|string $id the ID of the model object
5412
-     * @return boolean
5413
-     */
5414
-    public function clear_entity_map($id = null)
5415
-    {
5416
-        if (empty($id)) {
5417
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5418
-            return true;
5419
-        }
5420
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5421
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5422
-            return true;
5423
-        }
5424
-        return false;
5425
-    }
5426
-
5427
-
5428
-
5429
-    /**
5430
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5431
-     * Given an array where keys are column (or column alias) names and values,
5432
-     * returns an array of their corresponding field names and database values
5433
-     *
5434
-     * @param array $cols_n_values
5435
-     * @return array
5436
-     */
5437
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5438
-    {
5439
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5440
-    }
5441
-
5442
-
5443
-
5444
-    /**
5445
-     * _deduce_fields_n_values_from_cols_n_values
5446
-     * Given an array where keys are column (or column alias) names and values,
5447
-     * returns an array of their corresponding field names and database values
5448
-     *
5449
-     * @param string $cols_n_values
5450
-     * @return array
5451
-     */
5452
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5453
-    {
5454
-        $this_model_fields_n_values = array();
5455
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5456
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5457
-                $cols_n_values,
5458
-                $table_obj->get_fully_qualified_pk_column(),
5459
-                $table_obj->get_pk_column()
5460
-            );
5461
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5462
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5463
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5464
-                    if (! $field_obj->is_db_only_field()) {
5465
-                        // prepare field as if its coming from db
5466
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5467
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5468
-                    }
5469
-                }
5470
-            } else {
5471
-                // the table's rows existed. Use their values
5472
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5473
-                    if (! $field_obj->is_db_only_field()) {
5474
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5475
-                            $cols_n_values,
5476
-                            $field_obj->get_qualified_column(),
5477
-                            $field_obj->get_table_column()
5478
-                        );
5479
-                    }
5480
-                }
5481
-            }
5482
-        }
5483
-        return $this_model_fields_n_values;
5484
-    }
5485
-
5486
-
5487
-
5488
-    /**
5489
-     * @param $cols_n_values
5490
-     * @param $qualified_column
5491
-     * @param $regular_column
5492
-     * @return null
5493
-     */
5494
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5495
-    {
5496
-        $value = null;
5497
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5498
-        // does the field on the model relate to this column retrieved from the db?
5499
-        // or is it a db-only field? (not relating to the model)
5500
-        if (isset($cols_n_values[ $qualified_column ])) {
5501
-            $value = $cols_n_values[ $qualified_column ];
5502
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5503
-            $value = $cols_n_values[ $regular_column ];
5504
-        }
5505
-        return $value;
5506
-    }
5507
-
5508
-
5509
-
5510
-    /**
5511
-     * refresh_entity_map_from_db
5512
-     * Makes sure the model object in the entity map at $id assumes the values
5513
-     * of the database (opposite of EE_base_Class::save())
5514
-     *
5515
-     * @param int|string $id
5516
-     * @return EE_Base_Class
5517
-     * @throws EE_Error
5518
-     */
5519
-    public function refresh_entity_map_from_db($id)
5520
-    {
5521
-        $obj_in_map = $this->get_from_entity_map($id);
5522
-        if ($obj_in_map) {
5523
-            $wpdb_results = $this->_get_all_wpdb_results(
5524
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5525
-            );
5526
-            if ($wpdb_results && is_array($wpdb_results)) {
5527
-                $one_row = reset($wpdb_results);
5528
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5529
-                    $obj_in_map->set_from_db($field_name, $db_value);
5530
-                }
5531
-                // clear the cache of related model objects
5532
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5533
-                    $obj_in_map->clear_cache($relation_name, null, true);
5534
-                }
5535
-            }
5536
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5537
-            return $obj_in_map;
5538
-        }
5539
-        return $this->get_one_by_ID($id);
5540
-    }
5541
-
5542
-
5543
-
5544
-    /**
5545
-     * refresh_entity_map_with
5546
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5547
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5548
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5549
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5550
-     *
5551
-     * @param int|string    $id
5552
-     * @param EE_Base_Class $replacing_model_obj
5553
-     * @return \EE_Base_Class
5554
-     * @throws EE_Error
5555
-     */
5556
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5557
-    {
5558
-        $obj_in_map = $this->get_from_entity_map($id);
5559
-        if ($obj_in_map) {
5560
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5561
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5562
-                    $obj_in_map->set($field_name, $value);
5563
-                }
5564
-                // make the model object in the entity map's cache match the $replacing_model_obj
5565
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5566
-                    $obj_in_map->clear_cache($relation_name, null, true);
5567
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5568
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5569
-                    }
5570
-                }
5571
-            }
5572
-            return $obj_in_map;
5573
-        }
5574
-        $this->add_to_entity_map($replacing_model_obj);
5575
-        return $replacing_model_obj;
5576
-    }
5577
-
5578
-
5579
-
5580
-    /**
5581
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5582
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5583
-     * require_once($this->_getClassName().".class.php");
5584
-     *
5585
-     * @return string
5586
-     */
5587
-    private function _get_class_name()
5588
-    {
5589
-        return "EE_" . $this->get_this_model_name();
5590
-    }
5591
-
5592
-
5593
-
5594
-    /**
5595
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5596
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5597
-     * it would be 'Events'.
5598
-     *
5599
-     * @param int $quantity
5600
-     * @return string
5601
-     */
5602
-    public function item_name($quantity = 1)
5603
-    {
5604
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5605
-    }
5606
-
5607
-
5608
-
5609
-    /**
5610
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5611
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5612
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5613
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5614
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5615
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5616
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5617
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5618
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5619
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5620
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5621
-     *        return $previousReturnValue.$returnString;
5622
-     * }
5623
-     * require('EEM_Answer.model.php');
5624
-     * $answer=EEM_Answer::instance();
5625
-     * echo $answer->my_callback('monkeys',100);
5626
-     * //will output "you called my_callback! and passed args:monkeys,100"
5627
-     *
5628
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5629
-     * @param array  $args       array of original arguments passed to the function
5630
-     * @throws EE_Error
5631
-     * @return mixed whatever the plugin which calls add_filter decides
5632
-     */
5633
-    public function __call($methodName, $args)
5634
-    {
5635
-        $className = get_class($this);
5636
-        $tagName = "FHEE__{$className}__{$methodName}";
5637
-        if (! has_filter($tagName)) {
5638
-            throw new EE_Error(
5639
-                sprintf(
5640
-                    __(
5641
-                        '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 );',
5642
-                        'event_espresso'
5643
-                    ),
5644
-                    $methodName,
5645
-                    $className,
5646
-                    $tagName,
5647
-                    '<br />'
5648
-                )
5649
-            );
5650
-        }
5651
-        return apply_filters($tagName, null, $this, $args);
5652
-    }
5653
-
5654
-
5655
-
5656
-    /**
5657
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5658
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5659
-     *
5660
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5661
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5662
-     *                                                       the object's class name
5663
-     *                                                       or object's ID
5664
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5665
-     *                                                       exists in the database. If it does not, we add it
5666
-     * @throws EE_Error
5667
-     * @return EE_Base_Class
5668
-     */
5669
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5670
-    {
5671
-        $className = $this->_get_class_name();
5672
-        if ($base_class_obj_or_id instanceof $className) {
5673
-            $model_object = $base_class_obj_or_id;
5674
-        } else {
5675
-            $primary_key_field = $this->get_primary_key_field();
5676
-            if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5677
-                && (
5678
-                    is_int($base_class_obj_or_id)
5679
-                    || is_string($base_class_obj_or_id)
5680
-                )
5681
-            ) {
5682
-                // assume it's an ID.
5683
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5684
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5685
-            } elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5686
-                && is_string($base_class_obj_or_id)
5687
-            ) {
5688
-                // assume its a string representation of the object
5689
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5690
-            } else {
5691
-                throw new EE_Error(
5692
-                    sprintf(
5693
-                        __(
5694
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5695
-                            'event_espresso'
5696
-                        ),
5697
-                        $base_class_obj_or_id,
5698
-                        $this->_get_class_name(),
5699
-                        print_r($base_class_obj_or_id, true)
5700
-                    )
5701
-                );
5702
-            }
5703
-        }
5704
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5705
-            $model_object->save();
5706
-        }
5707
-        return $model_object;
5708
-    }
5709
-
5710
-
5711
-
5712
-    /**
5713
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5714
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5715
-     * returns it ID.
5716
-     *
5717
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5718
-     * @return int|string depending on the type of this model object's ID
5719
-     * @throws EE_Error
5720
-     */
5721
-    public function ensure_is_ID($base_class_obj_or_id)
5722
-    {
5723
-        $className = $this->_get_class_name();
5724
-        if ($base_class_obj_or_id instanceof $className) {
5725
-            /** @var $base_class_obj_or_id EE_Base_Class */
5726
-            $id = $base_class_obj_or_id->ID();
5727
-        } elseif (is_int($base_class_obj_or_id)) {
5728
-            // assume it's an ID
5729
-            $id = $base_class_obj_or_id;
5730
-        } elseif (is_string($base_class_obj_or_id)) {
5731
-            // assume its a string representation of the object
5732
-            $id = $base_class_obj_or_id;
5733
-        } else {
5734
-            throw new EE_Error(sprintf(
5735
-                __(
5736
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5737
-                    'event_espresso'
5738
-                ),
5739
-                $base_class_obj_or_id,
5740
-                $this->_get_class_name(),
5741
-                print_r($base_class_obj_or_id, true)
5742
-            ));
5743
-        }
5744
-        return $id;
5745
-    }
5746
-
5747
-
5748
-
5749
-    /**
5750
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5751
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5752
-     * been sanitized and converted into the appropriate domain.
5753
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5754
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5755
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5756
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5757
-     * $EVT = EEM_Event::instance(); $old_setting =
5758
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5759
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5760
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5761
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5762
-     *
5763
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5764
-     * @return void
5765
-     */
5766
-    public function assume_values_already_prepared_by_model_object(
5767
-        $values_already_prepared = self::not_prepared_by_model_object
5768
-    ) {
5769
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5770
-    }
5771
-
5772
-
5773
-
5774
-    /**
5775
-     * Read comments for assume_values_already_prepared_by_model_object()
5776
-     *
5777
-     * @return int
5778
-     */
5779
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5780
-    {
5781
-        return $this->_values_already_prepared_by_model_object;
5782
-    }
5783
-
5784
-
5785
-
5786
-    /**
5787
-     * Gets all the indexes on this model
5788
-     *
5789
-     * @return EE_Index[]
5790
-     */
5791
-    public function indexes()
5792
-    {
5793
-        return $this->_indexes;
5794
-    }
5795
-
5796
-
5797
-
5798
-    /**
5799
-     * Gets all the Unique Indexes on this model
5800
-     *
5801
-     * @return EE_Unique_Index[]
5802
-     */
5803
-    public function unique_indexes()
5804
-    {
5805
-        $unique_indexes = array();
5806
-        foreach ($this->_indexes as $name => $index) {
5807
-            if ($index instanceof EE_Unique_Index) {
5808
-                $unique_indexes [ $name ] = $index;
5809
-            }
5810
-        }
5811
-        return $unique_indexes;
5812
-    }
5813
-
5814
-
5815
-
5816
-    /**
5817
-     * Gets all the fields which, when combined, make the primary key.
5818
-     * This is usually just an array with 1 element (the primary key), but in cases
5819
-     * where there is no primary key, it's a combination of fields as defined
5820
-     * on a primary index
5821
-     *
5822
-     * @return EE_Model_Field_Base[] indexed by the field's name
5823
-     * @throws EE_Error
5824
-     */
5825
-    public function get_combined_primary_key_fields()
5826
-    {
5827
-        foreach ($this->indexes() as $index) {
5828
-            if ($index instanceof EE_Primary_Key_Index) {
5829
-                return $index->fields();
5830
-            }
5831
-        }
5832
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5833
-    }
5834
-
5835
-
5836
-
5837
-    /**
5838
-     * Used to build a primary key string (when the model has no primary key),
5839
-     * which can be used a unique string to identify this model object.
5840
-     *
5841
-     * @param array $cols_n_values keys are field names, values are their values
5842
-     * @return string
5843
-     * @throws EE_Error
5844
-     */
5845
-    public function get_index_primary_key_string($cols_n_values)
5846
-    {
5847
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5848
-            $cols_n_values,
5849
-            $this->get_combined_primary_key_fields()
5850
-        );
5851
-        return http_build_query($cols_n_values_for_primary_key_index);
5852
-    }
5853
-
5854
-
5855
-
5856
-    /**
5857
-     * Gets the field values from the primary key string
5858
-     *
5859
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5860
-     * @param string $index_primary_key_string
5861
-     * @return null|array
5862
-     * @throws EE_Error
5863
-     */
5864
-    public function parse_index_primary_key_string($index_primary_key_string)
5865
-    {
5866
-        $key_fields = $this->get_combined_primary_key_fields();
5867
-        // check all of them are in the $id
5868
-        $key_vals_in_combined_pk = array();
5869
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5870
-        foreach ($key_fields as $key_field_name => $field_obj) {
5871
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5872
-                return null;
5873
-            }
5874
-        }
5875
-        return $key_vals_in_combined_pk;
5876
-    }
5877
-
5878
-
5879
-
5880
-    /**
5881
-     * verifies that an array of key-value pairs for model fields has a key
5882
-     * for each field comprising the primary key index
5883
-     *
5884
-     * @param array $key_vals
5885
-     * @return boolean
5886
-     * @throws EE_Error
5887
-     */
5888
-    public function has_all_combined_primary_key_fields($key_vals)
5889
-    {
5890
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5891
-        foreach ($keys_it_should_have as $key) {
5892
-            if (! isset($key_vals[ $key ])) {
5893
-                return false;
5894
-            }
5895
-        }
5896
-        return true;
5897
-    }
5898
-
5899
-
5900
-
5901
-    /**
5902
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5903
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5904
-     *
5905
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5906
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5907
-     * @throws EE_Error
5908
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5909
-     *                                                              indexed)
5910
-     */
5911
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5912
-    {
5913
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5914
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5915
-        } elseif (is_array($model_object_or_attributes_array)) {
5916
-            $attributes_array = $model_object_or_attributes_array;
5917
-        } else {
5918
-            throw new EE_Error(sprintf(__(
5919
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5920
-                "event_espresso"
5921
-            ), $model_object_or_attributes_array));
5922
-        }
5923
-        // even copies obviously won't have the same ID, so remove the primary key
5924
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5925
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5926
-            unset($attributes_array[ $this->primary_key_name() ]);
5927
-        }
5928
-        if (isset($query_params[0])) {
5929
-            $query_params[0] = array_merge($attributes_array, $query_params);
5930
-        } else {
5931
-            $query_params[0] = $attributes_array;
5932
-        }
5933
-        return $this->get_all($query_params);
5934
-    }
5935
-
5936
-
5937
-
5938
-    /**
5939
-     * Gets the first copy we find. See get_all_copies for more details
5940
-     *
5941
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5942
-     * @param array $query_params
5943
-     * @return EE_Base_Class
5944
-     * @throws EE_Error
5945
-     */
5946
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5947
-    {
5948
-        if (! is_array($query_params)) {
5949
-            EE_Error::doing_it_wrong(
5950
-                'EEM_Base::get_one_copy',
5951
-                sprintf(
5952
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5953
-                    gettype($query_params)
5954
-                ),
5955
-                '4.6.0'
5956
-            );
5957
-            $query_params = array();
5958
-        }
5959
-        $query_params['limit'] = 1;
5960
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5961
-        if (is_array($copies)) {
5962
-            return array_shift($copies);
5963
-        }
5964
-        return null;
5965
-    }
5966
-
5967
-
5968
-
5969
-    /**
5970
-     * Updates the item with the specified id. Ignores default query parameters because
5971
-     * we have specified the ID, and its assumed we KNOW what we're doing
5972
-     *
5973
-     * @param array      $fields_n_values keys are field names, values are their new values
5974
-     * @param int|string $id              the value of the primary key to update
5975
-     * @return int number of rows updated
5976
-     * @throws EE_Error
5977
-     */
5978
-    public function update_by_ID($fields_n_values, $id)
5979
-    {
5980
-        $query_params = array(
5981
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5982
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5983
-        );
5984
-        return $this->update($fields_n_values, $query_params);
5985
-    }
5986
-
5987
-
5988
-
5989
-    /**
5990
-     * Changes an operator which was supplied to the models into one usable in SQL
5991
-     *
5992
-     * @param string $operator_supplied
5993
-     * @return string an operator which can be used in SQL
5994
-     * @throws EE_Error
5995
-     */
5996
-    private function _prepare_operator_for_sql($operator_supplied)
5997
-    {
5998
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5999
-            : null;
6000
-        if ($sql_operator) {
6001
-            return $sql_operator;
6002
-        }
6003
-        throw new EE_Error(
6004
-            sprintf(
6005
-                __(
6006
-                    "The operator '%s' is not in the list of valid operators: %s",
6007
-                    "event_espresso"
6008
-                ),
6009
-                $operator_supplied,
6010
-                implode(",", array_keys($this->_valid_operators))
6011
-            )
6012
-        );
6013
-    }
6014
-
6015
-
6016
-
6017
-    /**
6018
-     * Gets the valid operators
6019
-     * @return array keys are accepted strings, values are the SQL they are converted to
6020
-     */
6021
-    public function valid_operators()
6022
-    {
6023
-        return $this->_valid_operators;
6024
-    }
6025
-
6026
-
6027
-
6028
-    /**
6029
-     * Gets the between-style operators (take 2 arguments).
6030
-     * @return array keys are accepted strings, values are the SQL they are converted to
6031
-     */
6032
-    public function valid_between_style_operators()
6033
-    {
6034
-        return array_intersect(
6035
-            $this->valid_operators(),
6036
-            $this->_between_style_operators
6037
-        );
6038
-    }
6039
-
6040
-    /**
6041
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6042
-     * @return array keys are accepted strings, values are the SQL they are converted to
6043
-     */
6044
-    public function valid_like_style_operators()
6045
-    {
6046
-        return array_intersect(
6047
-            $this->valid_operators(),
6048
-            $this->_like_style_operators
6049
-        );
6050
-    }
6051
-
6052
-    /**
6053
-     * Gets the "in"-style operators
6054
-     * @return array keys are accepted strings, values are the SQL they are converted to
6055
-     */
6056
-    public function valid_in_style_operators()
6057
-    {
6058
-        return array_intersect(
6059
-            $this->valid_operators(),
6060
-            $this->_in_style_operators
6061
-        );
6062
-    }
6063
-
6064
-    /**
6065
-     * Gets the "null"-style operators (accept no arguments)
6066
-     * @return array keys are accepted strings, values are the SQL they are converted to
6067
-     */
6068
-    public function valid_null_style_operators()
6069
-    {
6070
-        return array_intersect(
6071
-            $this->valid_operators(),
6072
-            $this->_null_style_operators
6073
-        );
6074
-    }
6075
-
6076
-    /**
6077
-     * Gets an array where keys are the primary keys and values are their 'names'
6078
-     * (as determined by the model object's name() function, which is often overridden)
6079
-     *
6080
-     * @param array $query_params like get_all's
6081
-     * @return string[]
6082
-     * @throws EE_Error
6083
-     */
6084
-    public function get_all_names($query_params = array())
6085
-    {
6086
-        $objs = $this->get_all($query_params);
6087
-        $names = array();
6088
-        foreach ($objs as $obj) {
6089
-            $names[ $obj->ID() ] = $obj->name();
6090
-        }
6091
-        return $names;
6092
-    }
6093
-
6094
-
6095
-
6096
-    /**
6097
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6098
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6099
-     * this is duplicated effort and reduces efficiency) you would be better to use
6100
-     * array_keys() on $model_objects.
6101
-     *
6102
-     * @param \EE_Base_Class[] $model_objects
6103
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6104
-     *                                               in the returned array
6105
-     * @return array
6106
-     * @throws EE_Error
6107
-     */
6108
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6109
-    {
6110
-        if (! $this->has_primary_key_field()) {
6111
-            if (WP_DEBUG) {
6112
-                EE_Error::add_error(
6113
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6114
-                    __FILE__,
6115
-                    __FUNCTION__,
6116
-                    __LINE__
6117
-                );
6118
-            }
6119
-        }
6120
-        $IDs = array();
6121
-        foreach ($model_objects as $model_object) {
6122
-            $id = $model_object->ID();
6123
-            if (! $id) {
6124
-                if ($filter_out_empty_ids) {
6125
-                    continue;
6126
-                }
6127
-                if (WP_DEBUG) {
6128
-                    EE_Error::add_error(
6129
-                        __(
6130
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6131
-                            'event_espresso'
6132
-                        ),
6133
-                        __FILE__,
6134
-                        __FUNCTION__,
6135
-                        __LINE__
6136
-                    );
6137
-                }
6138
-            }
6139
-            $IDs[] = $id;
6140
-        }
6141
-        return $IDs;
6142
-    }
6143
-
6144
-
6145
-
6146
-    /**
6147
-     * Returns the string used in capabilities relating to this model. If there
6148
-     * are no capabilities that relate to this model returns false
6149
-     *
6150
-     * @return string|false
6151
-     */
6152
-    public function cap_slug()
6153
-    {
6154
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6155
-    }
6156
-
6157
-
6158
-
6159
-    /**
6160
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6161
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6162
-     * only returns the cap restrictions array in that context (ie, the array
6163
-     * at that key)
6164
-     *
6165
-     * @param string $context
6166
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6167
-     * @throws EE_Error
6168
-     */
6169
-    public function cap_restrictions($context = EEM_Base::caps_read)
6170
-    {
6171
-        EEM_Base::verify_is_valid_cap_context($context);
6172
-        // check if we ought to run the restriction generator first
6173
-        if (isset($this->_cap_restriction_generators[ $context ])
6174
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6175
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6176
-        ) {
6177
-            $this->_cap_restrictions[ $context ] = array_merge(
6178
-                $this->_cap_restrictions[ $context ],
6179
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6180
-            );
6181
-        }
6182
-        // and make sure we've finalized the construction of each restriction
6183
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6184
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6185
-                $where_conditions_obj->_finalize_construct($this);
6186
-            }
6187
-        }
6188
-        return $this->_cap_restrictions[ $context ];
6189
-    }
6190
-
6191
-
6192
-
6193
-    /**
6194
-     * Indicating whether or not this model thinks its a wp core model
6195
-     *
6196
-     * @return boolean
6197
-     */
6198
-    public function is_wp_core_model()
6199
-    {
6200
-        return $this->_wp_core_model;
6201
-    }
6202
-
6203
-
6204
-
6205
-    /**
6206
-     * Gets all the caps that are missing which impose a restriction on
6207
-     * queries made in this context
6208
-     *
6209
-     * @param string $context one of EEM_Base::caps_ constants
6210
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6211
-     * @throws EE_Error
6212
-     */
6213
-    public function caps_missing($context = EEM_Base::caps_read)
6214
-    {
6215
-        $missing_caps = array();
6216
-        $cap_restrictions = $this->cap_restrictions($context);
6217
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6218
-            if (! EE_Capabilities::instance()
6219
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6220
-            ) {
6221
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6222
-            }
6223
-        }
6224
-        return $missing_caps;
6225
-    }
6226
-
6227
-
6228
-
6229
-    /**
6230
-     * Gets the mapping from capability contexts to action strings used in capability names
6231
-     *
6232
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6233
-     * one of 'read', 'edit', or 'delete'
6234
-     */
6235
-    public function cap_contexts_to_cap_action_map()
6236
-    {
6237
-        return apply_filters(
6238
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6239
-            $this->_cap_contexts_to_cap_action_map,
6240
-            $this
6241
-        );
6242
-    }
6243
-
6244
-
6245
-
6246
-    /**
6247
-     * Gets the action string for the specified capability context
6248
-     *
6249
-     * @param string $context
6250
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6251
-     * @throws EE_Error
6252
-     */
6253
-    public function cap_action_for_context($context)
6254
-    {
6255
-        $mapping = $this->cap_contexts_to_cap_action_map();
6256
-        if (isset($mapping[ $context ])) {
6257
-            return $mapping[ $context ];
6258
-        }
6259
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6260
-            return $action;
6261
-        }
6262
-        throw new EE_Error(
6263
-            sprintf(
6264
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6265
-                $context,
6266
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6267
-            )
6268
-        );
6269
-    }
6270
-
6271
-
6272
-
6273
-    /**
6274
-     * Returns all the capability contexts which are valid when querying models
6275
-     *
6276
-     * @return array
6277
-     */
6278
-    public static function valid_cap_contexts()
6279
-    {
6280
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6281
-            self::caps_read,
6282
-            self::caps_read_admin,
6283
-            self::caps_edit,
6284
-            self::caps_delete,
6285
-        ));
6286
-    }
6287
-
6288
-
6289
-
6290
-    /**
6291
-     * Returns all valid options for 'default_where_conditions'
6292
-     *
6293
-     * @return array
6294
-     */
6295
-    public static function valid_default_where_conditions()
6296
-    {
6297
-        return array(
6298
-            EEM_Base::default_where_conditions_all,
6299
-            EEM_Base::default_where_conditions_this_only,
6300
-            EEM_Base::default_where_conditions_others_only,
6301
-            EEM_Base::default_where_conditions_minimum_all,
6302
-            EEM_Base::default_where_conditions_minimum_others,
6303
-            EEM_Base::default_where_conditions_none
6304
-        );
6305
-    }
6306
-
6307
-    // public static function default_where_conditions_full
6308
-    /**
6309
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6310
-     *
6311
-     * @param string $context
6312
-     * @return bool
6313
-     * @throws EE_Error
6314
-     */
6315
-    public static function verify_is_valid_cap_context($context)
6316
-    {
6317
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6318
-        if (in_array($context, $valid_cap_contexts)) {
6319
-            return true;
6320
-        }
6321
-        throw new EE_Error(
6322
-            sprintf(
6323
-                __(
6324
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6325
-                    'event_espresso'
6326
-                ),
6327
-                $context,
6328
-                'EEM_Base',
6329
-                implode(',', $valid_cap_contexts)
6330
-            )
6331
-        );
6332
-    }
6333
-
6334
-
6335
-
6336
-    /**
6337
-     * Clears all the models field caches. This is only useful when a sub-class
6338
-     * might have added a field or something and these caches might be invalidated
6339
-     */
6340
-    protected function _invalidate_field_caches()
6341
-    {
6342
-        $this->_cache_foreign_key_to_fields = array();
6343
-        $this->_cached_fields = null;
6344
-        $this->_cached_fields_non_db_only = null;
6345
-    }
6346
-
6347
-
6348
-
6349
-    /**
6350
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6351
-     * (eg "and", "or", "not").
6352
-     *
6353
-     * @return array
6354
-     */
6355
-    public function logic_query_param_keys()
6356
-    {
6357
-        return $this->_logic_query_param_keys;
6358
-    }
6359
-
6360
-
6361
-
6362
-    /**
6363
-     * Determines whether or not the where query param array key is for a logic query param.
6364
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6365
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6366
-     *
6367
-     * @param $query_param_key
6368
-     * @return bool
6369
-     */
6370
-    public function is_logic_query_param_key($query_param_key)
6371
-    {
6372
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6373
-            if ($query_param_key === $logic_query_param_key
6374
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6375
-            ) {
6376
-                return true;
6377
-            }
6378
-        }
6379
-        return false;
6380
-    }
3867
+		}
3868
+		return $null_friendly_where_conditions;
3869
+	}
3870
+
3871
+
3872
+
3873
+	/**
3874
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3875
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3876
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3877
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3878
+	 *
3879
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3880
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3881
+	 */
3882
+	private function _get_default_where_conditions($model_relation_path = null)
3883
+	{
3884
+		if ($this->_ignore_where_strategy) {
3885
+			return array();
3886
+		}
3887
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3888
+	}
3889
+
3890
+
3891
+
3892
+	/**
3893
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3894
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3895
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3896
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3897
+	 * Similar to _get_default_where_conditions
3898
+	 *
3899
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3900
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3901
+	 */
3902
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3903
+	{
3904
+		if ($this->_ignore_where_strategy) {
3905
+			return array();
3906
+		}
3907
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3908
+	}
3909
+
3910
+
3911
+
3912
+	/**
3913
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3914
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3915
+	 *
3916
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3917
+	 * @return string
3918
+	 * @throws EE_Error
3919
+	 */
3920
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3921
+	{
3922
+		$selects = $this->_get_columns_to_select_for_this_model();
3923
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3924
+			$name_of_other_model_included) {
3925
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3926
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3927
+			foreach ($other_model_selects as $key => $value) {
3928
+				$selects[] = $value;
3929
+			}
3930
+		}
3931
+		return implode(", ", $selects);
3932
+	}
3933
+
3934
+
3935
+
3936
+	/**
3937
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3938
+	 * So that's going to be the columns for all the fields on the model
3939
+	 *
3940
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3941
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3942
+	 */
3943
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3944
+	{
3945
+		$fields = $this->field_settings();
3946
+		$selects = array();
3947
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3948
+			$model_relation_chain,
3949
+			$this->get_this_model_name()
3950
+		);
3951
+		foreach ($fields as $field_obj) {
3952
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3953
+						 . $field_obj->get_table_alias()
3954
+						 . "."
3955
+						 . $field_obj->get_table_column()
3956
+						 . " AS '"
3957
+						 . $table_alias_with_model_relation_chain_prefix
3958
+						 . $field_obj->get_table_alias()
3959
+						 . "."
3960
+						 . $field_obj->get_table_column()
3961
+						 . "'";
3962
+		}
3963
+		// make sure we are also getting the PKs of each table
3964
+		$tables = $this->get_tables();
3965
+		if (count($tables) > 1) {
3966
+			foreach ($tables as $table_obj) {
3967
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3968
+									   . $table_obj->get_fully_qualified_pk_column();
3969
+				if (! in_array($qualified_pk_column, $selects)) {
3970
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3971
+				}
3972
+			}
3973
+		}
3974
+		return $selects;
3975
+	}
3976
+
3977
+
3978
+
3979
+	/**
3980
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3981
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3982
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3983
+	 * SQL for joining, and the data types
3984
+	 *
3985
+	 * @param null|string                 $original_query_param
3986
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3987
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3988
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3989
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3990
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3991
+	 *                                                          or 'Registration's
3992
+	 * @param string                      $original_query_param what it originally was (eg
3993
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3994
+	 *                                                          matches $query_param
3995
+	 * @throws EE_Error
3996
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3997
+	 */
3998
+	private function _extract_related_model_info_from_query_param(
3999
+		$query_param,
4000
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4001
+		$query_param_type,
4002
+		$original_query_param = null
4003
+	) {
4004
+		if ($original_query_param === null) {
4005
+			$original_query_param = $query_param;
4006
+		}
4007
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4008
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
4009
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
4010
+		$allow_fields = in_array(
4011
+			$query_param_type,
4012
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
4013
+			true
4014
+		);
4015
+		// check to see if we have a field on this model
4016
+		$this_model_fields = $this->field_settings(true);
4017
+		if (array_key_exists($query_param, $this_model_fields)) {
4018
+			if ($allow_fields) {
4019
+				return;
4020
+			}
4021
+			throw new EE_Error(
4022
+				sprintf(
4023
+					__(
4024
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4025
+						"event_espresso"
4026
+					),
4027
+					$query_param,
4028
+					get_class($this),
4029
+					$query_param_type,
4030
+					$original_query_param
4031
+				)
4032
+			);
4033
+		}
4034
+		// check if this is a special logic query param
4035
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4036
+			if ($allow_logic_query_params) {
4037
+				return;
4038
+			}
4039
+			throw new EE_Error(
4040
+				sprintf(
4041
+					__(
4042
+						'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4043
+						'event_espresso'
4044
+					),
4045
+					implode('", "', $this->_logic_query_param_keys),
4046
+					$query_param,
4047
+					get_class($this),
4048
+					'<br />',
4049
+					"\t"
4050
+					. ' $passed_in_query_info = <pre>'
4051
+					. print_r($passed_in_query_info, true)
4052
+					. '</pre>'
4053
+					. "\n\t"
4054
+					. ' $query_param_type = '
4055
+					. $query_param_type
4056
+					. "\n\t"
4057
+					. ' $original_query_param = '
4058
+					. $original_query_param
4059
+				)
4060
+			);
4061
+		}
4062
+		// check if it's a custom selection
4063
+		if ($this->_custom_selections instanceof CustomSelects
4064
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4065
+		) {
4066
+			return;
4067
+		}
4068
+		// check if has a model name at the beginning
4069
+		// and
4070
+		// check if it's a field on a related model
4071
+		if ($this->extractJoinModelFromQueryParams(
4072
+			$passed_in_query_info,
4073
+			$query_param,
4074
+			$original_query_param,
4075
+			$query_param_type
4076
+		)) {
4077
+			return;
4078
+		}
4079
+
4080
+		// ok so $query_param didn't start with a model name
4081
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4082
+		// it's wack, that's what it is
4083
+		throw new EE_Error(
4084
+			sprintf(
4085
+				esc_html__(
4086
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4087
+					"event_espresso"
4088
+				),
4089
+				$query_param,
4090
+				get_class($this),
4091
+				$query_param_type,
4092
+				$original_query_param
4093
+			)
4094
+		);
4095
+	}
4096
+
4097
+
4098
+	/**
4099
+	 * Extracts any possible join model information from the provided possible_join_string.
4100
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4101
+	 * parts that should be added to the query.
4102
+	 *
4103
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4104
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4105
+	 * @param null|string                 $original_query_param
4106
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4107
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4108
+	 * @return bool  returns true if a join was added and false if not.
4109
+	 * @throws EE_Error
4110
+	 */
4111
+	private function extractJoinModelFromQueryParams(
4112
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4113
+		$possible_join_string,
4114
+		$original_query_param,
4115
+		$query_parameter_type
4116
+	) {
4117
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4118
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4119
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4120
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4121
+				if ($possible_join_string === '') {
4122
+					// nothing left to $query_param
4123
+					// we should actually end in a field name, not a model like this!
4124
+					throw new EE_Error(
4125
+						sprintf(
4126
+							esc_html__(
4127
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4128
+								"event_espresso"
4129
+							),
4130
+							$possible_join_string,
4131
+							$query_parameter_type,
4132
+							get_class($this),
4133
+							$valid_related_model_name
4134
+						)
4135
+					);
4136
+				}
4137
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4138
+				$related_model_obj->_extract_related_model_info_from_query_param(
4139
+					$possible_join_string,
4140
+					$query_info_carrier,
4141
+					$query_parameter_type,
4142
+					$original_query_param
4143
+				);
4144
+				return true;
4145
+			}
4146
+			if ($possible_join_string === $valid_related_model_name) {
4147
+				$this->_add_join_to_model(
4148
+					$valid_related_model_name,
4149
+					$query_info_carrier,
4150
+					$original_query_param
4151
+				);
4152
+				return true;
4153
+			}
4154
+		}
4155
+		return false;
4156
+	}
4157
+
4158
+
4159
+	/**
4160
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4161
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4162
+	 * @throws EE_Error
4163
+	 */
4164
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4165
+	{
4166
+		if ($this->_custom_selections instanceof CustomSelects
4167
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4168
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4169
+			)
4170
+		) {
4171
+			$original_selects = $this->_custom_selections->originalSelects();
4172
+			foreach ($original_selects as $alias => $select_configuration) {
4173
+				$this->extractJoinModelFromQueryParams(
4174
+					$query_info_carrier,
4175
+					$select_configuration[0],
4176
+					$select_configuration[0],
4177
+					'custom_selects'
4178
+				);
4179
+			}
4180
+		}
4181
+	}
4182
+
4183
+
4184
+
4185
+	/**
4186
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4187
+	 * and store it on $passed_in_query_info
4188
+	 *
4189
+	 * @param string                      $model_name
4190
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4191
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4192
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4193
+	 *                                                          and are adding a join to 'Payment' with the original
4194
+	 *                                                          query param key
4195
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4196
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4197
+	 *                                                          Payment wants to add default query params so that it
4198
+	 *                                                          will know what models to prepend onto its default query
4199
+	 *                                                          params or in case it wants to rename tables (in case
4200
+	 *                                                          there are multiple joins to the same table)
4201
+	 * @return void
4202
+	 * @throws EE_Error
4203
+	 */
4204
+	private function _add_join_to_model(
4205
+		$model_name,
4206
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4207
+		$original_query_param
4208
+	) {
4209
+		$relation_obj = $this->related_settings_for($model_name);
4210
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4211
+		// check if the relation is HABTM, because then we're essentially doing two joins
4212
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4213
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4214
+			$join_model_obj = $relation_obj->get_join_model();
4215
+			// replace the model specified with the join model for this relation chain, whi
4216
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4217
+				$model_name,
4218
+				$join_model_obj->get_this_model_name(),
4219
+				$model_relation_chain
4220
+			);
4221
+			$passed_in_query_info->merge(
4222
+				new EE_Model_Query_Info_Carrier(
4223
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4224
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4225
+				)
4226
+			);
4227
+		}
4228
+		// now just join to the other table pointed to by the relation object, and add its data types
4229
+		$passed_in_query_info->merge(
4230
+			new EE_Model_Query_Info_Carrier(
4231
+				array($model_relation_chain => $model_name),
4232
+				$relation_obj->get_join_statement($model_relation_chain)
4233
+			)
4234
+		);
4235
+	}
4236
+
4237
+
4238
+
4239
+	/**
4240
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4241
+	 *
4242
+	 * @param array $where_params like EEM_Base::get_all
4243
+	 * @return string of SQL
4244
+	 * @throws EE_Error
4245
+	 */
4246
+	private function _construct_where_clause($where_params)
4247
+	{
4248
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4249
+		if ($SQL) {
4250
+			return " WHERE " . $SQL;
4251
+		}
4252
+		return '';
4253
+	}
4254
+
4255
+
4256
+
4257
+	/**
4258
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4259
+	 * and should be passed HAVING parameters, not WHERE parameters
4260
+	 *
4261
+	 * @param array $having_params
4262
+	 * @return string
4263
+	 * @throws EE_Error
4264
+	 */
4265
+	private function _construct_having_clause($having_params)
4266
+	{
4267
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4268
+		if ($SQL) {
4269
+			return " HAVING " . $SQL;
4270
+		}
4271
+		return '';
4272
+	}
4273
+
4274
+
4275
+	/**
4276
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4277
+	 * Event_Meta.meta_value = 'foo'))"
4278
+	 *
4279
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4280
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4281
+	 * @throws EE_Error
4282
+	 * @return string of SQL
4283
+	 */
4284
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4285
+	{
4286
+		$where_clauses = array();
4287
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4288
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4289
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4290
+				switch ($query_param) {
4291
+					case 'not':
4292
+					case 'NOT':
4293
+						$where_clauses[] = "! ("
4294
+										   . $this->_construct_condition_clause_recursive(
4295
+											   $op_and_value_or_sub_condition,
4296
+											   $glue
4297
+										   )
4298
+										   . ")";
4299
+						break;
4300
+					case 'and':
4301
+					case 'AND':
4302
+						$where_clauses[] = " ("
4303
+										   . $this->_construct_condition_clause_recursive(
4304
+											   $op_and_value_or_sub_condition,
4305
+											   ' AND '
4306
+										   )
4307
+										   . ")";
4308
+						break;
4309
+					case 'or':
4310
+					case 'OR':
4311
+						$where_clauses[] = " ("
4312
+										   . $this->_construct_condition_clause_recursive(
4313
+											   $op_and_value_or_sub_condition,
4314
+											   ' OR '
4315
+										   )
4316
+										   . ")";
4317
+						break;
4318
+				}
4319
+			} else {
4320
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4321
+				// if it's not a normal field, maybe it's a custom selection?
4322
+				if (! $field_obj) {
4323
+					if ($this->_custom_selections instanceof CustomSelects) {
4324
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4325
+					} else {
4326
+						throw new EE_Error(sprintf(__(
4327
+							"%s is neither a valid model field name, nor a custom selection",
4328
+							"event_espresso"
4329
+						), $query_param));
4330
+					}
4331
+				}
4332
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4333
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4334
+			}
4335
+		}
4336
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4337
+	}
4338
+
4339
+
4340
+
4341
+	/**
4342
+	 * Takes the input parameter and extract the table name (alias) and column name
4343
+	 *
4344
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4345
+	 * @throws EE_Error
4346
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4347
+	 */
4348
+	private function _deduce_column_name_from_query_param($query_param)
4349
+	{
4350
+		$field = $this->_deduce_field_from_query_param($query_param);
4351
+		if ($field) {
4352
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4353
+				$field->get_model_name(),
4354
+				$query_param
4355
+			);
4356
+			return $table_alias_prefix . $field->get_qualified_column();
4357
+		}
4358
+		if ($this->_custom_selections instanceof CustomSelects
4359
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4360
+		) {
4361
+			// maybe it's custom selection item?
4362
+			// if so, just use it as the "column name"
4363
+			return $query_param;
4364
+		}
4365
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4366
+			? implode(',', $this->_custom_selections->columnAliases())
4367
+			: '';
4368
+		throw new EE_Error(
4369
+			sprintf(
4370
+				__(
4371
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4372
+					"event_espresso"
4373
+				),
4374
+				$query_param,
4375
+				$custom_select_aliases
4376
+			)
4377
+		);
4378
+	}
4379
+
4380
+
4381
+
4382
+	/**
4383
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4384
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4385
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4386
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4387
+	 *
4388
+	 * @param string $condition_query_param_key
4389
+	 * @return string
4390
+	 */
4391
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4392
+	{
4393
+		$pos_of_star = strpos($condition_query_param_key, '*');
4394
+		if ($pos_of_star === false) {
4395
+			return $condition_query_param_key;
4396
+		}
4397
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4398
+		return $condition_query_param_sans_star;
4399
+	}
4400
+
4401
+
4402
+
4403
+	/**
4404
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4405
+	 *
4406
+	 * @param                            mixed      array | string    $op_and_value
4407
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4408
+	 * @throws EE_Error
4409
+	 * @return string
4410
+	 */
4411
+	private function _construct_op_and_value($op_and_value, $field_obj)
4412
+	{
4413
+		if (is_array($op_and_value)) {
4414
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4415
+			if (! $operator) {
4416
+				$php_array_like_string = array();
4417
+				foreach ($op_and_value as $key => $value) {
4418
+					$php_array_like_string[] = "$key=>$value";
4419
+				}
4420
+				throw new EE_Error(
4421
+					sprintf(
4422
+						__(
4423
+							"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))",
4424
+							"event_espresso"
4425
+						),
4426
+						implode(",", $php_array_like_string)
4427
+					)
4428
+				);
4429
+			}
4430
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4431
+		} else {
4432
+			$operator = '=';
4433
+			$value = $op_and_value;
4434
+		}
4435
+		// check to see if the value is actually another field
4436
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4437
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4438
+		}
4439
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4440
+			// in this case, the value should be an array, or at least a comma-separated list
4441
+			// it will need to handle a little differently
4442
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4443
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4444
+			return $operator . SP . $cleaned_value;
4445
+		}
4446
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4447
+			// the value should be an array with count of two.
4448
+			if (count($value) !== 2) {
4449
+				throw new EE_Error(
4450
+					sprintf(
4451
+						__(
4452
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4453
+							'event_espresso'
4454
+						),
4455
+						"BETWEEN"
4456
+					)
4457
+				);
4458
+			}
4459
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4460
+			return $operator . SP . $cleaned_value;
4461
+		}
4462
+		if (in_array($operator, $this->valid_null_style_operators())) {
4463
+			if ($value !== null) {
4464
+				throw new EE_Error(
4465
+					sprintf(
4466
+						__(
4467
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4468
+							"event_espresso"
4469
+						),
4470
+						$value,
4471
+						$operator
4472
+					)
4473
+				);
4474
+			}
4475
+			return $operator;
4476
+		}
4477
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4478
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4479
+			// remove other junk. So just treat it as a string.
4480
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4481
+		}
4482
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4483
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4484
+		}
4485
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4486
+			throw new EE_Error(
4487
+				sprintf(
4488
+					__(
4489
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4490
+						'event_espresso'
4491
+					),
4492
+					$operator,
4493
+					$operator
4494
+				)
4495
+			);
4496
+		}
4497
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4498
+			throw new EE_Error(
4499
+				sprintf(
4500
+					__(
4501
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4502
+						'event_espresso'
4503
+					),
4504
+					$operator,
4505
+					$operator
4506
+				)
4507
+			);
4508
+		}
4509
+		throw new EE_Error(
4510
+			sprintf(
4511
+				__(
4512
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4513
+					"event_espresso"
4514
+				),
4515
+				http_build_query($op_and_value)
4516
+			)
4517
+		);
4518
+	}
4519
+
4520
+
4521
+
4522
+	/**
4523
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4524
+	 *
4525
+	 * @param array                      $values
4526
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4527
+	 *                                              '%s'
4528
+	 * @return string
4529
+	 * @throws EE_Error
4530
+	 */
4531
+	public function _construct_between_value($values, $field_obj)
4532
+	{
4533
+		$cleaned_values = array();
4534
+		foreach ($values as $value) {
4535
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4536
+		}
4537
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4538
+	}
4539
+
4540
+
4541
+
4542
+	/**
4543
+	 * Takes an array or a comma-separated list of $values and cleans them
4544
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4545
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4546
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4547
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4548
+	 *
4549
+	 * @param mixed                      $values    array or comma-separated string
4550
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4551
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4552
+	 * @throws EE_Error
4553
+	 */
4554
+	public function _construct_in_value($values, $field_obj)
4555
+	{
4556
+		// check if the value is a CSV list
4557
+		if (is_string($values)) {
4558
+			// in which case, turn it into an array
4559
+			$values = explode(",", $values);
4560
+		}
4561
+		$cleaned_values = array();
4562
+		foreach ($values as $value) {
4563
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4564
+		}
4565
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4566
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4567
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4568
+		if (empty($cleaned_values)) {
4569
+			$all_fields = $this->field_settings();
4570
+			$a_field = array_shift($all_fields);
4571
+			$main_table = $this->_get_main_table();
4572
+			$cleaned_values[] = "SELECT "
4573
+								. $a_field->get_table_column()
4574
+								. " FROM "
4575
+								. $main_table->get_table_name()
4576
+								. " WHERE FALSE";
4577
+		}
4578
+		return "(" . implode(",", $cleaned_values) . ")";
4579
+	}
4580
+
4581
+
4582
+
4583
+	/**
4584
+	 * @param mixed                      $value
4585
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4586
+	 * @throws EE_Error
4587
+	 * @return false|null|string
4588
+	 */
4589
+	private function _wpdb_prepare_using_field($value, $field_obj)
4590
+	{
4591
+		/** @type WPDB $wpdb */
4592
+		global $wpdb;
4593
+		if ($field_obj instanceof EE_Model_Field_Base) {
4594
+			return $wpdb->prepare(
4595
+				$field_obj->get_wpdb_data_type(),
4596
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4597
+			);
4598
+		} //$field_obj should really just be a data type
4599
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4600
+			throw new EE_Error(
4601
+				sprintf(
4602
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4603
+					$field_obj,
4604
+					implode(",", $this->_valid_wpdb_data_types)
4605
+				)
4606
+			);
4607
+		}
4608
+		return $wpdb->prepare($field_obj, $value);
4609
+	}
4610
+
4611
+
4612
+
4613
+	/**
4614
+	 * Takes the input parameter and finds the model field that it indicates.
4615
+	 *
4616
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4617
+	 * @throws EE_Error
4618
+	 * @return EE_Model_Field_Base
4619
+	 */
4620
+	protected function _deduce_field_from_query_param($query_param_name)
4621
+	{
4622
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4623
+		// which will help us find the database table and column
4624
+		$query_param_parts = explode(".", $query_param_name);
4625
+		if (empty($query_param_parts)) {
4626
+			throw new EE_Error(sprintf(__(
4627
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4628
+				'event_espresso'
4629
+			), $query_param_name));
4630
+		}
4631
+		$number_of_parts = count($query_param_parts);
4632
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4633
+		if ($number_of_parts === 1) {
4634
+			$field_name = $last_query_param_part;
4635
+			$model_obj = $this;
4636
+		} else {// $number_of_parts >= 2
4637
+			// the last part is the column name, and there are only 2parts. therefore...
4638
+			$field_name = $last_query_param_part;
4639
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4640
+		}
4641
+		try {
4642
+			return $model_obj->field_settings_for($field_name);
4643
+		} catch (EE_Error $e) {
4644
+			return null;
4645
+		}
4646
+	}
4647
+
4648
+
4649
+
4650
+	/**
4651
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4652
+	 * alias and column which corresponds to it
4653
+	 *
4654
+	 * @param string $field_name
4655
+	 * @throws EE_Error
4656
+	 * @return string
4657
+	 */
4658
+	public function _get_qualified_column_for_field($field_name)
4659
+	{
4660
+		$all_fields = $this->field_settings();
4661
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4662
+		if ($field) {
4663
+			return $field->get_qualified_column();
4664
+		}
4665
+		throw new EE_Error(
4666
+			sprintf(
4667
+				__(
4668
+					"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.",
4669
+					'event_espresso'
4670
+				),
4671
+				$field_name,
4672
+				get_class($this)
4673
+			)
4674
+		);
4675
+	}
4676
+
4677
+
4678
+
4679
+	/**
4680
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4681
+	 * Example usage:
4682
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4683
+	 *      array(),
4684
+	 *      ARRAY_A,
4685
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4686
+	 *  );
4687
+	 * is equivalent to
4688
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4689
+	 * and
4690
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4691
+	 *      array(
4692
+	 *          array(
4693
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4694
+	 *          ),
4695
+	 *          ARRAY_A,
4696
+	 *          implode(
4697
+	 *              ', ',
4698
+	 *              array_merge(
4699
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4700
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4701
+	 *              )
4702
+	 *          )
4703
+	 *      )
4704
+	 *  );
4705
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4706
+	 *
4707
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4708
+	 *                                            and the one whose fields you are selecting for example: when querying
4709
+	 *                                            tickets model and selecting fields from the tickets model you would
4710
+	 *                                            leave this parameter empty, because no models are needed to join
4711
+	 *                                            between the queried model and the selected one. Likewise when
4712
+	 *                                            querying the datetime model and selecting fields from the tickets
4713
+	 *                                            model, it would also be left empty, because there is a direct
4714
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4715
+	 *                                            them together. However, when querying from the event model and
4716
+	 *                                            selecting fields from the ticket model, you should provide the string
4717
+	 *                                            'Datetime', indicating that the event model must first join to the
4718
+	 *                                            datetime model in order to find its relation to ticket model.
4719
+	 *                                            Also, when querying from the venue model and selecting fields from
4720
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4721
+	 *                                            indicating you need to join the venue model to the event model,
4722
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4723
+	 *                                            This string is used to deduce the prefix that gets added onto the
4724
+	 *                                            models' tables qualified columns
4725
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4726
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4727
+	 *                                            qualified column names
4728
+	 * @return array|string
4729
+	 */
4730
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4731
+	{
4732
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4733
+		$qualified_columns = array();
4734
+		foreach ($this->field_settings() as $field_name => $field) {
4735
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4736
+		}
4737
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4738
+	}
4739
+
4740
+
4741
+
4742
+	/**
4743
+	 * constructs the select use on special limit joins
4744
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4745
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4746
+	 * (as that is typically where the limits would be set).
4747
+	 *
4748
+	 * @param  string       $table_alias The table the select is being built for
4749
+	 * @param  mixed|string $limit       The limit for this select
4750
+	 * @return string                The final select join element for the query.
4751
+	 */
4752
+	public function _construct_limit_join_select($table_alias, $limit)
4753
+	{
4754
+		$SQL = '';
4755
+		foreach ($this->_tables as $table_obj) {
4756
+			if ($table_obj instanceof EE_Primary_Table) {
4757
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4758
+					? $table_obj->get_select_join_limit($limit)
4759
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4760
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4761
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4762
+					? $table_obj->get_select_join_limit_join($limit)
4763
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4764
+			}
4765
+		}
4766
+		return $SQL;
4767
+	}
4768
+
4769
+
4770
+
4771
+	/**
4772
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4773
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4774
+	 *
4775
+	 * @return string SQL
4776
+	 * @throws EE_Error
4777
+	 */
4778
+	public function _construct_internal_join()
4779
+	{
4780
+		$SQL = $this->_get_main_table()->get_table_sql();
4781
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4782
+		return $SQL;
4783
+	}
4784
+
4785
+
4786
+
4787
+	/**
4788
+	 * Constructs the SQL for joining all the tables on this model.
4789
+	 * Normally $alias should be the primary table's alias, but in cases where
4790
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4791
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4792
+	 * alias, this will construct SQL like:
4793
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4794
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4795
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4796
+	 *
4797
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4798
+	 * @return string
4799
+	 */
4800
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4801
+	{
4802
+		$SQL = '';
4803
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4804
+		foreach ($this->_tables as $table_obj) {
4805
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4806
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4807
+					// so we're joining to this table, meaning the table is already in
4808
+					// the FROM statement, BUT the primary table isn't. So we want
4809
+					// to add the inverse join sql
4810
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4811
+				} else {
4812
+					// just add a regular JOIN to this table from the primary table
4813
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4814
+				}
4815
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4816
+		}
4817
+		return $SQL;
4818
+	}
4819
+
4820
+
4821
+
4822
+	/**
4823
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4824
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4825
+	 * their data type (eg, '%s', '%d', etc)
4826
+	 *
4827
+	 * @return array
4828
+	 */
4829
+	public function _get_data_types()
4830
+	{
4831
+		$data_types = array();
4832
+		foreach ($this->field_settings() as $field_obj) {
4833
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4834
+			/** @var $field_obj EE_Model_Field_Base */
4835
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4836
+		}
4837
+		return $data_types;
4838
+	}
4839
+
4840
+
4841
+
4842
+	/**
4843
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4844
+	 *
4845
+	 * @param string $model_name
4846
+	 * @throws EE_Error
4847
+	 * @return EEM_Base
4848
+	 */
4849
+	public function get_related_model_obj($model_name)
4850
+	{
4851
+		$model_classname = "EEM_" . $model_name;
4852
+		if (! class_exists($model_classname)) {
4853
+			throw new EE_Error(sprintf(__(
4854
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4855
+				'event_espresso'
4856
+			), $model_name, $model_classname));
4857
+		}
4858
+		return call_user_func($model_classname . "::instance");
4859
+	}
4860
+
4861
+
4862
+
4863
+	/**
4864
+	 * Returns the array of EE_ModelRelations for this model.
4865
+	 *
4866
+	 * @return EE_Model_Relation_Base[]
4867
+	 */
4868
+	public function relation_settings()
4869
+	{
4870
+		return $this->_model_relations;
4871
+	}
4872
+
4873
+
4874
+
4875
+	/**
4876
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4877
+	 * because without THOSE models, this model probably doesn't have much purpose.
4878
+	 * (Eg, without an event, datetimes have little purpose.)
4879
+	 *
4880
+	 * @return EE_Belongs_To_Relation[]
4881
+	 */
4882
+	public function belongs_to_relations()
4883
+	{
4884
+		$belongs_to_relations = array();
4885
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4886
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4887
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4888
+			}
4889
+		}
4890
+		return $belongs_to_relations;
4891
+	}
4892
+
4893
+
4894
+
4895
+	/**
4896
+	 * Returns the specified EE_Model_Relation, or throws an exception
4897
+	 *
4898
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4899
+	 * @throws EE_Error
4900
+	 * @return EE_Model_Relation_Base
4901
+	 */
4902
+	public function related_settings_for($relation_name)
4903
+	{
4904
+		$relatedModels = $this->relation_settings();
4905
+		if (! array_key_exists($relation_name, $relatedModels)) {
4906
+			throw new EE_Error(
4907
+				sprintf(
4908
+					__(
4909
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4910
+						'event_espresso'
4911
+					),
4912
+					$relation_name,
4913
+					$this->_get_class_name(),
4914
+					implode(', ', array_keys($relatedModels))
4915
+				)
4916
+			);
4917
+		}
4918
+		return $relatedModels[ $relation_name ];
4919
+	}
4920
+
4921
+
4922
+
4923
+	/**
4924
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4925
+	 * fields
4926
+	 *
4927
+	 * @param string $fieldName
4928
+	 * @param boolean $include_db_only_fields
4929
+	 * @throws EE_Error
4930
+	 * @return EE_Model_Field_Base
4931
+	 */
4932
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4933
+	{
4934
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4935
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4936
+			throw new EE_Error(sprintf(
4937
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4938
+				$fieldName,
4939
+				get_class($this)
4940
+			));
4941
+		}
4942
+		return $fieldSettings[ $fieldName ];
4943
+	}
4944
+
4945
+
4946
+
4947
+	/**
4948
+	 * Checks if this field exists on this model
4949
+	 *
4950
+	 * @param string $fieldName a key in the model's _field_settings array
4951
+	 * @return boolean
4952
+	 */
4953
+	public function has_field($fieldName)
4954
+	{
4955
+		$fieldSettings = $this->field_settings(true);
4956
+		if (isset($fieldSettings[ $fieldName ])) {
4957
+			return true;
4958
+		}
4959
+		return false;
4960
+	}
4961
+
4962
+
4963
+
4964
+	/**
4965
+	 * Returns whether or not this model has a relation to the specified model
4966
+	 *
4967
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4968
+	 * @return boolean
4969
+	 */
4970
+	public function has_relation($relation_name)
4971
+	{
4972
+		$relations = $this->relation_settings();
4973
+		if (isset($relations[ $relation_name ])) {
4974
+			return true;
4975
+		}
4976
+		return false;
4977
+	}
4978
+
4979
+
4980
+
4981
+	/**
4982
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4983
+	 * Eg, on EE_Answer that would be ANS_ID field object
4984
+	 *
4985
+	 * @param $field_obj
4986
+	 * @return boolean
4987
+	 */
4988
+	public function is_primary_key_field($field_obj)
4989
+	{
4990
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4991
+	}
4992
+
4993
+
4994
+
4995
+	/**
4996
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4997
+	 * Eg, on EE_Answer that would be ANS_ID field object
4998
+	 *
4999
+	 * @return EE_Model_Field_Base
5000
+	 * @throws EE_Error
5001
+	 */
5002
+	public function get_primary_key_field()
5003
+	{
5004
+		if ($this->_primary_key_field === null) {
5005
+			foreach ($this->field_settings(true) as $field_obj) {
5006
+				if ($this->is_primary_key_field($field_obj)) {
5007
+					$this->_primary_key_field = $field_obj;
5008
+					break;
5009
+				}
5010
+			}
5011
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5012
+				throw new EE_Error(sprintf(
5013
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
5014
+					get_class($this)
5015
+				));
5016
+			}
5017
+		}
5018
+		return $this->_primary_key_field;
5019
+	}
5020
+
5021
+
5022
+
5023
+	/**
5024
+	 * Returns whether or not not there is a primary key on this model.
5025
+	 * Internally does some caching.
5026
+	 *
5027
+	 * @return boolean
5028
+	 */
5029
+	public function has_primary_key_field()
5030
+	{
5031
+		if ($this->_has_primary_key_field === null) {
5032
+			try {
5033
+				$this->get_primary_key_field();
5034
+				$this->_has_primary_key_field = true;
5035
+			} catch (EE_Error $e) {
5036
+				$this->_has_primary_key_field = false;
5037
+			}
5038
+		}
5039
+		return $this->_has_primary_key_field;
5040
+	}
5041
+
5042
+
5043
+
5044
+	/**
5045
+	 * Finds the first field of type $field_class_name.
5046
+	 *
5047
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5048
+	 *                                 EE_Foreign_Key_Field, etc
5049
+	 * @return EE_Model_Field_Base or null if none is found
5050
+	 */
5051
+	public function get_a_field_of_type($field_class_name)
5052
+	{
5053
+		foreach ($this->field_settings() as $field) {
5054
+			if ($field instanceof $field_class_name) {
5055
+				return $field;
5056
+			}
5057
+		}
5058
+		return null;
5059
+	}
5060
+
5061
+
5062
+
5063
+	/**
5064
+	 * Gets a foreign key field pointing to model.
5065
+	 *
5066
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5067
+	 * @return EE_Foreign_Key_Field_Base
5068
+	 * @throws EE_Error
5069
+	 */
5070
+	public function get_foreign_key_to($model_name)
5071
+	{
5072
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5073
+			foreach ($this->field_settings() as $field) {
5074
+				if ($field instanceof EE_Foreign_Key_Field_Base
5075
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5076
+				) {
5077
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5078
+					break;
5079
+				}
5080
+			}
5081
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5082
+				throw new EE_Error(sprintf(__(
5083
+					"There is no foreign key field pointing to model %s on model %s",
5084
+					'event_espresso'
5085
+				), $model_name, get_class($this)));
5086
+			}
5087
+		}
5088
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5089
+	}
5090
+
5091
+
5092
+
5093
+	/**
5094
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5095
+	 *
5096
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5097
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5098
+	 *                            Either one works
5099
+	 * @return string
5100
+	 */
5101
+	public function get_table_for_alias($table_alias)
5102
+	{
5103
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5104
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5105
+	}
5106
+
5107
+
5108
+
5109
+	/**
5110
+	 * Returns a flat array of all field son this model, instead of organizing them
5111
+	 * by table_alias as they are in the constructor.
5112
+	 *
5113
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5114
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5115
+	 */
5116
+	public function field_settings($include_db_only_fields = false)
5117
+	{
5118
+		if ($include_db_only_fields) {
5119
+			if ($this->_cached_fields === null) {
5120
+				$this->_cached_fields = array();
5121
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5122
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5123
+						$this->_cached_fields[ $field_name ] = $field_obj;
5124
+					}
5125
+				}
5126
+			}
5127
+			return $this->_cached_fields;
5128
+		}
5129
+		if ($this->_cached_fields_non_db_only === null) {
5130
+			$this->_cached_fields_non_db_only = array();
5131
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5132
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5133
+					/** @var $field_obj EE_Model_Field_Base */
5134
+					if (! $field_obj->is_db_only_field()) {
5135
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5136
+					}
5137
+				}
5138
+			}
5139
+		}
5140
+		return $this->_cached_fields_non_db_only;
5141
+	}
5142
+
5143
+
5144
+
5145
+	/**
5146
+	 *        cycle though array of attendees and create objects out of each item
5147
+	 *
5148
+	 * @access        private
5149
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5150
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5151
+	 *                           numerically indexed)
5152
+	 * @throws EE_Error
5153
+	 */
5154
+	protected function _create_objects($rows = array())
5155
+	{
5156
+		$array_of_objects = array();
5157
+		if (empty($rows)) {
5158
+			return array();
5159
+		}
5160
+		$count_if_model_has_no_primary_key = 0;
5161
+		$has_primary_key = $this->has_primary_key_field();
5162
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5163
+		foreach ((array) $rows as $row) {
5164
+			if (empty($row)) {
5165
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5166
+				return array();
5167
+			}
5168
+			// check if we've already set this object in the results array,
5169
+			// in which case there's no need to process it further (again)
5170
+			if ($has_primary_key) {
5171
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5172
+					$row,
5173
+					$primary_key_field->get_qualified_column(),
5174
+					$primary_key_field->get_table_column()
5175
+				);
5176
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5177
+					continue;
5178
+				}
5179
+			}
5180
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5181
+			if (! $classInstance) {
5182
+				throw new EE_Error(
5183
+					sprintf(
5184
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5185
+						$this->get_this_model_name(),
5186
+						http_build_query($row)
5187
+					)
5188
+				);
5189
+			}
5190
+			// set the timezone on the instantiated objects
5191
+			$classInstance->set_timezone($this->_timezone);
5192
+			// make sure if there is any timezone setting present that we set the timezone for the object
5193
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5194
+			$array_of_objects[ $key ] = $classInstance;
5195
+			// also, for all the relations of type BelongsTo, see if we can cache
5196
+			// those related models
5197
+			// (we could do this for other relations too, but if there are conditions
5198
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5199
+			// so it requires a little more thought than just caching them immediately...)
5200
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5201
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5202
+					// check if this model's INFO is present. If so, cache it on the model
5203
+					$other_model = $relation_obj->get_other_model();
5204
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5205
+					// if we managed to make a model object from the results, cache it on the main model object
5206
+					if ($other_model_obj_maybe) {
5207
+						// set timezone on these other model objects if they are present
5208
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5209
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5210
+					}
5211
+				}
5212
+			}
5213
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5214
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5215
+			// the field in the CustomSelects object
5216
+			if ($this->_custom_selections instanceof CustomSelects) {
5217
+				$classInstance->setCustomSelectsValues(
5218
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5219
+				);
5220
+			}
5221
+		}
5222
+		return $array_of_objects;
5223
+	}
5224
+
5225
+
5226
+	/**
5227
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5228
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5229
+	 *
5230
+	 * @param array $db_results_row
5231
+	 * @return array
5232
+	 */
5233
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5234
+	{
5235
+		$results = array();
5236
+		if ($this->_custom_selections instanceof CustomSelects) {
5237
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5238
+				if (isset($db_results_row[ $alias ])) {
5239
+					$results[ $alias ] = $this->convertValueToDataType(
5240
+						$db_results_row[ $alias ],
5241
+						$this->_custom_selections->getDataTypeForAlias($alias)
5242
+					);
5243
+				}
5244
+			}
5245
+		}
5246
+		return $results;
5247
+	}
5248
+
5249
+
5250
+	/**
5251
+	 * This will set the value for the given alias
5252
+	 * @param string $value
5253
+	 * @param string $datatype (one of %d, %s, %f)
5254
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5255
+	 */
5256
+	protected function convertValueToDataType($value, $datatype)
5257
+	{
5258
+		switch ($datatype) {
5259
+			case '%f':
5260
+				return (float) $value;
5261
+			case '%d':
5262
+				return (int) $value;
5263
+			default:
5264
+				return (string) $value;
5265
+		}
5266
+	}
5267
+
5268
+
5269
+	/**
5270
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5271
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5272
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5273
+	 * object (as set in the model_field!).
5274
+	 *
5275
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5276
+	 */
5277
+	public function create_default_object()
5278
+	{
5279
+		$this_model_fields_and_values = array();
5280
+		// setup the row using default values;
5281
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5282
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5283
+		}
5284
+		$className = $this->_get_class_name();
5285
+		$classInstance = EE_Registry::instance()
5286
+									->load_class($className, array($this_model_fields_and_values), false, false);
5287
+		return $classInstance;
5288
+	}
5289
+
5290
+
5291
+
5292
+	/**
5293
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5294
+	 *                             or an stdClass where each property is the name of a column,
5295
+	 * @return EE_Base_Class
5296
+	 * @throws EE_Error
5297
+	 */
5298
+	public function instantiate_class_from_array_or_object($cols_n_values)
5299
+	{
5300
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5301
+			$cols_n_values = get_object_vars($cols_n_values);
5302
+		}
5303
+		$primary_key = null;
5304
+		// make sure the array only has keys that are fields/columns on this model
5305
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5306
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5307
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5308
+		}
5309
+		$className = $this->_get_class_name();
5310
+		// check we actually found results that we can use to build our model object
5311
+		// if not, return null
5312
+		if ($this->has_primary_key_field()) {
5313
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5314
+				return null;
5315
+			}
5316
+		} elseif ($this->unique_indexes()) {
5317
+			$first_column = reset($this_model_fields_n_values);
5318
+			if (empty($first_column)) {
5319
+				return null;
5320
+			}
5321
+		}
5322
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5323
+		if ($primary_key) {
5324
+			$classInstance = $this->get_from_entity_map($primary_key);
5325
+			if (! $classInstance) {
5326
+				$classInstance = EE_Registry::instance()
5327
+											->load_class(
5328
+												$className,
5329
+												array($this_model_fields_n_values, $this->_timezone),
5330
+												true,
5331
+												false
5332
+											);
5333
+				// add this new object to the entity map
5334
+				$classInstance = $this->add_to_entity_map($classInstance);
5335
+			}
5336
+		} else {
5337
+			$classInstance = EE_Registry::instance()
5338
+										->load_class(
5339
+											$className,
5340
+											array($this_model_fields_n_values, $this->_timezone),
5341
+											true,
5342
+											false
5343
+										);
5344
+		}
5345
+		return $classInstance;
5346
+	}
5347
+
5348
+
5349
+
5350
+	/**
5351
+	 * Gets the model object from the  entity map if it exists
5352
+	 *
5353
+	 * @param int|string $id the ID of the model object
5354
+	 * @return EE_Base_Class
5355
+	 */
5356
+	public function get_from_entity_map($id)
5357
+	{
5358
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5359
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5360
+	}
5361
+
5362
+
5363
+
5364
+	/**
5365
+	 * add_to_entity_map
5366
+	 * Adds the object to the model's entity mappings
5367
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5368
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5369
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5370
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5371
+	 *        then this method should be called immediately after the update query
5372
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5373
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5374
+	 *
5375
+	 * @param    EE_Base_Class $object
5376
+	 * @throws EE_Error
5377
+	 * @return \EE_Base_Class
5378
+	 */
5379
+	public function add_to_entity_map(EE_Base_Class $object)
5380
+	{
5381
+		$className = $this->_get_class_name();
5382
+		if (! $object instanceof $className) {
5383
+			throw new EE_Error(sprintf(
5384
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5385
+				is_object($object) ? get_class($object) : $object,
5386
+				$className
5387
+			));
5388
+		}
5389
+		/** @var $object EE_Base_Class */
5390
+		if (! $object->ID()) {
5391
+			throw new EE_Error(sprintf(__(
5392
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5393
+				"event_espresso"
5394
+			), get_class($this)));
5395
+		}
5396
+		// double check it's not already there
5397
+		$classInstance = $this->get_from_entity_map($object->ID());
5398
+		if ($classInstance) {
5399
+			return $classInstance;
5400
+		}
5401
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5402
+		return $object;
5403
+	}
5404
+
5405
+
5406
+
5407
+	/**
5408
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5409
+	 * if no identifier is provided, then the entire entity map is emptied
5410
+	 *
5411
+	 * @param int|string $id the ID of the model object
5412
+	 * @return boolean
5413
+	 */
5414
+	public function clear_entity_map($id = null)
5415
+	{
5416
+		if (empty($id)) {
5417
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5418
+			return true;
5419
+		}
5420
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5421
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5422
+			return true;
5423
+		}
5424
+		return false;
5425
+	}
5426
+
5427
+
5428
+
5429
+	/**
5430
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5431
+	 * Given an array where keys are column (or column alias) names and values,
5432
+	 * returns an array of their corresponding field names and database values
5433
+	 *
5434
+	 * @param array $cols_n_values
5435
+	 * @return array
5436
+	 */
5437
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5438
+	{
5439
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5440
+	}
5441
+
5442
+
5443
+
5444
+	/**
5445
+	 * _deduce_fields_n_values_from_cols_n_values
5446
+	 * Given an array where keys are column (or column alias) names and values,
5447
+	 * returns an array of their corresponding field names and database values
5448
+	 *
5449
+	 * @param string $cols_n_values
5450
+	 * @return array
5451
+	 */
5452
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5453
+	{
5454
+		$this_model_fields_n_values = array();
5455
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5456
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5457
+				$cols_n_values,
5458
+				$table_obj->get_fully_qualified_pk_column(),
5459
+				$table_obj->get_pk_column()
5460
+			);
5461
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5462
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5463
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5464
+					if (! $field_obj->is_db_only_field()) {
5465
+						// prepare field as if its coming from db
5466
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5467
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5468
+					}
5469
+				}
5470
+			} else {
5471
+				// the table's rows existed. Use their values
5472
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5473
+					if (! $field_obj->is_db_only_field()) {
5474
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5475
+							$cols_n_values,
5476
+							$field_obj->get_qualified_column(),
5477
+							$field_obj->get_table_column()
5478
+						);
5479
+					}
5480
+				}
5481
+			}
5482
+		}
5483
+		return $this_model_fields_n_values;
5484
+	}
5485
+
5486
+
5487
+
5488
+	/**
5489
+	 * @param $cols_n_values
5490
+	 * @param $qualified_column
5491
+	 * @param $regular_column
5492
+	 * @return null
5493
+	 */
5494
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5495
+	{
5496
+		$value = null;
5497
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5498
+		// does the field on the model relate to this column retrieved from the db?
5499
+		// or is it a db-only field? (not relating to the model)
5500
+		if (isset($cols_n_values[ $qualified_column ])) {
5501
+			$value = $cols_n_values[ $qualified_column ];
5502
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5503
+			$value = $cols_n_values[ $regular_column ];
5504
+		}
5505
+		return $value;
5506
+	}
5507
+
5508
+
5509
+
5510
+	/**
5511
+	 * refresh_entity_map_from_db
5512
+	 * Makes sure the model object in the entity map at $id assumes the values
5513
+	 * of the database (opposite of EE_base_Class::save())
5514
+	 *
5515
+	 * @param int|string $id
5516
+	 * @return EE_Base_Class
5517
+	 * @throws EE_Error
5518
+	 */
5519
+	public function refresh_entity_map_from_db($id)
5520
+	{
5521
+		$obj_in_map = $this->get_from_entity_map($id);
5522
+		if ($obj_in_map) {
5523
+			$wpdb_results = $this->_get_all_wpdb_results(
5524
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5525
+			);
5526
+			if ($wpdb_results && is_array($wpdb_results)) {
5527
+				$one_row = reset($wpdb_results);
5528
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5529
+					$obj_in_map->set_from_db($field_name, $db_value);
5530
+				}
5531
+				// clear the cache of related model objects
5532
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5533
+					$obj_in_map->clear_cache($relation_name, null, true);
5534
+				}
5535
+			}
5536
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5537
+			return $obj_in_map;
5538
+		}
5539
+		return $this->get_one_by_ID($id);
5540
+	}
5541
+
5542
+
5543
+
5544
+	/**
5545
+	 * refresh_entity_map_with
5546
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5547
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5548
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5549
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5550
+	 *
5551
+	 * @param int|string    $id
5552
+	 * @param EE_Base_Class $replacing_model_obj
5553
+	 * @return \EE_Base_Class
5554
+	 * @throws EE_Error
5555
+	 */
5556
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5557
+	{
5558
+		$obj_in_map = $this->get_from_entity_map($id);
5559
+		if ($obj_in_map) {
5560
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5561
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5562
+					$obj_in_map->set($field_name, $value);
5563
+				}
5564
+				// make the model object in the entity map's cache match the $replacing_model_obj
5565
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5566
+					$obj_in_map->clear_cache($relation_name, null, true);
5567
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5568
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5569
+					}
5570
+				}
5571
+			}
5572
+			return $obj_in_map;
5573
+		}
5574
+		$this->add_to_entity_map($replacing_model_obj);
5575
+		return $replacing_model_obj;
5576
+	}
5577
+
5578
+
5579
+
5580
+	/**
5581
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5582
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5583
+	 * require_once($this->_getClassName().".class.php");
5584
+	 *
5585
+	 * @return string
5586
+	 */
5587
+	private function _get_class_name()
5588
+	{
5589
+		return "EE_" . $this->get_this_model_name();
5590
+	}
5591
+
5592
+
5593
+
5594
+	/**
5595
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5596
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5597
+	 * it would be 'Events'.
5598
+	 *
5599
+	 * @param int $quantity
5600
+	 * @return string
5601
+	 */
5602
+	public function item_name($quantity = 1)
5603
+	{
5604
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5605
+	}
5606
+
5607
+
5608
+
5609
+	/**
5610
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5611
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5612
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5613
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5614
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5615
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5616
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5617
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5618
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5619
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5620
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5621
+	 *        return $previousReturnValue.$returnString;
5622
+	 * }
5623
+	 * require('EEM_Answer.model.php');
5624
+	 * $answer=EEM_Answer::instance();
5625
+	 * echo $answer->my_callback('monkeys',100);
5626
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5627
+	 *
5628
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5629
+	 * @param array  $args       array of original arguments passed to the function
5630
+	 * @throws EE_Error
5631
+	 * @return mixed whatever the plugin which calls add_filter decides
5632
+	 */
5633
+	public function __call($methodName, $args)
5634
+	{
5635
+		$className = get_class($this);
5636
+		$tagName = "FHEE__{$className}__{$methodName}";
5637
+		if (! has_filter($tagName)) {
5638
+			throw new EE_Error(
5639
+				sprintf(
5640
+					__(
5641
+						'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 );',
5642
+						'event_espresso'
5643
+					),
5644
+					$methodName,
5645
+					$className,
5646
+					$tagName,
5647
+					'<br />'
5648
+				)
5649
+			);
5650
+		}
5651
+		return apply_filters($tagName, null, $this, $args);
5652
+	}
5653
+
5654
+
5655
+
5656
+	/**
5657
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5658
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5659
+	 *
5660
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5661
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5662
+	 *                                                       the object's class name
5663
+	 *                                                       or object's ID
5664
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5665
+	 *                                                       exists in the database. If it does not, we add it
5666
+	 * @throws EE_Error
5667
+	 * @return EE_Base_Class
5668
+	 */
5669
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5670
+	{
5671
+		$className = $this->_get_class_name();
5672
+		if ($base_class_obj_or_id instanceof $className) {
5673
+			$model_object = $base_class_obj_or_id;
5674
+		} else {
5675
+			$primary_key_field = $this->get_primary_key_field();
5676
+			if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5677
+				&& (
5678
+					is_int($base_class_obj_or_id)
5679
+					|| is_string($base_class_obj_or_id)
5680
+				)
5681
+			) {
5682
+				// assume it's an ID.
5683
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5684
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5685
+			} elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5686
+				&& is_string($base_class_obj_or_id)
5687
+			) {
5688
+				// assume its a string representation of the object
5689
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5690
+			} else {
5691
+				throw new EE_Error(
5692
+					sprintf(
5693
+						__(
5694
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5695
+							'event_espresso'
5696
+						),
5697
+						$base_class_obj_or_id,
5698
+						$this->_get_class_name(),
5699
+						print_r($base_class_obj_or_id, true)
5700
+					)
5701
+				);
5702
+			}
5703
+		}
5704
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5705
+			$model_object->save();
5706
+		}
5707
+		return $model_object;
5708
+	}
5709
+
5710
+
5711
+
5712
+	/**
5713
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5714
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5715
+	 * returns it ID.
5716
+	 *
5717
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5718
+	 * @return int|string depending on the type of this model object's ID
5719
+	 * @throws EE_Error
5720
+	 */
5721
+	public function ensure_is_ID($base_class_obj_or_id)
5722
+	{
5723
+		$className = $this->_get_class_name();
5724
+		if ($base_class_obj_or_id instanceof $className) {
5725
+			/** @var $base_class_obj_or_id EE_Base_Class */
5726
+			$id = $base_class_obj_or_id->ID();
5727
+		} elseif (is_int($base_class_obj_or_id)) {
5728
+			// assume it's an ID
5729
+			$id = $base_class_obj_or_id;
5730
+		} elseif (is_string($base_class_obj_or_id)) {
5731
+			// assume its a string representation of the object
5732
+			$id = $base_class_obj_or_id;
5733
+		} else {
5734
+			throw new EE_Error(sprintf(
5735
+				__(
5736
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5737
+					'event_espresso'
5738
+				),
5739
+				$base_class_obj_or_id,
5740
+				$this->_get_class_name(),
5741
+				print_r($base_class_obj_or_id, true)
5742
+			));
5743
+		}
5744
+		return $id;
5745
+	}
5746
+
5747
+
5748
+
5749
+	/**
5750
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5751
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5752
+	 * been sanitized and converted into the appropriate domain.
5753
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5754
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5755
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5756
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5757
+	 * $EVT = EEM_Event::instance(); $old_setting =
5758
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5759
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5760
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5761
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5762
+	 *
5763
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5764
+	 * @return void
5765
+	 */
5766
+	public function assume_values_already_prepared_by_model_object(
5767
+		$values_already_prepared = self::not_prepared_by_model_object
5768
+	) {
5769
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5770
+	}
5771
+
5772
+
5773
+
5774
+	/**
5775
+	 * Read comments for assume_values_already_prepared_by_model_object()
5776
+	 *
5777
+	 * @return int
5778
+	 */
5779
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5780
+	{
5781
+		return $this->_values_already_prepared_by_model_object;
5782
+	}
5783
+
5784
+
5785
+
5786
+	/**
5787
+	 * Gets all the indexes on this model
5788
+	 *
5789
+	 * @return EE_Index[]
5790
+	 */
5791
+	public function indexes()
5792
+	{
5793
+		return $this->_indexes;
5794
+	}
5795
+
5796
+
5797
+
5798
+	/**
5799
+	 * Gets all the Unique Indexes on this model
5800
+	 *
5801
+	 * @return EE_Unique_Index[]
5802
+	 */
5803
+	public function unique_indexes()
5804
+	{
5805
+		$unique_indexes = array();
5806
+		foreach ($this->_indexes as $name => $index) {
5807
+			if ($index instanceof EE_Unique_Index) {
5808
+				$unique_indexes [ $name ] = $index;
5809
+			}
5810
+		}
5811
+		return $unique_indexes;
5812
+	}
5813
+
5814
+
5815
+
5816
+	/**
5817
+	 * Gets all the fields which, when combined, make the primary key.
5818
+	 * This is usually just an array with 1 element (the primary key), but in cases
5819
+	 * where there is no primary key, it's a combination of fields as defined
5820
+	 * on a primary index
5821
+	 *
5822
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5823
+	 * @throws EE_Error
5824
+	 */
5825
+	public function get_combined_primary_key_fields()
5826
+	{
5827
+		foreach ($this->indexes() as $index) {
5828
+			if ($index instanceof EE_Primary_Key_Index) {
5829
+				return $index->fields();
5830
+			}
5831
+		}
5832
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5833
+	}
5834
+
5835
+
5836
+
5837
+	/**
5838
+	 * Used to build a primary key string (when the model has no primary key),
5839
+	 * which can be used a unique string to identify this model object.
5840
+	 *
5841
+	 * @param array $cols_n_values keys are field names, values are their values
5842
+	 * @return string
5843
+	 * @throws EE_Error
5844
+	 */
5845
+	public function get_index_primary_key_string($cols_n_values)
5846
+	{
5847
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5848
+			$cols_n_values,
5849
+			$this->get_combined_primary_key_fields()
5850
+		);
5851
+		return http_build_query($cols_n_values_for_primary_key_index);
5852
+	}
5853
+
5854
+
5855
+
5856
+	/**
5857
+	 * Gets the field values from the primary key string
5858
+	 *
5859
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5860
+	 * @param string $index_primary_key_string
5861
+	 * @return null|array
5862
+	 * @throws EE_Error
5863
+	 */
5864
+	public function parse_index_primary_key_string($index_primary_key_string)
5865
+	{
5866
+		$key_fields = $this->get_combined_primary_key_fields();
5867
+		// check all of them are in the $id
5868
+		$key_vals_in_combined_pk = array();
5869
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5870
+		foreach ($key_fields as $key_field_name => $field_obj) {
5871
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5872
+				return null;
5873
+			}
5874
+		}
5875
+		return $key_vals_in_combined_pk;
5876
+	}
5877
+
5878
+
5879
+
5880
+	/**
5881
+	 * verifies that an array of key-value pairs for model fields has a key
5882
+	 * for each field comprising the primary key index
5883
+	 *
5884
+	 * @param array $key_vals
5885
+	 * @return boolean
5886
+	 * @throws EE_Error
5887
+	 */
5888
+	public function has_all_combined_primary_key_fields($key_vals)
5889
+	{
5890
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5891
+		foreach ($keys_it_should_have as $key) {
5892
+			if (! isset($key_vals[ $key ])) {
5893
+				return false;
5894
+			}
5895
+		}
5896
+		return true;
5897
+	}
5898
+
5899
+
5900
+
5901
+	/**
5902
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5903
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5904
+	 *
5905
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5906
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5907
+	 * @throws EE_Error
5908
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5909
+	 *                                                              indexed)
5910
+	 */
5911
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5912
+	{
5913
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5914
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5915
+		} elseif (is_array($model_object_or_attributes_array)) {
5916
+			$attributes_array = $model_object_or_attributes_array;
5917
+		} else {
5918
+			throw new EE_Error(sprintf(__(
5919
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5920
+				"event_espresso"
5921
+			), $model_object_or_attributes_array));
5922
+		}
5923
+		// even copies obviously won't have the same ID, so remove the primary key
5924
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5925
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5926
+			unset($attributes_array[ $this->primary_key_name() ]);
5927
+		}
5928
+		if (isset($query_params[0])) {
5929
+			$query_params[0] = array_merge($attributes_array, $query_params);
5930
+		} else {
5931
+			$query_params[0] = $attributes_array;
5932
+		}
5933
+		return $this->get_all($query_params);
5934
+	}
5935
+
5936
+
5937
+
5938
+	/**
5939
+	 * Gets the first copy we find. See get_all_copies for more details
5940
+	 *
5941
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5942
+	 * @param array $query_params
5943
+	 * @return EE_Base_Class
5944
+	 * @throws EE_Error
5945
+	 */
5946
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5947
+	{
5948
+		if (! is_array($query_params)) {
5949
+			EE_Error::doing_it_wrong(
5950
+				'EEM_Base::get_one_copy',
5951
+				sprintf(
5952
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5953
+					gettype($query_params)
5954
+				),
5955
+				'4.6.0'
5956
+			);
5957
+			$query_params = array();
5958
+		}
5959
+		$query_params['limit'] = 1;
5960
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5961
+		if (is_array($copies)) {
5962
+			return array_shift($copies);
5963
+		}
5964
+		return null;
5965
+	}
5966
+
5967
+
5968
+
5969
+	/**
5970
+	 * Updates the item with the specified id. Ignores default query parameters because
5971
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5972
+	 *
5973
+	 * @param array      $fields_n_values keys are field names, values are their new values
5974
+	 * @param int|string $id              the value of the primary key to update
5975
+	 * @return int number of rows updated
5976
+	 * @throws EE_Error
5977
+	 */
5978
+	public function update_by_ID($fields_n_values, $id)
5979
+	{
5980
+		$query_params = array(
5981
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5982
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5983
+		);
5984
+		return $this->update($fields_n_values, $query_params);
5985
+	}
5986
+
5987
+
5988
+
5989
+	/**
5990
+	 * Changes an operator which was supplied to the models into one usable in SQL
5991
+	 *
5992
+	 * @param string $operator_supplied
5993
+	 * @return string an operator which can be used in SQL
5994
+	 * @throws EE_Error
5995
+	 */
5996
+	private function _prepare_operator_for_sql($operator_supplied)
5997
+	{
5998
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5999
+			: null;
6000
+		if ($sql_operator) {
6001
+			return $sql_operator;
6002
+		}
6003
+		throw new EE_Error(
6004
+			sprintf(
6005
+				__(
6006
+					"The operator '%s' is not in the list of valid operators: %s",
6007
+					"event_espresso"
6008
+				),
6009
+				$operator_supplied,
6010
+				implode(",", array_keys($this->_valid_operators))
6011
+			)
6012
+		);
6013
+	}
6014
+
6015
+
6016
+
6017
+	/**
6018
+	 * Gets the valid operators
6019
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6020
+	 */
6021
+	public function valid_operators()
6022
+	{
6023
+		return $this->_valid_operators;
6024
+	}
6025
+
6026
+
6027
+
6028
+	/**
6029
+	 * Gets the between-style operators (take 2 arguments).
6030
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6031
+	 */
6032
+	public function valid_between_style_operators()
6033
+	{
6034
+		return array_intersect(
6035
+			$this->valid_operators(),
6036
+			$this->_between_style_operators
6037
+		);
6038
+	}
6039
+
6040
+	/**
6041
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6042
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6043
+	 */
6044
+	public function valid_like_style_operators()
6045
+	{
6046
+		return array_intersect(
6047
+			$this->valid_operators(),
6048
+			$this->_like_style_operators
6049
+		);
6050
+	}
6051
+
6052
+	/**
6053
+	 * Gets the "in"-style operators
6054
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6055
+	 */
6056
+	public function valid_in_style_operators()
6057
+	{
6058
+		return array_intersect(
6059
+			$this->valid_operators(),
6060
+			$this->_in_style_operators
6061
+		);
6062
+	}
6063
+
6064
+	/**
6065
+	 * Gets the "null"-style operators (accept no arguments)
6066
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6067
+	 */
6068
+	public function valid_null_style_operators()
6069
+	{
6070
+		return array_intersect(
6071
+			$this->valid_operators(),
6072
+			$this->_null_style_operators
6073
+		);
6074
+	}
6075
+
6076
+	/**
6077
+	 * Gets an array where keys are the primary keys and values are their 'names'
6078
+	 * (as determined by the model object's name() function, which is often overridden)
6079
+	 *
6080
+	 * @param array $query_params like get_all's
6081
+	 * @return string[]
6082
+	 * @throws EE_Error
6083
+	 */
6084
+	public function get_all_names($query_params = array())
6085
+	{
6086
+		$objs = $this->get_all($query_params);
6087
+		$names = array();
6088
+		foreach ($objs as $obj) {
6089
+			$names[ $obj->ID() ] = $obj->name();
6090
+		}
6091
+		return $names;
6092
+	}
6093
+
6094
+
6095
+
6096
+	/**
6097
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6098
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6099
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6100
+	 * array_keys() on $model_objects.
6101
+	 *
6102
+	 * @param \EE_Base_Class[] $model_objects
6103
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6104
+	 *                                               in the returned array
6105
+	 * @return array
6106
+	 * @throws EE_Error
6107
+	 */
6108
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6109
+	{
6110
+		if (! $this->has_primary_key_field()) {
6111
+			if (WP_DEBUG) {
6112
+				EE_Error::add_error(
6113
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6114
+					__FILE__,
6115
+					__FUNCTION__,
6116
+					__LINE__
6117
+				);
6118
+			}
6119
+		}
6120
+		$IDs = array();
6121
+		foreach ($model_objects as $model_object) {
6122
+			$id = $model_object->ID();
6123
+			if (! $id) {
6124
+				if ($filter_out_empty_ids) {
6125
+					continue;
6126
+				}
6127
+				if (WP_DEBUG) {
6128
+					EE_Error::add_error(
6129
+						__(
6130
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6131
+							'event_espresso'
6132
+						),
6133
+						__FILE__,
6134
+						__FUNCTION__,
6135
+						__LINE__
6136
+					);
6137
+				}
6138
+			}
6139
+			$IDs[] = $id;
6140
+		}
6141
+		return $IDs;
6142
+	}
6143
+
6144
+
6145
+
6146
+	/**
6147
+	 * Returns the string used in capabilities relating to this model. If there
6148
+	 * are no capabilities that relate to this model returns false
6149
+	 *
6150
+	 * @return string|false
6151
+	 */
6152
+	public function cap_slug()
6153
+	{
6154
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6155
+	}
6156
+
6157
+
6158
+
6159
+	/**
6160
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6161
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6162
+	 * only returns the cap restrictions array in that context (ie, the array
6163
+	 * at that key)
6164
+	 *
6165
+	 * @param string $context
6166
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6167
+	 * @throws EE_Error
6168
+	 */
6169
+	public function cap_restrictions($context = EEM_Base::caps_read)
6170
+	{
6171
+		EEM_Base::verify_is_valid_cap_context($context);
6172
+		// check if we ought to run the restriction generator first
6173
+		if (isset($this->_cap_restriction_generators[ $context ])
6174
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6175
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6176
+		) {
6177
+			$this->_cap_restrictions[ $context ] = array_merge(
6178
+				$this->_cap_restrictions[ $context ],
6179
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6180
+			);
6181
+		}
6182
+		// and make sure we've finalized the construction of each restriction
6183
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6184
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6185
+				$where_conditions_obj->_finalize_construct($this);
6186
+			}
6187
+		}
6188
+		return $this->_cap_restrictions[ $context ];
6189
+	}
6190
+
6191
+
6192
+
6193
+	/**
6194
+	 * Indicating whether or not this model thinks its a wp core model
6195
+	 *
6196
+	 * @return boolean
6197
+	 */
6198
+	public function is_wp_core_model()
6199
+	{
6200
+		return $this->_wp_core_model;
6201
+	}
6202
+
6203
+
6204
+
6205
+	/**
6206
+	 * Gets all the caps that are missing which impose a restriction on
6207
+	 * queries made in this context
6208
+	 *
6209
+	 * @param string $context one of EEM_Base::caps_ constants
6210
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6211
+	 * @throws EE_Error
6212
+	 */
6213
+	public function caps_missing($context = EEM_Base::caps_read)
6214
+	{
6215
+		$missing_caps = array();
6216
+		$cap_restrictions = $this->cap_restrictions($context);
6217
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6218
+			if (! EE_Capabilities::instance()
6219
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6220
+			) {
6221
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6222
+			}
6223
+		}
6224
+		return $missing_caps;
6225
+	}
6226
+
6227
+
6228
+
6229
+	/**
6230
+	 * Gets the mapping from capability contexts to action strings used in capability names
6231
+	 *
6232
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6233
+	 * one of 'read', 'edit', or 'delete'
6234
+	 */
6235
+	public function cap_contexts_to_cap_action_map()
6236
+	{
6237
+		return apply_filters(
6238
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6239
+			$this->_cap_contexts_to_cap_action_map,
6240
+			$this
6241
+		);
6242
+	}
6243
+
6244
+
6245
+
6246
+	/**
6247
+	 * Gets the action string for the specified capability context
6248
+	 *
6249
+	 * @param string $context
6250
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6251
+	 * @throws EE_Error
6252
+	 */
6253
+	public function cap_action_for_context($context)
6254
+	{
6255
+		$mapping = $this->cap_contexts_to_cap_action_map();
6256
+		if (isset($mapping[ $context ])) {
6257
+			return $mapping[ $context ];
6258
+		}
6259
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6260
+			return $action;
6261
+		}
6262
+		throw new EE_Error(
6263
+			sprintf(
6264
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6265
+				$context,
6266
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6267
+			)
6268
+		);
6269
+	}
6270
+
6271
+
6272
+
6273
+	/**
6274
+	 * Returns all the capability contexts which are valid when querying models
6275
+	 *
6276
+	 * @return array
6277
+	 */
6278
+	public static function valid_cap_contexts()
6279
+	{
6280
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6281
+			self::caps_read,
6282
+			self::caps_read_admin,
6283
+			self::caps_edit,
6284
+			self::caps_delete,
6285
+		));
6286
+	}
6287
+
6288
+
6289
+
6290
+	/**
6291
+	 * Returns all valid options for 'default_where_conditions'
6292
+	 *
6293
+	 * @return array
6294
+	 */
6295
+	public static function valid_default_where_conditions()
6296
+	{
6297
+		return array(
6298
+			EEM_Base::default_where_conditions_all,
6299
+			EEM_Base::default_where_conditions_this_only,
6300
+			EEM_Base::default_where_conditions_others_only,
6301
+			EEM_Base::default_where_conditions_minimum_all,
6302
+			EEM_Base::default_where_conditions_minimum_others,
6303
+			EEM_Base::default_where_conditions_none
6304
+		);
6305
+	}
6306
+
6307
+	// public static function default_where_conditions_full
6308
+	/**
6309
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6310
+	 *
6311
+	 * @param string $context
6312
+	 * @return bool
6313
+	 * @throws EE_Error
6314
+	 */
6315
+	public static function verify_is_valid_cap_context($context)
6316
+	{
6317
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6318
+		if (in_array($context, $valid_cap_contexts)) {
6319
+			return true;
6320
+		}
6321
+		throw new EE_Error(
6322
+			sprintf(
6323
+				__(
6324
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6325
+					'event_espresso'
6326
+				),
6327
+				$context,
6328
+				'EEM_Base',
6329
+				implode(',', $valid_cap_contexts)
6330
+			)
6331
+		);
6332
+	}
6333
+
6334
+
6335
+
6336
+	/**
6337
+	 * Clears all the models field caches. This is only useful when a sub-class
6338
+	 * might have added a field or something and these caches might be invalidated
6339
+	 */
6340
+	protected function _invalidate_field_caches()
6341
+	{
6342
+		$this->_cache_foreign_key_to_fields = array();
6343
+		$this->_cached_fields = null;
6344
+		$this->_cached_fields_non_db_only = null;
6345
+	}
6346
+
6347
+
6348
+
6349
+	/**
6350
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6351
+	 * (eg "and", "or", "not").
6352
+	 *
6353
+	 * @return array
6354
+	 */
6355
+	public function logic_query_param_keys()
6356
+	{
6357
+		return $this->_logic_query_param_keys;
6358
+	}
6359
+
6360
+
6361
+
6362
+	/**
6363
+	 * Determines whether or not the where query param array key is for a logic query param.
6364
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6365
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6366
+	 *
6367
+	 * @param $query_param_key
6368
+	 * @return bool
6369
+	 */
6370
+	public function is_logic_query_param_key($query_param_key)
6371
+	{
6372
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6373
+			if ($query_param_key === $logic_query_param_key
6374
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6375
+			) {
6376
+				return true;
6377
+			}
6378
+		}
6379
+		return false;
6380
+	}
6381 6381
 }
Please login to merge, or discard this patch.
Spacing   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
     protected function __construct($timezone = null)
516 516
     {
517 517
         // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
518
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
519 519
             throw new EE_Error(
520 520
                 sprintf(
521 521
                     __(
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
          *
539 539
          * @var EE_Table_Base[] $_tables
540 540
          */
541
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
541
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
542 542
         foreach ($this->_tables as $table_alias => $table_obj) {
543 543
             /** @var $table_obj EE_Table_Base */
544 544
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -553,10 +553,10 @@  discard block
 block discarded – undo
553 553
          *
554 554
          * @param EE_Model_Field_Base[] $_fields
555 555
          */
556
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
556
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
557 557
         $this->_invalidate_field_caches();
558 558
         foreach ($this->_fields as $table_alias => $fields_for_table) {
559
-            if (! array_key_exists($table_alias, $this->_tables)) {
559
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
560 560
                 throw new EE_Error(sprintf(__(
561 561
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
562 562
                     'event_espresso'
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
          * @param EE_Model_Relation_Base[] $_model_relations
588 588
          */
589 589
         $this->_model_relations = (array) apply_filters(
590
-            'FHEE__' . get_class($this) . '__construct__model_relations',
590
+            'FHEE__'.get_class($this).'__construct__model_relations',
591 591
             $this->_model_relations
592 592
         );
593 593
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -600,12 +600,12 @@  discard block
 block discarded – undo
600 600
         }
601 601
         $this->set_timezone($timezone);
602 602
         // finalize default where condition strategy, or set default
603
-        if (! $this->_default_where_conditions_strategy) {
603
+        if ( ! $this->_default_where_conditions_strategy) {
604 604
             // nothing was set during child constructor, so set default
605 605
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
606 606
         }
607 607
         $this->_default_where_conditions_strategy->_finalize_construct($this);
608
-        if (! $this->_minimum_where_conditions_strategy) {
608
+        if ( ! $this->_minimum_where_conditions_strategy) {
609 609
             // nothing was set during child constructor, so set default
610 610
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
611 611
         }
@@ -618,8 +618,8 @@  discard block
 block discarded – undo
618 618
         // initialize the standard cap restriction generators if none were specified by the child constructor
619 619
         if ($this->_cap_restriction_generators !== false) {
620 620
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
621
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
622
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
621
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
622
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
623 623
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
624 624
                         new EE_Restriction_Generator_Protected(),
625 625
                         $cap_context,
@@ -631,10 +631,10 @@  discard block
 block discarded – undo
631 631
         // if there are cap restriction generators, use them to make the default cap restrictions
632 632
         if ($this->_cap_restriction_generators !== false) {
633 633
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
634
-                if (! $generator_object) {
634
+                if ( ! $generator_object) {
635 635
                     continue;
636 636
                 }
637
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
637
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
638 638
                     throw new EE_Error(
639 639
                         sprintf(
640 640
                             __(
@@ -647,12 +647,12 @@  discard block
 block discarded – undo
647 647
                     );
648 648
                 }
649 649
                 $action = $this->cap_action_for_context($context);
650
-                if (! $generator_object->construction_finalized()) {
650
+                if ( ! $generator_object->construction_finalized()) {
651 651
                     $generator_object->_construct_finalize($this, $action);
652 652
                 }
653 653
             }
654 654
         }
655
-        do_action('AHEE__' . get_class($this) . '__construct__end');
655
+        do_action('AHEE__'.get_class($this).'__construct__end');
656 656
     }
657 657
 
658 658
 
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
     public static function instance($timezone = null)
700 700
     {
701 701
         // check if instance of Espresso_model already exists
702
-        if (! static::$_instance instanceof static) {
702
+        if ( ! static::$_instance instanceof static) {
703 703
             // instantiate Espresso_model
704 704
             static::$_instance = new static(
705 705
                 $timezone,
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
             foreach ($r->getDefaultProperties() as $property => $value) {
739 739
                 // don't set instance to null like it was originally,
740 740
                 // but it's static anyways, and we're ignoring static properties (for now at least)
741
-                if (! isset($static_properties[ $property ])) {
741
+                if ( ! isset($static_properties[$property])) {
742 742
                     static::$_instance->{$property} = $value;
743 743
                 }
744 744
             }
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
      */
763 763
     private static function getLoader()
764 764
     {
765
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
765
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
766 766
             EEM_Base::$loader = LoaderFactory::getLoader();
767 767
         }
768 768
         return EEM_Base::$loader;
@@ -782,7 +782,7 @@  discard block
 block discarded – undo
782 782
      */
783 783
     public function status_array($translated = false)
784 784
     {
785
-        if (! array_key_exists('Status', $this->_model_relations)) {
785
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
786 786
             return array();
787 787
         }
788 788
         $model_name = $this->get_this_model_name();
@@ -790,7 +790,7 @@  discard block
 block discarded – undo
790 790
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
791 791
         $status_array = array();
792 792
         foreach ($stati as $status) {
793
-            $status_array[ $status->ID() ] = $status->get('STS_code');
793
+            $status_array[$status->ID()] = $status->get('STS_code');
794 794
         }
795 795
         return $translated
796 796
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -967,7 +967,7 @@  discard block
 block discarded – undo
967 967
     {
968 968
         $wp_user_field_name = $this->wp_user_field_name();
969 969
         if ($wp_user_field_name) {
970
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
970
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
971 971
         }
972 972
         return $query_params;
973 973
     }
@@ -985,17 +985,17 @@  discard block
 block discarded – undo
985 985
     public function wp_user_field_name()
986 986
     {
987 987
         try {
988
-            if (! empty($this->_model_chain_to_wp_user)) {
988
+            if ( ! empty($this->_model_chain_to_wp_user)) {
989 989
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
990 990
                 $last_model_name = end($models_to_follow_to_wp_users);
991 991
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
992
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
992
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
993 993
             } else {
994 994
                 $model_with_fk_to_wp_users = $this;
995 995
                 $model_chain_to_wp_user = '';
996 996
             }
997 997
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
998
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
998
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
999 999
         } catch (EE_Error $e) {
1000 1000
             return false;
1001 1001
         }
@@ -1072,11 +1072,11 @@  discard block
 block discarded – undo
1072 1072
         if ($this->_custom_selections instanceof CustomSelects) {
1073 1073
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1074 1074
             $select_expressions .= $select_expressions
1075
-                ? ', ' . $custom_expressions
1075
+                ? ', '.$custom_expressions
1076 1076
                 : $custom_expressions;
1077 1077
         }
1078 1078
 
1079
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1079
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1080 1080
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1081 1081
     }
1082 1082
 
@@ -1093,7 +1093,7 @@  discard block
 block discarded – undo
1093 1093
      */
1094 1094
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1095 1095
     {
1096
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1096
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1097 1097
             return null;
1098 1098
         }
1099 1099
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1142,7 +1142,7 @@  discard block
 block discarded – undo
1142 1142
         if (is_array($columns_to_select)) {
1143 1143
             $select_sql_array = array();
1144 1144
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1145
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1145
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1146 1146
                     throw new EE_Error(
1147 1147
                         sprintf(
1148 1148
                             __(
@@ -1154,7 +1154,7 @@  discard block
 block discarded – undo
1154 1154
                         )
1155 1155
                     );
1156 1156
                 }
1157
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1157
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1158 1158
                     throw new EE_Error(
1159 1159
                         sprintf(
1160 1160
                             esc_html__(
@@ -1226,12 +1226,12 @@  discard block
 block discarded – undo
1226 1226
      */
1227 1227
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1228 1228
     {
1229
-        if (! isset($query_params[0])) {
1229
+        if ( ! isset($query_params[0])) {
1230 1230
             $query_params[0] = array();
1231 1231
         }
1232 1232
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1233 1233
         if ($conditions_from_id === null) {
1234
-            $query_params[0][ $this->primary_key_name() ] = $id;
1234
+            $query_params[0][$this->primary_key_name()] = $id;
1235 1235
         } else {
1236 1236
             // no primary key, so the $id must be from the get_index_primary_key_string()
1237 1237
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1251,7 +1251,7 @@  discard block
 block discarded – undo
1251 1251
      */
1252 1252
     public function get_one($query_params = array())
1253 1253
     {
1254
-        if (! is_array($query_params)) {
1254
+        if ( ! is_array($query_params)) {
1255 1255
             EE_Error::doing_it_wrong(
1256 1256
                 'EEM_Base::get_one',
1257 1257
                 sprintf(
@@ -1449,7 +1449,7 @@  discard block
 block discarded – undo
1449 1449
                 return array();
1450 1450
             }
1451 1451
         }
1452
-        if (! is_array($query_params)) {
1452
+        if ( ! is_array($query_params)) {
1453 1453
             EE_Error::doing_it_wrong(
1454 1454
                 'EEM_Base::_get_consecutive',
1455 1455
                 sprintf(
@@ -1461,7 +1461,7 @@  discard block
 block discarded – undo
1461 1461
             $query_params = array();
1462 1462
         }
1463 1463
         // let's add the where query param for consecutive look up.
1464
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1464
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1465 1465
         $query_params['limit'] = $limit;
1466 1466
         // set direction
1467 1467
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1542,7 +1542,7 @@  discard block
 block discarded – undo
1542 1542
     {
1543 1543
         $field_settings = $this->field_settings_for($field_name);
1544 1544
         // if not a valid EE_Datetime_Field then throw error
1545
-        if (! $field_settings instanceof EE_Datetime_Field) {
1545
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1546 1546
             throw new EE_Error(sprintf(__(
1547 1547
                 '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.',
1548 1548
                 'event_espresso'
@@ -1692,7 +1692,7 @@  discard block
 block discarded – undo
1692 1692
      */
1693 1693
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1694 1694
     {
1695
-        if (! is_array($query_params)) {
1695
+        if ( ! is_array($query_params)) {
1696 1696
             EE_Error::doing_it_wrong(
1697 1697
                 'EEM_Base::update',
1698 1698
                 sprintf(
@@ -1740,7 +1740,7 @@  discard block
 block discarded – undo
1740 1740
             $wpdb_result = (array) $wpdb_result;
1741 1741
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1742 1742
             if ($this->has_primary_key_field()) {
1743
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1743
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1744 1744
             } else {
1745 1745
                 // 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)
1746 1746
                 $main_table_pk_value = null;
@@ -1754,8 +1754,8 @@  discard block
 block discarded – undo
1754 1754
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1755 1755
                     // if there is no private key for this table on the results, it means there's no entry
1756 1756
                     // in this table, right? so insert a row in the current table, using any fields available
1757
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1758
-                           && $wpdb_result[ $this_table_pk_column ])
1757
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1758
+                           && $wpdb_result[$this_table_pk_column])
1759 1759
                     ) {
1760 1760
                         $success = $this->_insert_into_specific_table(
1761 1761
                             $table_obj,
@@ -1763,7 +1763,7 @@  discard block
 block discarded – undo
1763 1763
                             $main_table_pk_value
1764 1764
                         );
1765 1765
                         // if we died here, report the error
1766
-                        if (! $success) {
1766
+                        if ( ! $success) {
1767 1767
                             return false;
1768 1768
                         }
1769 1769
                     }
@@ -1791,10 +1791,10 @@  discard block
 block discarded – undo
1791 1791
                 $model_objs_affected_ids = array();
1792 1792
                 foreach ($models_affected_key_columns as $row) {
1793 1793
                     $combined_index_key = $this->get_index_primary_key_string($row);
1794
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1794
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1795 1795
                 }
1796 1796
             }
1797
-            if (! $model_objs_affected_ids) {
1797
+            if ( ! $model_objs_affected_ids) {
1798 1798
                 // wait wait wait- if nothing was affected let's stop here
1799 1799
                 return 0;
1800 1800
             }
@@ -1821,7 +1821,7 @@  discard block
 block discarded – undo
1821 1821
                . $model_query_info->get_full_join_sql()
1822 1822
                . " SET "
1823 1823
                . $this->_construct_update_sql($fields_n_values)
1824
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1824
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1825 1825
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1826 1826
         /**
1827 1827
          * Action called after a model update call has been made.
@@ -1832,7 +1832,7 @@  discard block
 block discarded – undo
1832 1832
          * @param int      $rows_affected
1833 1833
          */
1834 1834
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1835
-        return $rows_affected;// how many supposedly got updated
1835
+        return $rows_affected; // how many supposedly got updated
1836 1836
     }
1837 1837
 
1838 1838
 
@@ -1860,7 +1860,7 @@  discard block
 block discarded – undo
1860 1860
         }
1861 1861
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1862 1862
         $select_expressions = $field->get_qualified_column();
1863
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1863
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1864 1864
         return $this->_do_wpdb_query('get_col', array($SQL));
1865 1865
     }
1866 1866
 
@@ -1878,7 +1878,7 @@  discard block
 block discarded – undo
1878 1878
     {
1879 1879
         $query_params['limit'] = 1;
1880 1880
         $col = $this->get_col($query_params, $field_to_select);
1881
-        if (! empty($col)) {
1881
+        if ( ! empty($col)) {
1882 1882
             return reset($col);
1883 1883
         }
1884 1884
         return null;
@@ -1909,7 +1909,7 @@  discard block
 block discarded – undo
1909 1909
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1910 1910
             $value_sql = $prepared_value === null ? 'NULL'
1911 1911
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1912
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1912
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1913 1913
         }
1914 1914
         return implode(",", $cols_n_values);
1915 1915
     }
@@ -2052,12 +2052,12 @@  discard block
 block discarded – undo
2052 2052
         // there was no error with the delete query.
2053 2053
         if ($this->has_primary_key_field()
2054 2054
             && $rows_deleted !== false
2055
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2055
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2056 2056
         ) {
2057
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2057
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2058 2058
             foreach ($ids_for_removal as $id) {
2059
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2060
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2059
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2060
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2061 2061
                 }
2062 2062
             }
2063 2063
 
@@ -2092,7 +2092,7 @@  discard block
 block discarded – undo
2092 2092
          * @param int      $rows_deleted
2093 2093
          */
2094 2094
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2095
-        return $rows_deleted;// how many supposedly got deleted
2095
+        return $rows_deleted; // how many supposedly got deleted
2096 2096
     }
2097 2097
 
2098 2098
 
@@ -2185,15 +2185,15 @@  discard block
 block discarded – undo
2185 2185
                 // make sure there's no related entities blocking its deletion (if we're checking)
2186 2186
                 if ($allow_blocking
2187 2187
                     && $this->delete_is_blocked_by_related_models(
2188
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2188
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2189 2189
                     )
2190 2190
                 ) {
2191 2191
                     continue;
2192 2192
                 }
2193 2193
                 // primary table deletes
2194
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2195
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2196
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2194
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2195
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2196
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2197 2197
                 }
2198 2198
             }
2199 2199
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2202,8 +2202,8 @@  discard block
 block discarded – undo
2202 2202
                 $ids_to_delete_indexed_by_column_for_row = array();
2203 2203
                 foreach ($fields as $cpk_field) {
2204 2204
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2205
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2206
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2205
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2206
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2207 2207
                     }
2208 2208
                 }
2209 2209
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2243,7 +2243,7 @@  discard block
 block discarded – undo
2243 2243
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2244 2244
                 // make sure we have unique $ids
2245 2245
                 $ids = array_unique($ids);
2246
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2246
+                $query[] = $column.' IN('.implode(',', $ids).')';
2247 2247
             }
2248 2248
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2249 2249
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2251,7 +2251,7 @@  discard block
 block discarded – undo
2251 2251
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2252 2252
                 $values_for_each_combined_primary_key_for_a_row = array();
2253 2253
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2254
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2254
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2255 2255
                 }
2256 2256
                 $ways_to_identify_a_row[] = '('
2257 2257
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2323,8 +2323,8 @@  discard block
 block discarded – undo
2323 2323
                 $column_to_count = '*';
2324 2324
             }
2325 2325
         }
2326
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2327
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2326
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2327
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2328 2328
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2329 2329
     }
2330 2330
 
@@ -2347,7 +2347,7 @@  discard block
 block discarded – undo
2347 2347
             $field_obj = $this->get_primary_key_field();
2348 2348
         }
2349 2349
         $column_to_count = $field_obj->get_qualified_column();
2350
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2350
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2351 2351
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2352 2352
         $data_type = $field_obj->get_wpdb_data_type();
2353 2353
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2374,7 +2374,7 @@  discard block
 block discarded – undo
2374 2374
         // if we're in maintenance mode level 2, DON'T run any queries
2375 2375
         // because level 2 indicates the database needs updating and
2376 2376
         // is probably out of sync with the code
2377
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2377
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2378 2378
             throw new EE_Error(sprintf(__(
2379 2379
                 "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.",
2380 2380
                 "event_espresso"
@@ -2382,7 +2382,7 @@  discard block
 block discarded – undo
2382 2382
         }
2383 2383
         /** @type WPDB $wpdb */
2384 2384
         global $wpdb;
2385
-        if (! method_exists($wpdb, $wpdb_method)) {
2385
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2386 2386
             throw new EE_Error(sprintf(__(
2387 2387
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2388 2388
                 'event_espresso'
@@ -2396,7 +2396,7 @@  discard block
 block discarded – undo
2396 2396
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2397 2397
         if (WP_DEBUG) {
2398 2398
             $wpdb->show_errors($old_show_errors_value);
2399
-            if (! empty($wpdb->last_error)) {
2399
+            if ( ! empty($wpdb->last_error)) {
2400 2400
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2401 2401
             }
2402 2402
             if ($result === false) {
@@ -2461,7 +2461,7 @@  discard block
 block discarded – undo
2461 2461
                     return $result;
2462 2462
                     break;
2463 2463
             }
2464
-            if (! empty($error_message)) {
2464
+            if ( ! empty($error_message)) {
2465 2465
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2466 2466
                 trigger_error($error_message);
2467 2467
             }
@@ -2541,11 +2541,11 @@  discard block
 block discarded – undo
2541 2541
      */
2542 2542
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2543 2543
     {
2544
-        return " FROM " . $model_query_info->get_full_join_sql() .
2545
-               $model_query_info->get_where_sql() .
2546
-               $model_query_info->get_group_by_sql() .
2547
-               $model_query_info->get_having_sql() .
2548
-               $model_query_info->get_order_by_sql() .
2544
+        return " FROM ".$model_query_info->get_full_join_sql().
2545
+               $model_query_info->get_where_sql().
2546
+               $model_query_info->get_group_by_sql().
2547
+               $model_query_info->get_having_sql().
2548
+               $model_query_info->get_order_by_sql().
2549 2549
                $model_query_info->get_limit_sql();
2550 2550
     }
2551 2551
 
@@ -2741,12 +2741,12 @@  discard block
 block discarded – undo
2741 2741
         $related_model = $this->get_related_model_obj($model_name);
2742 2742
         // we're just going to use the query params on the related model's normal get_all query,
2743 2743
         // except add a condition to say to match the current mod
2744
-        if (! isset($query_params['default_where_conditions'])) {
2744
+        if ( ! isset($query_params['default_where_conditions'])) {
2745 2745
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2746 2746
         }
2747 2747
         $this_model_name = $this->get_this_model_name();
2748 2748
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2749
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2749
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2750 2750
         return $related_model->count($query_params, $field_to_count, $distinct);
2751 2751
     }
2752 2752
 
@@ -2766,7 +2766,7 @@  discard block
 block discarded – undo
2766 2766
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2767 2767
     {
2768 2768
         $related_model = $this->get_related_model_obj($model_name);
2769
-        if (! is_array($query_params)) {
2769
+        if ( ! is_array($query_params)) {
2770 2770
             EE_Error::doing_it_wrong(
2771 2771
                 'EEM_Base::sum_related',
2772 2772
                 sprintf(
@@ -2779,12 +2779,12 @@  discard block
 block discarded – undo
2779 2779
         }
2780 2780
         // we're just going to use the query params on the related model's normal get_all query,
2781 2781
         // except add a condition to say to match the current mod
2782
-        if (! isset($query_params['default_where_conditions'])) {
2782
+        if ( ! isset($query_params['default_where_conditions'])) {
2783 2783
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2784 2784
         }
2785 2785
         $this_model_name = $this->get_this_model_name();
2786 2786
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2787
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2787
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2788 2788
         return $related_model->sum($query_params, $field_to_sum);
2789 2789
     }
2790 2790
 
@@ -2837,7 +2837,7 @@  discard block
 block discarded – undo
2837 2837
                 $field_with_model_name = $field;
2838 2838
             }
2839 2839
         }
2840
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2840
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2841 2841
             throw new EE_Error(sprintf(
2842 2842
                 __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2843 2843
                 $this->get_this_model_name()
@@ -2973,13 +2973,13 @@  discard block
 block discarded – undo
2973 2973
                 || $this->get_primary_key_field()
2974 2974
                    instanceof
2975 2975
                    EE_Primary_Key_String_Field)
2976
-            && isset($fields_n_values[ $this->primary_key_name() ])
2976
+            && isset($fields_n_values[$this->primary_key_name()])
2977 2977
         ) {
2978
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2978
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2979 2979
         }
2980 2980
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2981 2981
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2982
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2982
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2983 2983
         }
2984 2984
         // if there is nothing to base this search on, then we shouldn't find anything
2985 2985
         if (empty($query_params)) {
@@ -3057,15 +3057,15 @@  discard block
 block discarded – undo
3057 3057
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3058 3058
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3059 3059
             if ($prepared_value !== null) {
3060
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3060
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3061 3061
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3062 3062
             }
3063 3063
         }
3064 3064
         if ($table instanceof EE_Secondary_Table && $new_id) {
3065 3065
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3066 3066
             // so add the fk to the main table as a column
3067
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3068
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3067
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3068
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
3069 3069
         }
3070 3070
         // insert the new entry
3071 3071
         $result = $this->_do_wpdb_query(
@@ -3082,7 +3082,7 @@  discard block
 block discarded – undo
3082 3082
             }
3083 3083
             // it's not an auto-increment primary key, so
3084 3084
             // it must have been supplied
3085
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3085
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3086 3086
         }
3087 3087
         // we can't return a  primary key because there is none. instead return
3088 3088
         // a unique string indicating this model
@@ -3104,16 +3104,16 @@  discard block
 block discarded – undo
3104 3104
     protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3105 3105
     {
3106 3106
         // if this field doesn't allow nullable, don't allow it
3107
-        if (! $field_obj->is_nullable()
3107
+        if ( ! $field_obj->is_nullable()
3108 3108
             && (
3109
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3110
-                || $fields_n_values[ $field_obj->get_name() ] === null
3109
+                ! isset($fields_n_values[$field_obj->get_name()])
3110
+                || $fields_n_values[$field_obj->get_name()] === null
3111 3111
             )
3112 3112
         ) {
3113
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3113
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3114 3114
         }
3115
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3116
-            ? $fields_n_values[ $field_obj->get_name() ]
3115
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3116
+            ? $fields_n_values[$field_obj->get_name()]
3117 3117
             : null;
3118 3118
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3119 3119
     }
@@ -3214,7 +3214,7 @@  discard block
 block discarded – undo
3214 3214
      */
3215 3215
     public function get_table_obj_by_alias($table_alias = '')
3216 3216
     {
3217
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3217
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3218 3218
     }
3219 3219
 
3220 3220
 
@@ -3229,7 +3229,7 @@  discard block
 block discarded – undo
3229 3229
         $other_tables = array();
3230 3230
         foreach ($this->_tables as $table_alias => $table) {
3231 3231
             if ($table instanceof EE_Secondary_Table) {
3232
-                $other_tables[ $table_alias ] = $table;
3232
+                $other_tables[$table_alias] = $table;
3233 3233
             }
3234 3234
         }
3235 3235
         return $other_tables;
@@ -3245,7 +3245,7 @@  discard block
 block discarded – undo
3245 3245
      */
3246 3246
     public function _get_fields_for_table($table_alias)
3247 3247
     {
3248
-        return $this->_fields[ $table_alias ];
3248
+        return $this->_fields[$table_alias];
3249 3249
     }
3250 3250
 
3251 3251
 
@@ -3274,7 +3274,7 @@  discard block
 block discarded – undo
3274 3274
                     $query_info_carrier,
3275 3275
                     'group_by'
3276 3276
                 );
3277
-            } elseif (! empty($query_params['group_by'])) {
3277
+            } elseif ( ! empty($query_params['group_by'])) {
3278 3278
                 $this->_extract_related_model_info_from_query_param(
3279 3279
                     $query_params['group_by'],
3280 3280
                     $query_info_carrier,
@@ -3296,7 +3296,7 @@  discard block
 block discarded – undo
3296 3296
                     $query_info_carrier,
3297 3297
                     'order_by'
3298 3298
                 );
3299
-            } elseif (! empty($query_params['order_by'])) {
3299
+            } elseif ( ! empty($query_params['order_by'])) {
3300 3300
                 $this->_extract_related_model_info_from_query_param(
3301 3301
                     $query_params['order_by'],
3302 3302
                     $query_info_carrier,
@@ -3332,7 +3332,7 @@  discard block
 block discarded – undo
3332 3332
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3333 3333
         $query_param_type
3334 3334
     ) {
3335
-        if (! empty($sub_query_params)) {
3335
+        if ( ! empty($sub_query_params)) {
3336 3336
             $sub_query_params = (array) $sub_query_params;
3337 3337
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3338 3338
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3347,7 +3347,7 @@  discard block
 block discarded – undo
3347 3347
                 // of array('Registration.TXN_ID'=>23)
3348 3348
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3349 3349
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3350
-                    if (! is_array($possibly_array_of_params)) {
3350
+                    if ( ! is_array($possibly_array_of_params)) {
3351 3351
                         throw new EE_Error(sprintf(
3352 3352
                             __(
3353 3353
                                 "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'))",
@@ -3370,7 +3370,7 @@  discard block
 block discarded – undo
3370 3370
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3371 3371
                     // indicating that $possible_array_of_params[1] is actually a field name,
3372 3372
                     // from which we should extract query parameters!
3373
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3373
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3374 3374
                         throw new EE_Error(sprintf(__(
3375 3375
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3376 3376
                             "event_espresso"
@@ -3405,8 +3405,8 @@  discard block
 block discarded – undo
3405 3405
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3406 3406
         $query_param_type
3407 3407
     ) {
3408
-        if (! empty($sub_query_params)) {
3409
-            if (! is_array($sub_query_params)) {
3408
+        if ( ! empty($sub_query_params)) {
3409
+            if ( ! is_array($sub_query_params)) {
3410 3410
                 throw new EE_Error(sprintf(
3411 3411
                     __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3412 3412
                     $sub_query_params
@@ -3440,7 +3440,7 @@  discard block
 block discarded – undo
3440 3440
      */
3441 3441
     public function _create_model_query_info_carrier($query_params)
3442 3442
     {
3443
-        if (! is_array($query_params)) {
3443
+        if ( ! is_array($query_params)) {
3444 3444
             EE_Error::doing_it_wrong(
3445 3445
                 'EEM_Base::_create_model_query_info_carrier',
3446 3446
                 sprintf(
@@ -3515,7 +3515,7 @@  discard block
 block discarded – undo
3515 3515
         // set limit
3516 3516
         if (array_key_exists('limit', $query_params)) {
3517 3517
             if (is_array($query_params['limit'])) {
3518
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3518
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3519 3519
                     $e = sprintf(
3520 3520
                         __(
3521 3521
                             "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)",
@@ -3523,12 +3523,12 @@  discard block
 block discarded – undo
3523 3523
                         ),
3524 3524
                         http_build_query($query_params['limit'])
3525 3525
                     );
3526
-                    throw new EE_Error($e . "|" . $e);
3526
+                    throw new EE_Error($e."|".$e);
3527 3527
                 }
3528 3528
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3529
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3530
-            } elseif (! empty($query_params['limit'])) {
3531
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3529
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3530
+            } elseif ( ! empty($query_params['limit'])) {
3531
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3532 3532
             }
3533 3533
         }
3534 3534
         // set order by
@@ -3560,10 +3560,10 @@  discard block
 block discarded – undo
3560 3560
                 $order_array = array();
3561 3561
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3562 3562
                     $order = $this->_extract_order($order);
3563
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3563
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3564 3564
                 }
3565
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3566
-            } elseif (! empty($query_params['order_by'])) {
3565
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3566
+            } elseif ( ! empty($query_params['order_by'])) {
3567 3567
                 $this->_extract_related_model_info_from_query_param(
3568 3568
                     $query_params['order_by'],
3569 3569
                     $query_object,
@@ -3574,18 +3574,18 @@  discard block
 block discarded – undo
3574 3574
                     ? $this->_extract_order($query_params['order'])
3575 3575
                     : 'DESC';
3576 3576
                 $query_object->set_order_by_sql(
3577
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3577
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3578 3578
                 );
3579 3579
             }
3580 3580
         }
3581 3581
         // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3582
-        if (! array_key_exists('order_by', $query_params)
3582
+        if ( ! array_key_exists('order_by', $query_params)
3583 3583
             && array_key_exists('order', $query_params)
3584 3584
             && ! empty($query_params['order'])
3585 3585
         ) {
3586 3586
             $pk_field = $this->get_primary_key_field();
3587 3587
             $order = $this->_extract_order($query_params['order']);
3588
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3588
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3589 3589
         }
3590 3590
         // set group by
3591 3591
         if (array_key_exists('group_by', $query_params)) {
@@ -3595,10 +3595,10 @@  discard block
 block discarded – undo
3595 3595
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3596 3596
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3597 3597
                 }
3598
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3599
-            } elseif (! empty($query_params['group_by'])) {
3598
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3599
+            } elseif ( ! empty($query_params['group_by'])) {
3600 3600
                 $query_object->set_group_by_sql(
3601
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3601
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3602 3602
                 );
3603 3603
             }
3604 3604
         }
@@ -3608,7 +3608,7 @@  discard block
 block discarded – undo
3608 3608
         }
3609 3609
         // now, just verify they didn't pass anything wack
3610 3610
         foreach ($query_params as $query_key => $query_value) {
3611
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3611
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3612 3612
                 throw new EE_Error(
3613 3613
                     sprintf(
3614 3614
                         __(
@@ -3716,7 +3716,7 @@  discard block
 block discarded – undo
3716 3716
         $where_query_params = array()
3717 3717
     ) {
3718 3718
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3719
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3719
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3720 3720
             throw new EE_Error(sprintf(
3721 3721
                 __(
3722 3722
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3848,19 +3848,19 @@  discard block
 block discarded – undo
3848 3848
     ) {
3849 3849
         $null_friendly_where_conditions = array();
3850 3850
         $none_overridden = true;
3851
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3851
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3852 3852
         foreach ($default_where_conditions as $key => $val) {
3853
-            if (isset($provided_where_conditions[ $key ])) {
3853
+            if (isset($provided_where_conditions[$key])) {
3854 3854
                 $none_overridden = false;
3855 3855
             } else {
3856
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3856
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3857 3857
             }
3858 3858
         }
3859 3859
         if ($none_overridden && $default_where_conditions) {
3860 3860
             if ($model->has_primary_key_field()) {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3861
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3862 3862
                                                                                 . "."
3863
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3863
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3864 3864
             }/*else{
3865 3865
                 //@todo NO PK, use other defaults
3866 3866
             }*/
@@ -3966,7 +3966,7 @@  discard block
 block discarded – undo
3966 3966
             foreach ($tables as $table_obj) {
3967 3967
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3968 3968
                                        . $table_obj->get_fully_qualified_pk_column();
3969
-                if (! in_array($qualified_pk_column, $selects)) {
3969
+                if ( ! in_array($qualified_pk_column, $selects)) {
3970 3970
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3971 3971
                 }
3972 3972
             }
@@ -4115,9 +4115,9 @@  discard block
 block discarded – undo
4115 4115
         $query_parameter_type
4116 4116
     ) {
4117 4117
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4118
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4118
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4119 4119
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4120
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4120
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4121 4121
                 if ($possible_join_string === '') {
4122 4122
                     // nothing left to $query_param
4123 4123
                     // we should actually end in a field name, not a model like this!
@@ -4247,7 +4247,7 @@  discard block
 block discarded – undo
4247 4247
     {
4248 4248
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4249 4249
         if ($SQL) {
4250
-            return " WHERE " . $SQL;
4250
+            return " WHERE ".$SQL;
4251 4251
         }
4252 4252
         return '';
4253 4253
     }
@@ -4266,7 +4266,7 @@  discard block
 block discarded – undo
4266 4266
     {
4267 4267
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4268 4268
         if ($SQL) {
4269
-            return " HAVING " . $SQL;
4269
+            return " HAVING ".$SQL;
4270 4270
         }
4271 4271
         return '';
4272 4272
     }
@@ -4285,7 +4285,7 @@  discard block
 block discarded – undo
4285 4285
     {
4286 4286
         $where_clauses = array();
4287 4287
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4288
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4288
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4289 4289
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4290 4290
                 switch ($query_param) {
4291 4291
                     case 'not':
@@ -4319,7 +4319,7 @@  discard block
 block discarded – undo
4319 4319
             } else {
4320 4320
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4321 4321
                 // if it's not a normal field, maybe it's a custom selection?
4322
-                if (! $field_obj) {
4322
+                if ( ! $field_obj) {
4323 4323
                     if ($this->_custom_selections instanceof CustomSelects) {
4324 4324
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4325 4325
                     } else {
@@ -4330,7 +4330,7 @@  discard block
 block discarded – undo
4330 4330
                     }
4331 4331
                 }
4332 4332
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4333
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4333
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4334 4334
             }
4335 4335
         }
4336 4336
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4353,7 +4353,7 @@  discard block
 block discarded – undo
4353 4353
                 $field->get_model_name(),
4354 4354
                 $query_param
4355 4355
             );
4356
-            return $table_alias_prefix . $field->get_qualified_column();
4356
+            return $table_alias_prefix.$field->get_qualified_column();
4357 4357
         }
4358 4358
         if ($this->_custom_selections instanceof CustomSelects
4359 4359
             && in_array($query_param, $this->_custom_selections->columnAliases(), true)
@@ -4412,7 +4412,7 @@  discard block
 block discarded – undo
4412 4412
     {
4413 4413
         if (is_array($op_and_value)) {
4414 4414
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4415
-            if (! $operator) {
4415
+            if ( ! $operator) {
4416 4416
                 $php_array_like_string = array();
4417 4417
                 foreach ($op_and_value as $key => $value) {
4418 4418
                     $php_array_like_string[] = "$key=>$value";
@@ -4434,14 +4434,14 @@  discard block
 block discarded – undo
4434 4434
         }
4435 4435
         // check to see if the value is actually another field
4436 4436
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4437
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4437
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4438 4438
         }
4439 4439
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4440 4440
             // in this case, the value should be an array, or at least a comma-separated list
4441 4441
             // it will need to handle a little differently
4442 4442
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4443 4443
             // note: $cleaned_value has already been run through $wpdb->prepare()
4444
-            return $operator . SP . $cleaned_value;
4444
+            return $operator.SP.$cleaned_value;
4445 4445
         }
4446 4446
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4447 4447
             // the value should be an array with count of two.
@@ -4457,7 +4457,7 @@  discard block
 block discarded – undo
4457 4457
                 );
4458 4458
             }
4459 4459
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4460
-            return $operator . SP . $cleaned_value;
4460
+            return $operator.SP.$cleaned_value;
4461 4461
         }
4462 4462
         if (in_array($operator, $this->valid_null_style_operators())) {
4463 4463
             if ($value !== null) {
@@ -4477,10 +4477,10 @@  discard block
 block discarded – undo
4477 4477
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4478 4478
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4479 4479
             // remove other junk. So just treat it as a string.
4480
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4480
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4481 4481
         }
4482
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4483
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4482
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4483
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4484 4484
         }
4485 4485
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4486 4486
             throw new EE_Error(
@@ -4494,7 +4494,7 @@  discard block
 block discarded – undo
4494 4494
                 )
4495 4495
             );
4496 4496
         }
4497
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4497
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4498 4498
             throw new EE_Error(
4499 4499
                 sprintf(
4500 4500
                     __(
@@ -4534,7 +4534,7 @@  discard block
 block discarded – undo
4534 4534
         foreach ($values as $value) {
4535 4535
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4536 4536
         }
4537
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4537
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4538 4538
     }
4539 4539
 
4540 4540
 
@@ -4575,7 +4575,7 @@  discard block
 block discarded – undo
4575 4575
                                 . $main_table->get_table_name()
4576 4576
                                 . " WHERE FALSE";
4577 4577
         }
4578
-        return "(" . implode(",", $cleaned_values) . ")";
4578
+        return "(".implode(",", $cleaned_values).")";
4579 4579
     }
4580 4580
 
4581 4581
 
@@ -4596,7 +4596,7 @@  discard block
 block discarded – undo
4596 4596
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4597 4597
             );
4598 4598
         } //$field_obj should really just be a data type
4599
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4599
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4600 4600
             throw new EE_Error(
4601 4601
                 sprintf(
4602 4602
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4629,14 +4629,14 @@  discard block
 block discarded – undo
4629 4629
             ), $query_param_name));
4630 4630
         }
4631 4631
         $number_of_parts = count($query_param_parts);
4632
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4632
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4633 4633
         if ($number_of_parts === 1) {
4634 4634
             $field_name = $last_query_param_part;
4635 4635
             $model_obj = $this;
4636 4636
         } else {// $number_of_parts >= 2
4637 4637
             // the last part is the column name, and there are only 2parts. therefore...
4638 4638
             $field_name = $last_query_param_part;
4639
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4639
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4640 4640
         }
4641 4641
         try {
4642 4642
             return $model_obj->field_settings_for($field_name);
@@ -4658,7 +4658,7 @@  discard block
 block discarded – undo
4658 4658
     public function _get_qualified_column_for_field($field_name)
4659 4659
     {
4660 4660
         $all_fields = $this->field_settings();
4661
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4661
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4662 4662
         if ($field) {
4663 4663
             return $field->get_qualified_column();
4664 4664
         }
@@ -4729,10 +4729,10 @@  discard block
 block discarded – undo
4729 4729
      */
4730 4730
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4731 4731
     {
4732
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4732
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4733 4733
         $qualified_columns = array();
4734 4734
         foreach ($this->field_settings() as $field_name => $field) {
4735
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4735
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4736 4736
         }
4737 4737
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4738 4738
     }
@@ -4756,11 +4756,11 @@  discard block
 block discarded – undo
4756 4756
             if ($table_obj instanceof EE_Primary_Table) {
4757 4757
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4758 4758
                     ? $table_obj->get_select_join_limit($limit)
4759
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4759
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4760 4760
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4761 4761
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4762 4762
                     ? $table_obj->get_select_join_limit_join($limit)
4763
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4763
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4764 4764
             }
4765 4765
         }
4766 4766
         return $SQL;
@@ -4832,7 +4832,7 @@  discard block
 block discarded – undo
4832 4832
         foreach ($this->field_settings() as $field_obj) {
4833 4833
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4834 4834
             /** @var $field_obj EE_Model_Field_Base */
4835
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4835
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4836 4836
         }
4837 4837
         return $data_types;
4838 4838
     }
@@ -4848,14 +4848,14 @@  discard block
 block discarded – undo
4848 4848
      */
4849 4849
     public function get_related_model_obj($model_name)
4850 4850
     {
4851
-        $model_classname = "EEM_" . $model_name;
4852
-        if (! class_exists($model_classname)) {
4851
+        $model_classname = "EEM_".$model_name;
4852
+        if ( ! class_exists($model_classname)) {
4853 4853
             throw new EE_Error(sprintf(__(
4854 4854
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4855 4855
                 'event_espresso'
4856 4856
             ), $model_name, $model_classname));
4857 4857
         }
4858
-        return call_user_func($model_classname . "::instance");
4858
+        return call_user_func($model_classname."::instance");
4859 4859
     }
4860 4860
 
4861 4861
 
@@ -4884,7 +4884,7 @@  discard block
 block discarded – undo
4884 4884
         $belongs_to_relations = array();
4885 4885
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4886 4886
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4887
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4887
+                $belongs_to_relations[$model_name] = $relation_obj;
4888 4888
             }
4889 4889
         }
4890 4890
         return $belongs_to_relations;
@@ -4902,7 +4902,7 @@  discard block
 block discarded – undo
4902 4902
     public function related_settings_for($relation_name)
4903 4903
     {
4904 4904
         $relatedModels = $this->relation_settings();
4905
-        if (! array_key_exists($relation_name, $relatedModels)) {
4905
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4906 4906
             throw new EE_Error(
4907 4907
                 sprintf(
4908 4908
                     __(
@@ -4915,7 +4915,7 @@  discard block
 block discarded – undo
4915 4915
                 )
4916 4916
             );
4917 4917
         }
4918
-        return $relatedModels[ $relation_name ];
4918
+        return $relatedModels[$relation_name];
4919 4919
     }
4920 4920
 
4921 4921
 
@@ -4932,14 +4932,14 @@  discard block
 block discarded – undo
4932 4932
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4933 4933
     {
4934 4934
         $fieldSettings = $this->field_settings($include_db_only_fields);
4935
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4935
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4936 4936
             throw new EE_Error(sprintf(
4937 4937
                 __("There is no field/column '%s' on '%s'", 'event_espresso'),
4938 4938
                 $fieldName,
4939 4939
                 get_class($this)
4940 4940
             ));
4941 4941
         }
4942
-        return $fieldSettings[ $fieldName ];
4942
+        return $fieldSettings[$fieldName];
4943 4943
     }
4944 4944
 
4945 4945
 
@@ -4953,7 +4953,7 @@  discard block
 block discarded – undo
4953 4953
     public function has_field($fieldName)
4954 4954
     {
4955 4955
         $fieldSettings = $this->field_settings(true);
4956
-        if (isset($fieldSettings[ $fieldName ])) {
4956
+        if (isset($fieldSettings[$fieldName])) {
4957 4957
             return true;
4958 4958
         }
4959 4959
         return false;
@@ -4970,7 +4970,7 @@  discard block
 block discarded – undo
4970 4970
     public function has_relation($relation_name)
4971 4971
     {
4972 4972
         $relations = $this->relation_settings();
4973
-        if (isset($relations[ $relation_name ])) {
4973
+        if (isset($relations[$relation_name])) {
4974 4974
             return true;
4975 4975
         }
4976 4976
         return false;
@@ -5008,7 +5008,7 @@  discard block
 block discarded – undo
5008 5008
                     break;
5009 5009
                 }
5010 5010
             }
5011
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5011
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5012 5012
                 throw new EE_Error(sprintf(
5013 5013
                     __("There is no Primary Key defined on model %s", 'event_espresso'),
5014 5014
                     get_class($this)
@@ -5069,23 +5069,23 @@  discard block
 block discarded – undo
5069 5069
      */
5070 5070
     public function get_foreign_key_to($model_name)
5071 5071
     {
5072
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5072
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5073 5073
             foreach ($this->field_settings() as $field) {
5074 5074
                 if ($field instanceof EE_Foreign_Key_Field_Base
5075 5075
                     && in_array($model_name, $field->get_model_names_pointed_to())
5076 5076
                 ) {
5077
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5077
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5078 5078
                     break;
5079 5079
                 }
5080 5080
             }
5081
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5081
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5082 5082
                 throw new EE_Error(sprintf(__(
5083 5083
                     "There is no foreign key field pointing to model %s on model %s",
5084 5084
                     'event_espresso'
5085 5085
                 ), $model_name, get_class($this)));
5086 5086
             }
5087 5087
         }
5088
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5088
+        return $this->_cache_foreign_key_to_fields[$model_name];
5089 5089
     }
5090 5090
 
5091 5091
 
@@ -5101,7 +5101,7 @@  discard block
 block discarded – undo
5101 5101
     public function get_table_for_alias($table_alias)
5102 5102
     {
5103 5103
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5104
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5104
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5105 5105
     }
5106 5106
 
5107 5107
 
@@ -5120,7 +5120,7 @@  discard block
 block discarded – undo
5120 5120
                 $this->_cached_fields = array();
5121 5121
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5122 5122
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5123
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5123
+                        $this->_cached_fields[$field_name] = $field_obj;
5124 5124
                     }
5125 5125
                 }
5126 5126
             }
@@ -5131,8 +5131,8 @@  discard block
 block discarded – undo
5131 5131
             foreach ($this->_fields as $fields_corresponding_to_table) {
5132 5132
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5133 5133
                     /** @var $field_obj EE_Model_Field_Base */
5134
-                    if (! $field_obj->is_db_only_field()) {
5135
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5134
+                    if ( ! $field_obj->is_db_only_field()) {
5135
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5136 5136
                     }
5137 5137
                 }
5138 5138
             }
@@ -5173,12 +5173,12 @@  discard block
 block discarded – undo
5173 5173
                     $primary_key_field->get_qualified_column(),
5174 5174
                     $primary_key_field->get_table_column()
5175 5175
                 );
5176
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5176
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5177 5177
                     continue;
5178 5178
                 }
5179 5179
             }
5180 5180
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5181
-            if (! $classInstance) {
5181
+            if ( ! $classInstance) {
5182 5182
                 throw new EE_Error(
5183 5183
                     sprintf(
5184 5184
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5191,7 +5191,7 @@  discard block
 block discarded – undo
5191 5191
             $classInstance->set_timezone($this->_timezone);
5192 5192
             // make sure if there is any timezone setting present that we set the timezone for the object
5193 5193
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5194
-            $array_of_objects[ $key ] = $classInstance;
5194
+            $array_of_objects[$key] = $classInstance;
5195 5195
             // also, for all the relations of type BelongsTo, see if we can cache
5196 5196
             // those related models
5197 5197
             // (we could do this for other relations too, but if there are conditions
@@ -5235,9 +5235,9 @@  discard block
 block discarded – undo
5235 5235
         $results = array();
5236 5236
         if ($this->_custom_selections instanceof CustomSelects) {
5237 5237
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5238
-                if (isset($db_results_row[ $alias ])) {
5239
-                    $results[ $alias ] = $this->convertValueToDataType(
5240
-                        $db_results_row[ $alias ],
5238
+                if (isset($db_results_row[$alias])) {
5239
+                    $results[$alias] = $this->convertValueToDataType(
5240
+                        $db_results_row[$alias],
5241 5241
                         $this->_custom_selections->getDataTypeForAlias($alias)
5242 5242
                     );
5243 5243
                 }
@@ -5279,7 +5279,7 @@  discard block
 block discarded – undo
5279 5279
         $this_model_fields_and_values = array();
5280 5280
         // setup the row using default values;
5281 5281
         foreach ($this->field_settings() as $field_name => $field_obj) {
5282
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5282
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5283 5283
         }
5284 5284
         $className = $this->_get_class_name();
5285 5285
         $classInstance = EE_Registry::instance()
@@ -5297,20 +5297,20 @@  discard block
 block discarded – undo
5297 5297
      */
5298 5298
     public function instantiate_class_from_array_or_object($cols_n_values)
5299 5299
     {
5300
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5300
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5301 5301
             $cols_n_values = get_object_vars($cols_n_values);
5302 5302
         }
5303 5303
         $primary_key = null;
5304 5304
         // make sure the array only has keys that are fields/columns on this model
5305 5305
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5306
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5307
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5306
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5307
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5308 5308
         }
5309 5309
         $className = $this->_get_class_name();
5310 5310
         // check we actually found results that we can use to build our model object
5311 5311
         // if not, return null
5312 5312
         if ($this->has_primary_key_field()) {
5313
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5313
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5314 5314
                 return null;
5315 5315
             }
5316 5316
         } elseif ($this->unique_indexes()) {
@@ -5322,7 +5322,7 @@  discard block
 block discarded – undo
5322 5322
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5323 5323
         if ($primary_key) {
5324 5324
             $classInstance = $this->get_from_entity_map($primary_key);
5325
-            if (! $classInstance) {
5325
+            if ( ! $classInstance) {
5326 5326
                 $classInstance = EE_Registry::instance()
5327 5327
                                             ->load_class(
5328 5328
                                                 $className,
@@ -5355,8 +5355,8 @@  discard block
 block discarded – undo
5355 5355
      */
5356 5356
     public function get_from_entity_map($id)
5357 5357
     {
5358
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5359
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5358
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5359
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5360 5360
     }
5361 5361
 
5362 5362
 
@@ -5379,7 +5379,7 @@  discard block
 block discarded – undo
5379 5379
     public function add_to_entity_map(EE_Base_Class $object)
5380 5380
     {
5381 5381
         $className = $this->_get_class_name();
5382
-        if (! $object instanceof $className) {
5382
+        if ( ! $object instanceof $className) {
5383 5383
             throw new EE_Error(sprintf(
5384 5384
                 __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5385 5385
                 is_object($object) ? get_class($object) : $object,
@@ -5387,7 +5387,7 @@  discard block
 block discarded – undo
5387 5387
             ));
5388 5388
         }
5389 5389
         /** @var $object EE_Base_Class */
5390
-        if (! $object->ID()) {
5390
+        if ( ! $object->ID()) {
5391 5391
             throw new EE_Error(sprintf(__(
5392 5392
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5393 5393
                 "event_espresso"
@@ -5398,7 +5398,7 @@  discard block
 block discarded – undo
5398 5398
         if ($classInstance) {
5399 5399
             return $classInstance;
5400 5400
         }
5401
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5401
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5402 5402
         return $object;
5403 5403
     }
5404 5404
 
@@ -5414,11 +5414,11 @@  discard block
 block discarded – undo
5414 5414
     public function clear_entity_map($id = null)
5415 5415
     {
5416 5416
         if (empty($id)) {
5417
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5417
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5418 5418
             return true;
5419 5419
         }
5420
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5421
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5420
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5421
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5422 5422
             return true;
5423 5423
         }
5424 5424
         return false;
@@ -5461,17 +5461,17 @@  discard block
 block discarded – undo
5461 5461
             // there is a primary key on this table and its not set. Use defaults for all its columns
5462 5462
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5463 5463
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5464
-                    if (! $field_obj->is_db_only_field()) {
5464
+                    if ( ! $field_obj->is_db_only_field()) {
5465 5465
                         // prepare field as if its coming from db
5466 5466
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5467
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5467
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5468 5468
                     }
5469 5469
                 }
5470 5470
             } else {
5471 5471
                 // the table's rows existed. Use their values
5472 5472
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5473
-                    if (! $field_obj->is_db_only_field()) {
5474
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5473
+                    if ( ! $field_obj->is_db_only_field()) {
5474
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5475 5475
                             $cols_n_values,
5476 5476
                             $field_obj->get_qualified_column(),
5477 5477
                             $field_obj->get_table_column()
@@ -5497,10 +5497,10 @@  discard block
 block discarded – undo
5497 5497
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5498 5498
         // does the field on the model relate to this column retrieved from the db?
5499 5499
         // or is it a db-only field? (not relating to the model)
5500
-        if (isset($cols_n_values[ $qualified_column ])) {
5501
-            $value = $cols_n_values[ $qualified_column ];
5502
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5503
-            $value = $cols_n_values[ $regular_column ];
5500
+        if (isset($cols_n_values[$qualified_column])) {
5501
+            $value = $cols_n_values[$qualified_column];
5502
+        } elseif (isset($cols_n_values[$regular_column])) {
5503
+            $value = $cols_n_values[$regular_column];
5504 5504
         }
5505 5505
         return $value;
5506 5506
     }
@@ -5533,7 +5533,7 @@  discard block
 block discarded – undo
5533 5533
                     $obj_in_map->clear_cache($relation_name, null, true);
5534 5534
                 }
5535 5535
             }
5536
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5536
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5537 5537
             return $obj_in_map;
5538 5538
         }
5539 5539
         return $this->get_one_by_ID($id);
@@ -5586,7 +5586,7 @@  discard block
 block discarded – undo
5586 5586
      */
5587 5587
     private function _get_class_name()
5588 5588
     {
5589
-        return "EE_" . $this->get_this_model_name();
5589
+        return "EE_".$this->get_this_model_name();
5590 5590
     }
5591 5591
 
5592 5592
 
@@ -5634,7 +5634,7 @@  discard block
 block discarded – undo
5634 5634
     {
5635 5635
         $className = get_class($this);
5636 5636
         $tagName = "FHEE__{$className}__{$methodName}";
5637
-        if (! has_filter($tagName)) {
5637
+        if ( ! has_filter($tagName)) {
5638 5638
             throw new EE_Error(
5639 5639
                 sprintf(
5640 5640
                     __(
@@ -5805,7 +5805,7 @@  discard block
 block discarded – undo
5805 5805
         $unique_indexes = array();
5806 5806
         foreach ($this->_indexes as $name => $index) {
5807 5807
             if ($index instanceof EE_Unique_Index) {
5808
-                $unique_indexes [ $name ] = $index;
5808
+                $unique_indexes [$name] = $index;
5809 5809
             }
5810 5810
         }
5811 5811
         return $unique_indexes;
@@ -5868,7 +5868,7 @@  discard block
 block discarded – undo
5868 5868
         $key_vals_in_combined_pk = array();
5869 5869
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5870 5870
         foreach ($key_fields as $key_field_name => $field_obj) {
5871
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5871
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5872 5872
                 return null;
5873 5873
             }
5874 5874
         }
@@ -5889,7 +5889,7 @@  discard block
 block discarded – undo
5889 5889
     {
5890 5890
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5891 5891
         foreach ($keys_it_should_have as $key) {
5892
-            if (! isset($key_vals[ $key ])) {
5892
+            if ( ! isset($key_vals[$key])) {
5893 5893
                 return false;
5894 5894
             }
5895 5895
         }
@@ -5922,8 +5922,8 @@  discard block
 block discarded – undo
5922 5922
         }
5923 5923
         // even copies obviously won't have the same ID, so remove the primary key
5924 5924
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5925
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5926
-            unset($attributes_array[ $this->primary_key_name() ]);
5925
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5926
+            unset($attributes_array[$this->primary_key_name()]);
5927 5927
         }
5928 5928
         if (isset($query_params[0])) {
5929 5929
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5945,7 +5945,7 @@  discard block
 block discarded – undo
5945 5945
      */
5946 5946
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5947 5947
     {
5948
-        if (! is_array($query_params)) {
5948
+        if ( ! is_array($query_params)) {
5949 5949
             EE_Error::doing_it_wrong(
5950 5950
                 'EEM_Base::get_one_copy',
5951 5951
                 sprintf(
@@ -5995,7 +5995,7 @@  discard block
 block discarded – undo
5995 5995
      */
5996 5996
     private function _prepare_operator_for_sql($operator_supplied)
5997 5997
     {
5998
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5998
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5999 5999
             : null;
6000 6000
         if ($sql_operator) {
6001 6001
             return $sql_operator;
@@ -6086,7 +6086,7 @@  discard block
 block discarded – undo
6086 6086
         $objs = $this->get_all($query_params);
6087 6087
         $names = array();
6088 6088
         foreach ($objs as $obj) {
6089
-            $names[ $obj->ID() ] = $obj->name();
6089
+            $names[$obj->ID()] = $obj->name();
6090 6090
         }
6091 6091
         return $names;
6092 6092
     }
@@ -6107,7 +6107,7 @@  discard block
 block discarded – undo
6107 6107
      */
6108 6108
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6109 6109
     {
6110
-        if (! $this->has_primary_key_field()) {
6110
+        if ( ! $this->has_primary_key_field()) {
6111 6111
             if (WP_DEBUG) {
6112 6112
                 EE_Error::add_error(
6113 6113
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6120,7 +6120,7 @@  discard block
 block discarded – undo
6120 6120
         $IDs = array();
6121 6121
         foreach ($model_objects as $model_object) {
6122 6122
             $id = $model_object->ID();
6123
-            if (! $id) {
6123
+            if ( ! $id) {
6124 6124
                 if ($filter_out_empty_ids) {
6125 6125
                     continue;
6126 6126
                 }
@@ -6170,22 +6170,22 @@  discard block
 block discarded – undo
6170 6170
     {
6171 6171
         EEM_Base::verify_is_valid_cap_context($context);
6172 6172
         // check if we ought to run the restriction generator first
6173
-        if (isset($this->_cap_restriction_generators[ $context ])
6174
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6175
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6173
+        if (isset($this->_cap_restriction_generators[$context])
6174
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6175
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6176 6176
         ) {
6177
-            $this->_cap_restrictions[ $context ] = array_merge(
6178
-                $this->_cap_restrictions[ $context ],
6179
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6177
+            $this->_cap_restrictions[$context] = array_merge(
6178
+                $this->_cap_restrictions[$context],
6179
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6180 6180
             );
6181 6181
         }
6182 6182
         // and make sure we've finalized the construction of each restriction
6183
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6183
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6184 6184
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6185 6185
                 $where_conditions_obj->_finalize_construct($this);
6186 6186
             }
6187 6187
         }
6188
-        return $this->_cap_restrictions[ $context ];
6188
+        return $this->_cap_restrictions[$context];
6189 6189
     }
6190 6190
 
6191 6191
 
@@ -6215,10 +6215,10 @@  discard block
 block discarded – undo
6215 6215
         $missing_caps = array();
6216 6216
         $cap_restrictions = $this->cap_restrictions($context);
6217 6217
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6218
-            if (! EE_Capabilities::instance()
6219
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6218
+            if ( ! EE_Capabilities::instance()
6219
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6220 6220
             ) {
6221
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6221
+                $missing_caps[$cap] = $restriction_if_no_cap;
6222 6222
             }
6223 6223
         }
6224 6224
         return $missing_caps;
@@ -6253,8 +6253,8 @@  discard block
 block discarded – undo
6253 6253
     public function cap_action_for_context($context)
6254 6254
     {
6255 6255
         $mapping = $this->cap_contexts_to_cap_action_map();
6256
-        if (isset($mapping[ $context ])) {
6257
-            return $mapping[ $context ];
6256
+        if (isset($mapping[$context])) {
6257
+            return $mapping[$context];
6258 6258
         }
6259 6259
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6260 6260
             return $action;
@@ -6371,7 +6371,7 @@  discard block
 block discarded – undo
6371 6371
     {
6372 6372
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6373 6373
             if ($query_param_key === $logic_query_param_key
6374
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6374
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6375 6375
             ) {
6376 6376
                 return true;
6377 6377
             }
Please login to merge, or discard this patch.
core/db_classes/EE_Registration.class.php 3 patches
Doc Comments   +4 added lines, -3 removed lines patch added patch discarded remove patch
@@ -1164,7 +1164,7 @@  discard block
 block discarded – undo
1164 1164
      * Sets deleted
1165 1165
      *
1166 1166
      * @param boolean $deleted
1167
-     * @return bool
1167
+     * @return boolean|null
1168 1168
      * @throws EE_Error
1169 1169
      * @throws RuntimeException
1170 1170
      */
@@ -1222,6 +1222,7 @@  discard block
 block discarded – undo
1222 1222
      * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1223 1223
      * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1224 1224
      *                                          consider registration status as well as datetime access.
1225
+     * @param integer $DTT_OR_ID
1225 1226
      * @return bool
1226 1227
      * @throws EE_Error
1227 1228
      */
@@ -1392,7 +1393,7 @@  discard block
 block discarded – undo
1392 1393
      * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1393 1394
      * "Latest" is defined by the `DTT_EVT_start` column.
1394 1395
      *
1395
-     * @return EE_Datetime|null
1396
+     * @return null|EE_Base_Class
1396 1397
      * @throws EE_Error
1397 1398
      */
1398 1399
     public function get_latest_related_datetime()
@@ -1688,7 +1689,7 @@  discard block
 block discarded – undo
1688 1689
      * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1689 1690
      * Note: if there are no payments on the registration there will be no payment method returned.
1690 1691
      *
1691
-     * @return EE_Payment_Method|null
1692
+     * @return null|EE_Base_Class
1692 1693
      */
1693 1694
     public function payment_method()
1694 1695
     {
Please login to merge, or discard this patch.
Indentation   +2067 added lines, -2067 removed lines patch added patch discarded remove patch
@@ -17,2071 +17,2071 @@
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * Used to reference when a registration has never been checked in.
22
-     *
23
-     * @deprecated use \EE_Checkin::status_checked_never instead
24
-     * @type int
25
-     */
26
-    const checkin_status_never = 2;
27
-
28
-    /**
29
-     * Used to reference when a registration has been checked in.
30
-     *
31
-     * @deprecated use \EE_Checkin::status_checked_in instead
32
-     * @type int
33
-     */
34
-    const checkin_status_in = 1;
35
-
36
-
37
-    /**
38
-     * Used to reference when a registration has been checked out.
39
-     *
40
-     * @deprecated use \EE_Checkin::status_checked_out instead
41
-     * @type int
42
-     */
43
-    const checkin_status_out = 0;
44
-
45
-
46
-    /**
47
-     * extra meta key for tracking reg status os trashed registrations
48
-     *
49
-     * @type string
50
-     */
51
-    const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
-
53
-
54
-    /**
55
-     * extra meta key for tracking if registration has reserved ticket
56
-     *
57
-     * @type string
58
-     */
59
-    const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
60
-
61
-
62
-    /**
63
-     * @param array  $props_n_values          incoming values
64
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
65
-     *                                        used.)
66
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
67
-     *                                        date_format and the second value is the time format
68
-     * @return EE_Registration
69
-     * @throws EE_Error
70
-     */
71
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
72
-    {
73
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
74
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
75
-    }
76
-
77
-
78
-    /**
79
-     * @param array  $props_n_values  incoming values from the database
80
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
-     *                                the website will be used.
82
-     * @return EE_Registration
83
-     */
84
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
85
-    {
86
-        return new self($props_n_values, true, $timezone);
87
-    }
88
-
89
-
90
-    /**
91
-     *        Set Event ID
92
-     *
93
-     * @param        int $EVT_ID Event ID
94
-     * @throws EE_Error
95
-     * @throws RuntimeException
96
-     */
97
-    public function set_event($EVT_ID = 0)
98
-    {
99
-        $this->set('EVT_ID', $EVT_ID);
100
-    }
101
-
102
-
103
-    /**
104
-     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
105
-     * be routed to internal methods
106
-     *
107
-     * @param string $field_name
108
-     * @param mixed  $field_value
109
-     * @param bool   $use_default
110
-     * @throws EE_Error
111
-     * @throws EntityNotFoundException
112
-     * @throws InvalidArgumentException
113
-     * @throws InvalidDataTypeException
114
-     * @throws InvalidInterfaceException
115
-     * @throws ReflectionException
116
-     * @throws RuntimeException
117
-     */
118
-    public function set($field_name, $field_value, $use_default = false)
119
-    {
120
-        switch ($field_name) {
121
-            case 'REG_code':
122
-                if (! empty($field_value) && $this->reg_code() === null) {
123
-                    $this->set_reg_code($field_value, $use_default);
124
-                }
125
-                break;
126
-            case 'STS_ID':
127
-                $this->set_status($field_value, $use_default);
128
-                break;
129
-            default:
130
-                parent::set($field_name, $field_value, $use_default);
131
-        }
132
-    }
133
-
134
-
135
-    /**
136
-     * Set Status ID
137
-     * updates the registration status and ALSO...
138
-     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
139
-     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
140
-     *
141
-     * @param string                $new_STS_ID
142
-     * @param boolean               $use_default
143
-     * @param ContextInterface|null $context
144
-     * @return bool
145
-     * @throws EE_Error
146
-     * @throws EntityNotFoundException
147
-     * @throws InvalidArgumentException
148
-     * @throws ReflectionException
149
-     * @throws RuntimeException
150
-     * @throws InvalidDataTypeException
151
-     * @throws InvalidInterfaceException
152
-     */
153
-    public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
154
-    {
155
-        // get current REG_Status
156
-        $old_STS_ID = $this->status_ID();
157
-        // if status has changed
158
-        if ($old_STS_ID !== $new_STS_ID // and that status has actually changed
159
-            && ! empty($old_STS_ID) // and that old status is actually set
160
-            && ! empty($new_STS_ID) // as well as the new status
161
-            && $this->ID() // ensure registration is in the db
162
-        ) {
163
-            // TO approved
164
-            if ($new_STS_ID === EEM_Registration::status_id_approved) {
165
-                // reserve a space by incrementing ticket and datetime sold values
166
-                $this->_reserve_registration_space();
167
-                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
168
-                // OR FROM  approved
169
-            } elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
170
-                // release a space by decrementing ticket and datetime sold values
171
-                $this->_release_registration_space();
172
-                do_action(
173
-                    'AHEE__EE_Registration__set_status__from_approved',
174
-                    $this,
175
-                    $old_STS_ID,
176
-                    $new_STS_ID,
177
-                    $context
178
-                );
179
-            }
180
-            // update status
181
-            parent::set('STS_ID', $new_STS_ID, $use_default);
182
-            $this->_update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, $context);
183
-            if ($this->statusChangeUpdatesTransaction($context)) {
184
-                $this->updateTransactionAfterStatusChange();
185
-            }
186
-            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
187
-            return true;
188
-        }
189
-        // even though the old value matches the new value, it's still good to
190
-        // allow the parent set method to have a say
191
-        parent::set('STS_ID', $new_STS_ID, $use_default);
192
-        return true;
193
-    }
194
-
195
-
196
-    /**
197
-     * update REGs and TXN when cancelled or declined registrations involved
198
-     *
199
-     * @param string                $new_STS_ID
200
-     * @param string                $old_STS_ID
201
-     * @param ContextInterface|null $context
202
-     * @throws EE_Error
203
-     * @throws InvalidArgumentException
204
-     * @throws InvalidDataTypeException
205
-     * @throws InvalidInterfaceException
206
-     * @throws ReflectionException
207
-     */
208
-    private function _update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
209
-    {
210
-        // these reg statuses should not be considered in any calculations involving monies owing
211
-        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
212
-        // true if registration has been cancelled or declined
213
-        $this->updateIfCanceled(
214
-            $closed_reg_statuses,
215
-            $new_STS_ID,
216
-            $old_STS_ID,
217
-            $context
218
-        );
219
-        $this->updateIfDeclined(
220
-            $closed_reg_statuses,
221
-            $new_STS_ID,
222
-            $old_STS_ID,
223
-            $context
224
-        );
225
-    }
226
-
227
-
228
-    /**
229
-     * update REGs and TXN when cancelled or declined registrations involved
230
-     *
231
-     * @param array                 $closed_reg_statuses
232
-     * @param string                $new_STS_ID
233
-     * @param string                $old_STS_ID
234
-     * @param ContextInterface|null $context
235
-     * @throws EE_Error
236
-     * @throws InvalidArgumentException
237
-     * @throws InvalidDataTypeException
238
-     * @throws InvalidInterfaceException
239
-     * @throws ReflectionException
240
-     */
241
-    private function updateIfCanceled(
242
-        array $closed_reg_statuses,
243
-        $new_STS_ID,
244
-        $old_STS_ID,
245
-        ContextInterface $context = null
246
-    ) {
247
-        // true if registration has been cancelled or declined
248
-        if (in_array($new_STS_ID, $closed_reg_statuses, true)
249
-            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
250
-        ) {
251
-            /** @type EE_Registration_Processor $registration_processor */
252
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
253
-            /** @type EE_Transaction_Processor $transaction_processor */
254
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
255
-            // cancelled or declined registration
256
-            $registration_processor->update_registration_after_being_canceled_or_declined(
257
-                $this,
258
-                $closed_reg_statuses
259
-            );
260
-            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
261
-                $this,
262
-                $closed_reg_statuses,
263
-                false
264
-            );
265
-            do_action(
266
-                'AHEE__EE_Registration__set_status__canceled_or_declined',
267
-                $this,
268
-                $old_STS_ID,
269
-                $new_STS_ID,
270
-                $context
271
-            );
272
-            return;
273
-        }
274
-    }
275
-
276
-
277
-    /**
278
-     * update REGs and TXN when cancelled or declined registrations involved
279
-     *
280
-     * @param array                 $closed_reg_statuses
281
-     * @param string                $new_STS_ID
282
-     * @param string                $old_STS_ID
283
-     * @param ContextInterface|null $context
284
-     * @throws EE_Error
285
-     * @throws InvalidArgumentException
286
-     * @throws InvalidDataTypeException
287
-     * @throws InvalidInterfaceException
288
-     * @throws ReflectionException
289
-     */
290
-    private function updateIfDeclined(
291
-        array $closed_reg_statuses,
292
-        $new_STS_ID,
293
-        $old_STS_ID,
294
-        ContextInterface $context = null
295
-    ) {
296
-        // true if reinstating cancelled or declined registration
297
-        if (in_array($old_STS_ID, $closed_reg_statuses, true)
298
-            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
299
-        ) {
300
-            /** @type EE_Registration_Processor $registration_processor */
301
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
302
-            /** @type EE_Transaction_Processor $transaction_processor */
303
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
304
-            // reinstating cancelled or declined registration
305
-            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
306
-                $this,
307
-                $closed_reg_statuses
308
-            );
309
-            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
310
-                $this,
311
-                $closed_reg_statuses,
312
-                false
313
-            );
314
-            do_action(
315
-                'AHEE__EE_Registration__set_status__after_reinstated',
316
-                $this,
317
-                $old_STS_ID,
318
-                $new_STS_ID,
319
-                $context
320
-            );
321
-        }
322
-    }
323
-
324
-
325
-    /**
326
-     * @param ContextInterface|null $context
327
-     * @return bool
328
-     */
329
-    private function statusChangeUpdatesTransaction(ContextInterface $context = null)
330
-    {
331
-        $contexts_that_do_not_update_transaction = (array) apply_filters(
332
-            'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
333
-            array('spco_reg_step_attendee_information_process_registrations'),
334
-            $context,
335
-            $this
336
-        );
337
-        return ! (
338
-            $context instanceof ContextInterface
339
-            && in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
340
-        );
341
-    }
342
-
343
-
344
-    /**
345
-     * @throws EE_Error
346
-     * @throws EntityNotFoundException
347
-     * @throws InvalidArgumentException
348
-     * @throws InvalidDataTypeException
349
-     * @throws InvalidInterfaceException
350
-     * @throws ReflectionException
351
-     * @throws RuntimeException
352
-     */
353
-    private function updateTransactionAfterStatusChange()
354
-    {
355
-        /** @type EE_Transaction_Payments $transaction_payments */
356
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
357
-        $transaction_payments->recalculate_transaction_total($this->transaction(), false);
358
-        $this->transaction()->update_status_based_on_total_paid(true);
359
-    }
360
-
361
-
362
-    /**
363
-     *        get Status ID
364
-     */
365
-    public function status_ID()
366
-    {
367
-        return $this->get('STS_ID');
368
-    }
369
-
370
-
371
-    /**
372
-     * Gets the ticket this registration is for
373
-     *
374
-     * @param boolean $include_archived whether to include archived tickets or not.
375
-     *
376
-     * @return EE_Ticket|EE_Base_Class
377
-     * @throws EE_Error
378
-     */
379
-    public function ticket($include_archived = true)
380
-    {
381
-        $query_params = array();
382
-        if ($include_archived) {
383
-            $query_params['default_where_conditions'] = 'none';
384
-        }
385
-        return $this->get_first_related('Ticket', $query_params);
386
-    }
387
-
388
-
389
-    /**
390
-     * Gets the event this registration is for
391
-     *
392
-     * @return EE_Event
393
-     * @throws EE_Error
394
-     * @throws EntityNotFoundException
395
-     */
396
-    public function event()
397
-    {
398
-        $event = $this->get_first_related('Event');
399
-        if (! $event instanceof \EE_Event) {
400
-            throw new EntityNotFoundException('Event ID', $this->event_ID());
401
-        }
402
-        return $event;
403
-    }
404
-
405
-
406
-    /**
407
-     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
408
-     * with the author of the event this registration is for.
409
-     *
410
-     * @since 4.5.0
411
-     * @return int
412
-     * @throws EE_Error
413
-     * @throws EntityNotFoundException
414
-     */
415
-    public function wp_user()
416
-    {
417
-        $event = $this->event();
418
-        if ($event instanceof EE_Event) {
419
-            return $event->wp_user();
420
-        }
421
-        return 0;
422
-    }
423
-
424
-
425
-    /**
426
-     * increments this registration's related ticket sold and corresponding datetime sold values
427
-     *
428
-     * @return void
429
-     * @throws DomainException
430
-     * @throws EE_Error
431
-     * @throws EntityNotFoundException
432
-     * @throws InvalidArgumentException
433
-     * @throws InvalidDataTypeException
434
-     * @throws InvalidInterfaceException
435
-     * @throws ReflectionException
436
-     * @throws UnexpectedEntityException
437
-     */
438
-    private function _reserve_registration_space()
439
-    {
440
-        // reserved ticket and datetime counts will be decremented as sold counts are incremented
441
-        // so stop tracking that this reg has a ticket reserved
442
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
443
-        $ticket = $this->ticket();
444
-        $ticket->increase_sold();
445
-        $ticket->save();
446
-        // possibly set event status to sold out
447
-        $this->event()->perform_sold_out_status_check();
448
-    }
449
-
450
-
451
-    /**
452
-     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
453
-     *
454
-     * @return void
455
-     * @throws DomainException
456
-     * @throws EE_Error
457
-     * @throws EntityNotFoundException
458
-     * @throws InvalidArgumentException
459
-     * @throws InvalidDataTypeException
460
-     * @throws InvalidInterfaceException
461
-     * @throws ReflectionException
462
-     * @throws UnexpectedEntityException
463
-     */
464
-    private function _release_registration_space()
465
-    {
466
-        $ticket = $this->ticket();
467
-        $ticket->decrease_sold();
468
-        $ticket->save();
469
-        // possibly change event status from sold out back to previous status
470
-        $this->event()->perform_sold_out_status_check();
471
-    }
472
-
473
-
474
-    /**
475
-     * tracks this registration's ticket reservation in extra meta
476
-     * and can increment related ticket reserved and corresponding datetime reserved values
477
-     *
478
-     * @param bool $update_ticket if true, will increment ticket and datetime reserved count
479
-     * @return void
480
-     * @throws EE_Error
481
-     * @throws InvalidArgumentException
482
-     * @throws InvalidDataTypeException
483
-     * @throws InvalidInterfaceException
484
-     * @throws ReflectionException
485
-     */
486
-    public function reserve_ticket($update_ticket = false, $source = 'unknown')
487
-    {
488
-        // only reserve ticket if space is not currently reserved
489
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
490
-            $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
491
-            // IMPORTANT !!!
492
-            // although checking $update_ticket first would be more efficient,
493
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
494
-            if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
495
-                && $update_ticket
496
-            ) {
497
-                $ticket = $this->ticket();
498
-                $ticket->increase_reserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
499
-                $ticket->save();
500
-            }
501
-        }
502
-    }
503
-
504
-
505
-    /**
506
-     * stops tracking this registration's ticket reservation in extra meta
507
-     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
508
-     *
509
-     * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
510
-     * @return void
511
-     * @throws EE_Error
512
-     * @throws InvalidArgumentException
513
-     * @throws InvalidDataTypeException
514
-     * @throws InvalidInterfaceException
515
-     * @throws ReflectionException
516
-     */
517
-    public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
518
-    {
519
-        // only release ticket if space is currently reserved
520
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
521
-            $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
522
-            // IMPORTANT !!!
523
-            // although checking $update_ticket first would be more efficient,
524
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
525
-            if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
526
-                && $update_ticket
527
-            ) {
528
-                $ticket = $this->ticket();
529
-                $ticket->decrease_reserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
530
-                $ticket->save();
531
-            }
532
-        }
533
-    }
534
-
535
-
536
-    /**
537
-     * Set Attendee ID
538
-     *
539
-     * @param        int $ATT_ID Attendee ID
540
-     * @throws EE_Error
541
-     * @throws RuntimeException
542
-     */
543
-    public function set_attendee_id($ATT_ID = 0)
544
-    {
545
-        $this->set('ATT_ID', $ATT_ID);
546
-    }
547
-
548
-
549
-    /**
550
-     *        Set Transaction ID
551
-     *
552
-     * @param        int $TXN_ID Transaction ID
553
-     * @throws EE_Error
554
-     * @throws RuntimeException
555
-     */
556
-    public function set_transaction_id($TXN_ID = 0)
557
-    {
558
-        $this->set('TXN_ID', $TXN_ID);
559
-    }
560
-
561
-
562
-    /**
563
-     *        Set Session
564
-     *
565
-     * @param    string $REG_session PHP Session ID
566
-     * @throws EE_Error
567
-     * @throws RuntimeException
568
-     */
569
-    public function set_session($REG_session = '')
570
-    {
571
-        $this->set('REG_session', $REG_session);
572
-    }
573
-
574
-
575
-    /**
576
-     *        Set Registration URL Link
577
-     *
578
-     * @param    string $REG_url_link Registration URL Link
579
-     * @throws EE_Error
580
-     * @throws RuntimeException
581
-     */
582
-    public function set_reg_url_link($REG_url_link = '')
583
-    {
584
-        $this->set('REG_url_link', $REG_url_link);
585
-    }
586
-
587
-
588
-    /**
589
-     *        Set Attendee Counter
590
-     *
591
-     * @param        int $REG_count Primary Attendee
592
-     * @throws EE_Error
593
-     * @throws RuntimeException
594
-     */
595
-    public function set_count($REG_count = 1)
596
-    {
597
-        $this->set('REG_count', $REG_count);
598
-    }
599
-
600
-
601
-    /**
602
-     *        Set Group Size
603
-     *
604
-     * @param        boolean $REG_group_size Group Registration
605
-     * @throws EE_Error
606
-     * @throws RuntimeException
607
-     */
608
-    public function set_group_size($REG_group_size = false)
609
-    {
610
-        $this->set('REG_group_size', $REG_group_size);
611
-    }
612
-
613
-
614
-    /**
615
-     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
616
-     *    EEM_Registration::status_id_not_approved
617
-     *
618
-     * @return        boolean
619
-     */
620
-    public function is_not_approved()
621
-    {
622
-        return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
623
-    }
624
-
625
-
626
-    /**
627
-     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
628
-     *    EEM_Registration::status_id_pending_payment
629
-     *
630
-     * @return        boolean
631
-     */
632
-    public function is_pending_payment()
633
-    {
634
-        return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
635
-    }
636
-
637
-
638
-    /**
639
-     *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
640
-     *
641
-     * @return        boolean
642
-     */
643
-    public function is_approved()
644
-    {
645
-        return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
646
-    }
647
-
648
-
649
-    /**
650
-     *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
651
-     *
652
-     * @return        boolean
653
-     */
654
-    public function is_cancelled()
655
-    {
656
-        return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
657
-    }
658
-
659
-
660
-    /**
661
-     *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
662
-     *
663
-     * @return        boolean
664
-     */
665
-    public function is_declined()
666
-    {
667
-        return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
668
-    }
669
-
670
-
671
-    /**
672
-     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
673
-     *    EEM_Registration::status_id_incomplete
674
-     *
675
-     * @return        boolean
676
-     */
677
-    public function is_incomplete()
678
-    {
679
-        return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
680
-    }
681
-
682
-
683
-    /**
684
-     *        Set Registration Date
685
-     *
686
-     * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
687
-     *                                                 Date
688
-     * @throws EE_Error
689
-     * @throws RuntimeException
690
-     */
691
-    public function set_reg_date($REG_date = false)
692
-    {
693
-        $this->set('REG_date', $REG_date);
694
-    }
695
-
696
-
697
-    /**
698
-     *    Set final price owing for this registration after all ticket/price modifications
699
-     *
700
-     * @access    public
701
-     * @param    float $REG_final_price
702
-     * @throws EE_Error
703
-     * @throws RuntimeException
704
-     */
705
-    public function set_final_price($REG_final_price = 0.00)
706
-    {
707
-        $this->set('REG_final_price', $REG_final_price);
708
-    }
709
-
710
-
711
-    /**
712
-     *    Set amount paid towards this registration's final price
713
-     *
714
-     * @access    public
715
-     * @param    float $REG_paid
716
-     * @throws EE_Error
717
-     * @throws RuntimeException
718
-     */
719
-    public function set_paid($REG_paid = 0.00)
720
-    {
721
-        $this->set('REG_paid', $REG_paid);
722
-    }
723
-
724
-
725
-    /**
726
-     *        Attendee Is Going
727
-     *
728
-     * @param        boolean $REG_att_is_going Attendee Is Going
729
-     * @throws EE_Error
730
-     * @throws RuntimeException
731
-     */
732
-    public function set_att_is_going($REG_att_is_going = false)
733
-    {
734
-        $this->set('REG_att_is_going', $REG_att_is_going);
735
-    }
736
-
737
-
738
-    /**
739
-     * Gets the related attendee
740
-     *
741
-     * @return EE_Attendee
742
-     * @throws EE_Error
743
-     */
744
-    public function attendee()
745
-    {
746
-        return $this->get_first_related('Attendee');
747
-    }
748
-
749
-
750
-    /**
751
-     *        get Event ID
752
-     */
753
-    public function event_ID()
754
-    {
755
-        return $this->get('EVT_ID');
756
-    }
757
-
758
-
759
-    /**
760
-     *        get Event ID
761
-     */
762
-    public function event_name()
763
-    {
764
-        $event = $this->event_obj();
765
-        if ($event) {
766
-            return $event->name();
767
-        } else {
768
-            return null;
769
-        }
770
-    }
771
-
772
-
773
-    /**
774
-     * Fetches the event this registration is for
775
-     *
776
-     * @return EE_Event
777
-     * @throws EE_Error
778
-     */
779
-    public function event_obj()
780
-    {
781
-        return $this->get_first_related('Event');
782
-    }
783
-
784
-
785
-    /**
786
-     *        get Attendee ID
787
-     */
788
-    public function attendee_ID()
789
-    {
790
-        return $this->get('ATT_ID');
791
-    }
792
-
793
-
794
-    /**
795
-     *        get PHP Session ID
796
-     */
797
-    public function session_ID()
798
-    {
799
-        return $this->get('REG_session');
800
-    }
801
-
802
-
803
-    /**
804
-     * Gets the string which represents the URL trigger for the receipt template in the message template system.
805
-     *
806
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
807
-     * @return string
808
-     */
809
-    public function receipt_url($messenger = 'html')
810
-    {
811
-
812
-        /**
813
-         * The below will be deprecated one version after this.  We check first if there is a custom receipt template
814
-         * already in use on old system.  If there is then we just return the standard url for it.
815
-         *
816
-         * @since 4.5.0
817
-         */
818
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
819
-        $has_custom = EEH_Template::locate_template(
820
-            $template_relative_path,
821
-            array(),
822
-            true,
823
-            true,
824
-            true
825
-        );
826
-
827
-        if ($has_custom) {
828
-            return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
829
-        }
830
-        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
831
-    }
832
-
833
-
834
-    /**
835
-     * Gets the string which represents the URL trigger for the invoice template in the message template system.
836
-     *
837
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
838
-     * @return string
839
-     * @throws EE_Error
840
-     */
841
-    public function invoice_url($messenger = 'html')
842
-    {
843
-        /**
844
-         * The below will be deprecated one version after this.  We check first if there is a custom invoice template
845
-         * already in use on old system.  If there is then we just return the standard url for it.
846
-         *
847
-         * @since 4.5.0
848
-         */
849
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
850
-        $has_custom = EEH_Template::locate_template(
851
-            $template_relative_path,
852
-            array(),
853
-            true,
854
-            true,
855
-            true
856
-        );
857
-
858
-        if ($has_custom) {
859
-            if ($messenger == 'html') {
860
-                return $this->invoice_url('launch');
861
-            }
862
-            $route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
863
-
864
-            $query_args = array('ee' => $route, 'id' => $this->reg_url_link());
865
-            if ($messenger == 'html') {
866
-                $query_args['html'] = true;
867
-            }
868
-            return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
869
-        }
870
-        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
871
-    }
872
-
873
-
874
-    /**
875
-     * get Registration URL Link
876
-     *
877
-     * @access public
878
-     * @return string
879
-     * @throws EE_Error
880
-     */
881
-    public function reg_url_link()
882
-    {
883
-        return (string) $this->get('REG_url_link');
884
-    }
885
-
886
-
887
-    /**
888
-     * Echoes out invoice_url()
889
-     *
890
-     * @param string $type 'download','launch', or 'html' (default is 'launch')
891
-     * @return void
892
-     * @throws EE_Error
893
-     */
894
-    public function e_invoice_url($type = 'launch')
895
-    {
896
-        echo $this->invoice_url($type);
897
-    }
898
-
899
-
900
-    /**
901
-     * Echoes out payment_overview_url
902
-     */
903
-    public function e_payment_overview_url()
904
-    {
905
-        echo $this->payment_overview_url();
906
-    }
907
-
908
-
909
-    /**
910
-     * Gets the URL for the checkout payment options reg step
911
-     * with this registration's REG_url_link added as a query parameter
912
-     *
913
-     * @param bool $clear_session Set to true when you want to clear the session on revisiting the
914
-     *                            payment overview url.
915
-     * @return string
916
-     * @throws InvalidInterfaceException
917
-     * @throws InvalidDataTypeException
918
-     * @throws EE_Error
919
-     * @throws InvalidArgumentException
920
-     */
921
-    public function payment_overview_url($clear_session = false)
922
-    {
923
-        return add_query_arg(
924
-            (array) apply_filters(
925
-                'FHEE__EE_Registration__payment_overview_url__query_args',
926
-                array(
927
-                    'e_reg_url_link' => $this->reg_url_link(),
928
-                    'step'           => 'payment_options',
929
-                    'revisit'        => true,
930
-                    'clear_session'  => (bool) $clear_session,
931
-                ),
932
-                $this
933
-            ),
934
-            EE_Registry::instance()->CFG->core->reg_page_url()
935
-        );
936
-    }
937
-
938
-
939
-    /**
940
-     * Gets the URL for the checkout attendee information reg step
941
-     * with this registration's REG_url_link added as a query parameter
942
-     *
943
-     * @return string
944
-     * @throws InvalidInterfaceException
945
-     * @throws InvalidDataTypeException
946
-     * @throws EE_Error
947
-     * @throws InvalidArgumentException
948
-     */
949
-    public function edit_attendee_information_url()
950
-    {
951
-        return add_query_arg(
952
-            (array) apply_filters(
953
-                'FHEE__EE_Registration__edit_attendee_information_url__query_args',
954
-                array(
955
-                    'e_reg_url_link' => $this->reg_url_link(),
956
-                    'step'           => 'attendee_information',
957
-                    'revisit'        => true,
958
-                ),
959
-                $this
960
-            ),
961
-            EE_Registry::instance()->CFG->core->reg_page_url()
962
-        );
963
-    }
964
-
965
-
966
-    /**
967
-     * Simply generates and returns the appropriate admin_url link to edit this registration
968
-     *
969
-     * @return string
970
-     * @throws EE_Error
971
-     */
972
-    public function get_admin_edit_url()
973
-    {
974
-        return EEH_URL::add_query_args_and_nonce(
975
-            array(
976
-                'page'    => 'espresso_registrations',
977
-                'action'  => 'view_registration',
978
-                '_REG_ID' => $this->ID(),
979
-            ),
980
-            admin_url('admin.php')
981
-        );
982
-    }
983
-
984
-
985
-    /**
986
-     *    is_primary_registrant?
987
-     */
988
-    public function is_primary_registrant()
989
-    {
990
-        return $this->get('REG_count') == 1 ? true : false;
991
-    }
992
-
993
-
994
-    /**
995
-     * This returns the primary registration object for this registration group (which may be this object).
996
-     *
997
-     * @return EE_Registration
998
-     * @throws EE_Error
999
-     */
1000
-    public function get_primary_registration()
1001
-    {
1002
-        if ($this->is_primary_registrant()) {
1003
-            return $this;
1004
-        }
1005
-
1006
-        // k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1007
-        /** @var EE_Registration $primary_registrant */
1008
-        $primary_registrant = EEM_Registration::instance()->get_one(
1009
-            array(
1010
-                array(
1011
-                    'TXN_ID'    => $this->transaction_ID(),
1012
-                    'REG_count' => 1,
1013
-                ),
1014
-            )
1015
-        );
1016
-        return $primary_registrant;
1017
-    }
1018
-
1019
-
1020
-    /**
1021
-     *        get  Attendee Number
1022
-     *
1023
-     * @access        public
1024
-     */
1025
-    public function count()
1026
-    {
1027
-        return $this->get('REG_count');
1028
-    }
1029
-
1030
-
1031
-    /**
1032
-     *        get Group Size
1033
-     */
1034
-    public function group_size()
1035
-    {
1036
-        return $this->get('REG_group_size');
1037
-    }
1038
-
1039
-
1040
-    /**
1041
-     *        get Registration Date
1042
-     */
1043
-    public function date()
1044
-    {
1045
-        return $this->get('REG_date');
1046
-    }
1047
-
1048
-
1049
-    /**
1050
-     * gets a pretty date
1051
-     *
1052
-     * @param string $date_format
1053
-     * @param string $time_format
1054
-     * @return string
1055
-     * @throws EE_Error
1056
-     */
1057
-    public function pretty_date($date_format = null, $time_format = null)
1058
-    {
1059
-        return $this->get_datetime('REG_date', $date_format, $time_format);
1060
-    }
1061
-
1062
-
1063
-    /**
1064
-     * final_price
1065
-     * the registration's share of the transaction total, so that the
1066
-     * sum of all the transaction's REG_final_prices equal the transaction's total
1067
-     *
1068
-     * @return float
1069
-     * @throws EE_Error
1070
-     */
1071
-    public function final_price()
1072
-    {
1073
-        return $this->get('REG_final_price');
1074
-    }
1075
-
1076
-
1077
-    /**
1078
-     * pretty_final_price
1079
-     *  final price as formatted string, with correct decimal places and currency symbol
1080
-     *
1081
-     * @return string
1082
-     * @throws EE_Error
1083
-     */
1084
-    public function pretty_final_price()
1085
-    {
1086
-        return $this->get_pretty('REG_final_price');
1087
-    }
1088
-
1089
-
1090
-    /**
1091
-     * get paid (yeah)
1092
-     *
1093
-     * @return float
1094
-     * @throws EE_Error
1095
-     */
1096
-    public function paid()
1097
-    {
1098
-        return $this->get('REG_paid');
1099
-    }
1100
-
1101
-
1102
-    /**
1103
-     * pretty_paid
1104
-     *
1105
-     * @return float
1106
-     * @throws EE_Error
1107
-     */
1108
-    public function pretty_paid()
1109
-    {
1110
-        return $this->get_pretty('REG_paid');
1111
-    }
1112
-
1113
-
1114
-    /**
1115
-     * owes_monies_and_can_pay
1116
-     * whether or not this registration has monies owing and it's' status allows payment
1117
-     *
1118
-     * @param array $requires_payment
1119
-     * @return bool
1120
-     * @throws EE_Error
1121
-     */
1122
-    public function owes_monies_and_can_pay($requires_payment = array())
1123
-    {
1124
-        // these reg statuses require payment (if event is not free)
1125
-        $requires_payment = ! empty($requires_payment)
1126
-            ? $requires_payment
1127
-            : EEM_Registration::reg_statuses_that_allow_payment();
1128
-        if (in_array($this->status_ID(), $requires_payment) &&
1129
-            $this->final_price() != 0 &&
1130
-            $this->final_price() != $this->paid()
1131
-        ) {
1132
-            return true;
1133
-        } else {
1134
-            return false;
1135
-        }
1136
-    }
1137
-
1138
-
1139
-    /**
1140
-     * Prints out the return value of $this->pretty_status()
1141
-     *
1142
-     * @param bool $show_icons
1143
-     * @return void
1144
-     * @throws EE_Error
1145
-     */
1146
-    public function e_pretty_status($show_icons = false)
1147
-    {
1148
-        echo $this->pretty_status($show_icons);
1149
-    }
1150
-
1151
-
1152
-    /**
1153
-     * Returns a nice version of the status for displaying to customers
1154
-     *
1155
-     * @param bool $show_icons
1156
-     * @return string
1157
-     * @throws EE_Error
1158
-     */
1159
-    public function pretty_status($show_icons = false)
1160
-    {
1161
-        $status = EEM_Status::instance()->localized_status(
1162
-            array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1163
-            false,
1164
-            'sentence'
1165
-        );
1166
-        $icon = '';
1167
-        switch ($this->status_ID()) {
1168
-            case EEM_Registration::status_id_approved:
1169
-                $icon = $show_icons
1170
-                    ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1171
-                    : '';
1172
-                break;
1173
-            case EEM_Registration::status_id_pending_payment:
1174
-                $icon = $show_icons
1175
-                    ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1176
-                    : '';
1177
-                break;
1178
-            case EEM_Registration::status_id_not_approved:
1179
-                $icon = $show_icons
1180
-                    ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1181
-                    : '';
1182
-                break;
1183
-            case EEM_Registration::status_id_cancelled:
1184
-                $icon = $show_icons
1185
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1186
-                    : '';
1187
-                break;
1188
-            case EEM_Registration::status_id_incomplete:
1189
-                $icon = $show_icons
1190
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1191
-                    : '';
1192
-                break;
1193
-            case EEM_Registration::status_id_declined:
1194
-                $icon = $show_icons
1195
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1196
-                    : '';
1197
-                break;
1198
-            case EEM_Registration::status_id_wait_list:
1199
-                $icon = $show_icons
1200
-                    ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1201
-                    : '';
1202
-                break;
1203
-        }
1204
-        return $icon . $status[ $this->status_ID() ];
1205
-    }
1206
-
1207
-
1208
-    /**
1209
-     *        get Attendee Is Going
1210
-     */
1211
-    public function att_is_going()
1212
-    {
1213
-        return $this->get('REG_att_is_going');
1214
-    }
1215
-
1216
-
1217
-    /**
1218
-     * Gets related answers
1219
-     *
1220
-     * @param array $query_params like EEM_Base::get_all
1221
-     * @return EE_Answer[]
1222
-     * @throws EE_Error
1223
-     */
1224
-    public function answers($query_params = null)
1225
-    {
1226
-        return $this->get_many_related('Answer', $query_params);
1227
-    }
1228
-
1229
-
1230
-    /**
1231
-     * Gets the registration's answer value to the specified question
1232
-     * (either the question's ID or a question object)
1233
-     *
1234
-     * @param EE_Question|int $question
1235
-     * @param bool            $pretty_value
1236
-     * @return array|string if pretty_value= true, the result will always be a string
1237
-     * (because the answer might be an array of answer values, so passing pretty_value=true
1238
-     * will convert it into some kind of string)
1239
-     * @throws EE_Error
1240
-     */
1241
-    public function answer_value_to_question($question, $pretty_value = true)
1242
-    {
1243
-        $question_id = EEM_Question::instance()->ensure_is_ID($question);
1244
-        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1245
-    }
1246
-
1247
-
1248
-    /**
1249
-     * question_groups
1250
-     * returns an array of EE_Question_Group objects for this registration
1251
-     *
1252
-     * @return EE_Question_Group[]
1253
-     * @throws EE_Error
1254
-     * @throws EntityNotFoundException
1255
-     */
1256
-    public function question_groups()
1257
-    {
1258
-        $question_groups = array();
1259
-        if ($this->event() instanceof EE_Event) {
1260
-            $question_groups = $this->event()->question_groups(
1261
-                array(
1262
-                    array(
1263
-                        'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1264
-                    ),
1265
-                    'order_by' => array('QSG_order' => 'ASC'),
1266
-                )
1267
-            );
1268
-        }
1269
-        return $question_groups;
1270
-    }
1271
-
1272
-
1273
-    /**
1274
-     * count_question_groups
1275
-     * returns a count of the number of EE_Question_Group objects for this registration
1276
-     *
1277
-     * @return int
1278
-     * @throws EE_Error
1279
-     * @throws EntityNotFoundException
1280
-     */
1281
-    public function count_question_groups()
1282
-    {
1283
-        $qg_count = 0;
1284
-        if ($this->event() instanceof EE_Event) {
1285
-            $qg_count = $this->event()->count_related(
1286
-                'Question_Group',
1287
-                array(
1288
-                    array(
1289
-                        'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1290
-                    ),
1291
-                )
1292
-            );
1293
-        }
1294
-        return $qg_count;
1295
-    }
1296
-
1297
-
1298
-    /**
1299
-     * Returns the registration date in the 'standard' string format
1300
-     * (function may be improved in the future to allow for different formats and timezones)
1301
-     *
1302
-     * @return string
1303
-     * @throws EE_Error
1304
-     */
1305
-    public function reg_date()
1306
-    {
1307
-        return $this->get_datetime('REG_date');
1308
-    }
1309
-
1310
-
1311
-    /**
1312
-     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1313
-     * the ticket this registration purchased, or the datetime they have registered
1314
-     * to attend)
1315
-     *
1316
-     * @return EE_Datetime_Ticket
1317
-     * @throws EE_Error
1318
-     */
1319
-    public function datetime_ticket()
1320
-    {
1321
-        return $this->get_first_related('Datetime_Ticket');
1322
-    }
1323
-
1324
-
1325
-    /**
1326
-     * Sets the registration's datetime_ticket.
1327
-     *
1328
-     * @param EE_Datetime_Ticket $datetime_ticket
1329
-     * @return EE_Datetime_Ticket
1330
-     * @throws EE_Error
1331
-     */
1332
-    public function set_datetime_ticket($datetime_ticket)
1333
-    {
1334
-        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1335
-    }
1336
-
1337
-    /**
1338
-     * Gets deleted
1339
-     *
1340
-     * @return bool
1341
-     * @throws EE_Error
1342
-     */
1343
-    public function deleted()
1344
-    {
1345
-        return $this->get('REG_deleted');
1346
-    }
1347
-
1348
-    /**
1349
-     * Sets deleted
1350
-     *
1351
-     * @param boolean $deleted
1352
-     * @return bool
1353
-     * @throws EE_Error
1354
-     * @throws RuntimeException
1355
-     */
1356
-    public function set_deleted($deleted)
1357
-    {
1358
-        if ($deleted) {
1359
-            $this->delete();
1360
-        } else {
1361
-            $this->restore();
1362
-        }
1363
-    }
1364
-
1365
-
1366
-    /**
1367
-     * Get the status object of this object
1368
-     *
1369
-     * @return EE_Status
1370
-     * @throws EE_Error
1371
-     */
1372
-    public function status_obj()
1373
-    {
1374
-        return $this->get_first_related('Status');
1375
-    }
1376
-
1377
-
1378
-    /**
1379
-     * Returns the number of times this registration has checked into any of the datetimes
1380
-     * its available for
1381
-     *
1382
-     * @return int
1383
-     * @throws EE_Error
1384
-     */
1385
-    public function count_checkins()
1386
-    {
1387
-        return $this->get_model()->count_related($this, 'Checkin');
1388
-    }
1389
-
1390
-
1391
-    /**
1392
-     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1393
-     * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1394
-     *
1395
-     * @return int
1396
-     * @throws EE_Error
1397
-     */
1398
-    public function count_checkins_not_checkedout()
1399
-    {
1400
-        return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1401
-    }
1402
-
1403
-
1404
-    /**
1405
-     * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1406
-     *
1407
-     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1408
-     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1409
-     *                                          consider registration status as well as datetime access.
1410
-     * @return bool
1411
-     * @throws EE_Error
1412
-     */
1413
-    public function can_checkin($DTT_OR_ID, $check_approved = true)
1414
-    {
1415
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1416
-
1417
-        // first check registration status
1418
-        if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1419
-            return false;
1420
-        }
1421
-        // is there a datetime ticket that matches this dtt_ID?
1422
-        if (! (EEM_Datetime_Ticket::instance()->exists(
1423
-            array(
1424
-                array(
1425
-                    'TKT_ID' => $this->get('TKT_ID'),
1426
-                    'DTT_ID' => $DTT_ID,
1427
-                ),
1428
-            )
1429
-        ))
1430
-        ) {
1431
-            return false;
1432
-        }
1433
-
1434
-        // final check is against TKT_uses
1435
-        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1436
-    }
1437
-
1438
-
1439
-    /**
1440
-     * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1441
-     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1442
-     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1443
-     * then return false.  Otherwise return true.
1444
-     *
1445
-     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1446
-     * @return bool true means can checkin.  false means cannot checkin.
1447
-     * @throws EE_Error
1448
-     */
1449
-    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1450
-    {
1451
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1452
-
1453
-        if (! $DTT_ID) {
1454
-            return false;
1455
-        }
1456
-
1457
-        $max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1458
-
1459
-        // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1460
-        // check-in or not.
1461
-        if (! $max_uses || $max_uses === EE_INF) {
1462
-            return true;
1463
-        }
1464
-
1465
-        // does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1466
-        // go ahead and toggle.
1467
-        if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1468
-            return true;
1469
-        }
1470
-
1471
-        // made it here so the last check is whether the number of checkins per unique datetime on this registration
1472
-        // disallows further check-ins.
1473
-        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1474
-            array(
1475
-                array(
1476
-                    'REG_ID' => $this->ID(),
1477
-                    'CHK_in' => true,
1478
-                ),
1479
-            ),
1480
-            'DTT_ID',
1481
-            true
1482
-        );
1483
-        // checkins have already reached their max number of uses
1484
-        // so registrant can NOT checkin
1485
-        if ($count_unique_dtt_checkins >= $max_uses) {
1486
-            EE_Error::add_error(
1487
-                esc_html__(
1488
-                    'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1489
-                    'event_espresso'
1490
-                ),
1491
-                __FILE__,
1492
-                __FUNCTION__,
1493
-                __LINE__
1494
-            );
1495
-            return false;
1496
-        }
1497
-        return true;
1498
-    }
1499
-
1500
-
1501
-    /**
1502
-     * toggle Check-in status for this registration
1503
-     * Check-ins are toggled in the following order:
1504
-     * never checked in -> checked in
1505
-     * checked in -> checked out
1506
-     * checked out -> checked in
1507
-     *
1508
-     * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1509
-     *                      If not included or null, then it is assumed latest datetime is being toggled.
1510
-     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1511
-     *                      can be checked in or not.  Otherwise this forces change in checkin status.
1512
-     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1513
-     * @throws EE_Error
1514
-     */
1515
-    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1516
-    {
1517
-        if (empty($DTT_ID)) {
1518
-            $datetime = $this->get_latest_related_datetime();
1519
-            $DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1520
-            // verify the registration can checkin for the given DTT_ID
1521
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1522
-            EE_Error::add_error(
1523
-                sprintf(
1524
-                    esc_html__(
1525
-                        'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1526
-                        'event_espresso'
1527
-                    ),
1528
-                    $this->ID(),
1529
-                    $DTT_ID
1530
-                ),
1531
-                __FILE__,
1532
-                __FUNCTION__,
1533
-                __LINE__
1534
-            );
1535
-            return false;
1536
-        }
1537
-        $status_paths = array(
1538
-            EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1539
-            EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1540
-            EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1541
-        );
1542
-        // start by getting the current status so we know what status we'll be changing to.
1543
-        $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1544
-        $status_to = $status_paths[ $cur_status ];
1545
-        // database only records true for checked IN or false for checked OUT
1546
-        // no record ( null ) means checked in NEVER, but we obviously don't save that
1547
-        $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1548
-        // add relation - note Check-ins are always creating new rows
1549
-        // because we are keeping track of Check-ins over time.
1550
-        // Eventually we'll probably want to show a list table
1551
-        // for the individual Check-ins so that they can be managed.
1552
-        $checkin = EE_Checkin::new_instance(
1553
-            array(
1554
-                'REG_ID' => $this->ID(),
1555
-                'DTT_ID' => $DTT_ID,
1556
-                'CHK_in' => $new_status,
1557
-            )
1558
-        );
1559
-        // if the record could not be saved then return false
1560
-        if ($checkin->save() === 0) {
1561
-            if (WP_DEBUG) {
1562
-                global $wpdb;
1563
-                $error = sprintf(
1564
-                    esc_html__(
1565
-                        'Registration check in update failed because of the following database error: %1$s%2$s',
1566
-                        'event_espresso'
1567
-                    ),
1568
-                    '<br />',
1569
-                    $wpdb->last_error
1570
-                );
1571
-            } else {
1572
-                $error = esc_html__(
1573
-                    'Registration check in update failed because of an unknown database error',
1574
-                    'event_espresso'
1575
-                );
1576
-            }
1577
-            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1578
-            return false;
1579
-        }
1580
-        return $status_to;
1581
-    }
1582
-
1583
-
1584
-    /**
1585
-     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1586
-     * "Latest" is defined by the `DTT_EVT_start` column.
1587
-     *
1588
-     * @return EE_Datetime|null
1589
-     * @throws EE_Error
1590
-     */
1591
-    public function get_latest_related_datetime()
1592
-    {
1593
-        return EEM_Datetime::instance()->get_one(
1594
-            array(
1595
-                array(
1596
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1597
-                ),
1598
-                'order_by' => array('DTT_EVT_start' => 'DESC'),
1599
-            )
1600
-        );
1601
-    }
1602
-
1603
-
1604
-    /**
1605
-     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1606
-     * "Earliest" is defined by the `DTT_EVT_start` column.
1607
-     *
1608
-     * @throws EE_Error
1609
-     */
1610
-    public function get_earliest_related_datetime()
1611
-    {
1612
-        return EEM_Datetime::instance()->get_one(
1613
-            array(
1614
-                array(
1615
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1616
-                ),
1617
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
1618
-            )
1619
-        );
1620
-    }
1621
-
1622
-
1623
-    /**
1624
-     * This method simply returns the check-in status for this registration and the given datetime.
1625
-     * If neither the datetime nor the checkin values are provided as arguments,
1626
-     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1627
-     *
1628
-     * @param  int       $DTT_ID  The ID of the datetime we're checking against
1629
-     *                            (if empty we'll get the primary datetime for
1630
-     *                            this registration (via event) and use it's ID);
1631
-     * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1632
-     *
1633
-     * @return int                Integer representing Check-in status.
1634
-     * @throws EE_Error
1635
-     */
1636
-    public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1637
-    {
1638
-        $checkin_query_params = array(
1639
-            'order_by' => array('CHK_timestamp' => 'DESC'),
1640
-        );
1641
-
1642
-        if ($DTT_ID > 0) {
1643
-            $checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1644
-        }
1645
-
1646
-        // get checkin object (if exists)
1647
-        $checkin = $checkin instanceof EE_Checkin
1648
-            ? $checkin
1649
-            : $this->get_first_related('Checkin', $checkin_query_params);
1650
-        if ($checkin instanceof EE_Checkin) {
1651
-            if ($checkin->get('CHK_in')) {
1652
-                return EE_Checkin::status_checked_in; // checked in
1653
-            }
1654
-            return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1655
-        }
1656
-        return EE_Checkin::status_checked_never; // never been checked in
1657
-    }
1658
-
1659
-
1660
-    /**
1661
-     * This method returns a localized message for the toggled Check-in message.
1662
-     *
1663
-     * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1664
-     *                     then it is assumed Check-in for primary datetime was toggled.
1665
-     * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1666
-     *                     message can be customized with the attendee name.
1667
-     * @return string internationalized message
1668
-     * @throws EE_Error
1669
-     */
1670
-    public function get_checkin_msg($DTT_ID, $error = false)
1671
-    {
1672
-        // let's get the attendee first so we can include the name of the attendee
1673
-        $attendee = $this->get_first_related('Attendee');
1674
-        if ($attendee instanceof EE_Attendee) {
1675
-            if ($error) {
1676
-                return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1677
-            }
1678
-            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1679
-            // what is the status message going to be?
1680
-            switch ($cur_status) {
1681
-                case EE_Checkin::status_checked_never:
1682
-                    return sprintf(
1683
-                        __("%s has been removed from Check-in records", "event_espresso"),
1684
-                        $attendee->full_name()
1685
-                    );
1686
-                    break;
1687
-                case EE_Checkin::status_checked_in:
1688
-                    return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1689
-                    break;
1690
-                case EE_Checkin::status_checked_out:
1691
-                    return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1692
-                    break;
1693
-            }
1694
-        }
1695
-        return esc_html__("The check-in status could not be determined.", "event_espresso");
1696
-    }
1697
-
1698
-
1699
-    /**
1700
-     * Returns the related EE_Transaction to this registration
1701
-     *
1702
-     * @return EE_Transaction
1703
-     * @throws EE_Error
1704
-     * @throws EntityNotFoundException
1705
-     */
1706
-    public function transaction()
1707
-    {
1708
-        $transaction = $this->get_first_related('Transaction');
1709
-        if (! $transaction instanceof \EE_Transaction) {
1710
-            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1711
-        }
1712
-        return $transaction;
1713
-    }
1714
-
1715
-
1716
-    /**
1717
-     *        get Registration Code
1718
-     */
1719
-    public function reg_code()
1720
-    {
1721
-        return $this->get('REG_code');
1722
-    }
1723
-
1724
-
1725
-    /**
1726
-     *        get Transaction ID
1727
-     */
1728
-    public function transaction_ID()
1729
-    {
1730
-        return $this->get('TXN_ID');
1731
-    }
1732
-
1733
-
1734
-    /**
1735
-     * @return int
1736
-     * @throws EE_Error
1737
-     */
1738
-    public function ticket_ID()
1739
-    {
1740
-        return $this->get('TKT_ID');
1741
-    }
1742
-
1743
-
1744
-    /**
1745
-     *        Set Registration Code
1746
-     *
1747
-     * @access    public
1748
-     * @param    string  $REG_code Registration Code
1749
-     * @param    boolean $use_default
1750
-     * @throws EE_Error
1751
-     */
1752
-    public function set_reg_code($REG_code, $use_default = false)
1753
-    {
1754
-        if (empty($REG_code)) {
1755
-            EE_Error::add_error(
1756
-                esc_html__('REG_code can not be empty.', 'event_espresso'),
1757
-                __FILE__,
1758
-                __FUNCTION__,
1759
-                __LINE__
1760
-            );
1761
-            return;
1762
-        }
1763
-        if (! $this->reg_code()) {
1764
-            parent::set('REG_code', $REG_code, $use_default);
1765
-        } else {
1766
-            EE_Error::doing_it_wrong(
1767
-                __CLASS__ . '::' . __FUNCTION__,
1768
-                esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1769
-                '4.6.0'
1770
-            );
1771
-        }
1772
-    }
1773
-
1774
-
1775
-    /**
1776
-     * Returns all other registrations in the same group as this registrant who have the same ticket option.
1777
-     * Note, if you want to just get all registrations in the same transaction (group), use:
1778
-     *    $registration->transaction()->registrations();
1779
-     *
1780
-     * @since 4.5.0
1781
-     * @return EE_Registration[] or empty array if this isn't a group registration.
1782
-     * @throws EE_Error
1783
-     */
1784
-    public function get_all_other_registrations_in_group()
1785
-    {
1786
-        if ($this->group_size() < 2) {
1787
-            return array();
1788
-        }
1789
-
1790
-        $query[0] = array(
1791
-            'TXN_ID' => $this->transaction_ID(),
1792
-            'REG_ID' => array('!=', $this->ID()),
1793
-            'TKT_ID' => $this->ticket_ID(),
1794
-        );
1795
-        /** @var EE_Registration[] $registrations */
1796
-        $registrations = $this->get_model()->get_all($query);
1797
-        return $registrations;
1798
-    }
1799
-
1800
-    /**
1801
-     * Return the link to the admin details for the object.
1802
-     *
1803
-     * @return string
1804
-     * @throws EE_Error
1805
-     */
1806
-    public function get_admin_details_link()
1807
-    {
1808
-        EE_Registry::instance()->load_helper('URL');
1809
-        return EEH_URL::add_query_args_and_nonce(
1810
-            array(
1811
-                'page'    => 'espresso_registrations',
1812
-                'action'  => 'view_registration',
1813
-                '_REG_ID' => $this->ID(),
1814
-            ),
1815
-            admin_url('admin.php')
1816
-        );
1817
-    }
1818
-
1819
-    /**
1820
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1821
-     *
1822
-     * @return string
1823
-     * @throws EE_Error
1824
-     */
1825
-    public function get_admin_edit_link()
1826
-    {
1827
-        return $this->get_admin_details_link();
1828
-    }
1829
-
1830
-    /**
1831
-     * Returns the link to a settings page for the object.
1832
-     *
1833
-     * @return string
1834
-     * @throws EE_Error
1835
-     */
1836
-    public function get_admin_settings_link()
1837
-    {
1838
-        return $this->get_admin_details_link();
1839
-    }
1840
-
1841
-    /**
1842
-     * Returns the link to the "overview" for the object (typically the "list table" view).
1843
-     *
1844
-     * @return string
1845
-     */
1846
-    public function get_admin_overview_link()
1847
-    {
1848
-        EE_Registry::instance()->load_helper('URL');
1849
-        return EEH_URL::add_query_args_and_nonce(
1850
-            array(
1851
-                'page' => 'espresso_registrations',
1852
-            ),
1853
-            admin_url('admin.php')
1854
-        );
1855
-    }
1856
-
1857
-
1858
-    /**
1859
-     * @param array $query_params
1860
-     *
1861
-     * @return \EE_Registration[]
1862
-     * @throws EE_Error
1863
-     */
1864
-    public function payments($query_params = array())
1865
-    {
1866
-        return $this->get_many_related('Payment', $query_params);
1867
-    }
1868
-
1869
-
1870
-    /**
1871
-     * @param array $query_params
1872
-     *
1873
-     * @return \EE_Registration_Payment[]
1874
-     * @throws EE_Error
1875
-     */
1876
-    public function registration_payments($query_params = array())
1877
-    {
1878
-        return $this->get_many_related('Registration_Payment', $query_params);
1879
-    }
1880
-
1881
-
1882
-    /**
1883
-     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1884
-     * Note: if there are no payments on the registration there will be no payment method returned.
1885
-     *
1886
-     * @return EE_Payment_Method|null
1887
-     */
1888
-    public function payment_method()
1889
-    {
1890
-        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1891
-    }
1892
-
1893
-
1894
-    /**
1895
-     * @return \EE_Line_Item
1896
-     * @throws EntityNotFoundException
1897
-     * @throws EE_Error
1898
-     */
1899
-    public function ticket_line_item()
1900
-    {
1901
-        $ticket = $this->ticket();
1902
-        $transaction = $this->transaction();
1903
-        $line_item = null;
1904
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1905
-            $transaction->total_line_item(),
1906
-            'Ticket',
1907
-            array($ticket->ID())
1908
-        );
1909
-        foreach ($ticket_line_items as $ticket_line_item) {
1910
-            if ($ticket_line_item instanceof \EE_Line_Item
1911
-                && $ticket_line_item->OBJ_type() === 'Ticket'
1912
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
1913
-            ) {
1914
-                $line_item = $ticket_line_item;
1915
-                break;
1916
-            }
1917
-        }
1918
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1919
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1920
-        }
1921
-        return $line_item;
1922
-    }
1923
-
1924
-
1925
-    /**
1926
-     * Soft Deletes this model object.
1927
-     *
1928
-     * @return boolean | int
1929
-     * @throws RuntimeException
1930
-     * @throws EE_Error
1931
-     */
1932
-    public function delete()
1933
-    {
1934
-        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1935
-            $this->set_status(EEM_Registration::status_id_cancelled);
1936
-        }
1937
-        return parent::delete();
1938
-    }
1939
-
1940
-
1941
-    /**
1942
-     * Restores whatever the previous status was on a registration before it was trashed (if possible)
1943
-     *
1944
-     * @throws EE_Error
1945
-     * @throws RuntimeException
1946
-     */
1947
-    public function restore()
1948
-    {
1949
-        $previous_status = $this->get_extra_meta(
1950
-            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1951
-            true,
1952
-            EEM_Registration::status_id_cancelled
1953
-        );
1954
-        if ($previous_status) {
1955
-            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1956
-            $this->set_status($previous_status);
1957
-        }
1958
-        return parent::restore();
1959
-    }
1960
-
1961
-
1962
-    /**
1963
-     * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1964
-     *
1965
-     * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1966
-     *                                           depending on whether the reg status changes to or from "Approved"
1967
-     * @return boolean whether the Registration status was updated
1968
-     * @throws EE_Error
1969
-     * @throws RuntimeException
1970
-     */
1971
-    public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
1972
-    {
1973
-        $paid = $this->paid();
1974
-        $price = $this->final_price();
1975
-        switch (true) {
1976
-            // overpaid or paid
1977
-            case EEH_Money::compare_floats($paid, $price, '>'):
1978
-            case EEH_Money::compare_floats($paid, $price):
1979
-                $new_status = EEM_Registration::status_id_approved;
1980
-                break;
1981
-            //  underpaid
1982
-            case EEH_Money::compare_floats($paid, $price, '<'):
1983
-                $new_status = EEM_Registration::status_id_pending_payment;
1984
-                break;
1985
-            // uhhh Houston...
1986
-            default:
1987
-                throw new RuntimeException(
1988
-                    esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
1989
-                );
1990
-        }
1991
-        if ($new_status !== $this->status_ID()) {
1992
-            if ($trigger_set_status_logic) {
1993
-                return $this->set_status($new_status);
1994
-            }
1995
-            parent::set('STS_ID', $new_status);
1996
-            return true;
1997
-        }
1998
-        return false;
1999
-    }
2000
-
2001
-
2002
-    /*************************** DEPRECATED ***************************/
2003
-
2004
-
2005
-    /**
2006
-     * @deprecated
2007
-     * @since     4.7.0
2008
-     * @access    public
2009
-     */
2010
-    public function price_paid()
2011
-    {
2012
-        EE_Error::doing_it_wrong(
2013
-            'EE_Registration::price_paid()',
2014
-            esc_html__(
2015
-                'This method is deprecated, please use EE_Registration::final_price() instead.',
2016
-                'event_espresso'
2017
-            ),
2018
-            '4.7.0'
2019
-        );
2020
-        return $this->final_price();
2021
-    }
2022
-
2023
-
2024
-    /**
2025
-     * @deprecated
2026
-     * @since     4.7.0
2027
-     * @access    public
2028
-     * @param    float $REG_final_price
2029
-     * @throws EE_Error
2030
-     * @throws RuntimeException
2031
-     */
2032
-    public function set_price_paid($REG_final_price = 0.00)
2033
-    {
2034
-        EE_Error::doing_it_wrong(
2035
-            'EE_Registration::set_price_paid()',
2036
-            esc_html__(
2037
-                'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2038
-                'event_espresso'
2039
-            ),
2040
-            '4.7.0'
2041
-        );
2042
-        $this->set_final_price($REG_final_price);
2043
-    }
2044
-
2045
-
2046
-    /**
2047
-     * @deprecated
2048
-     * @since 4.7.0
2049
-     * @return string
2050
-     * @throws EE_Error
2051
-     */
2052
-    public function pretty_price_paid()
2053
-    {
2054
-        EE_Error::doing_it_wrong(
2055
-            'EE_Registration::pretty_price_paid()',
2056
-            esc_html__(
2057
-                'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2058
-                'event_espresso'
2059
-            ),
2060
-            '4.7.0'
2061
-        );
2062
-        return $this->pretty_final_price();
2063
-    }
2064
-
2065
-
2066
-    /**
2067
-     * Gets the primary datetime related to this registration via the related Event to this registration
2068
-     *
2069
-     * @deprecated 4.9.17
2070
-     * @return EE_Datetime
2071
-     * @throws EE_Error
2072
-     * @throws EntityNotFoundException
2073
-     */
2074
-    public function get_related_primary_datetime()
2075
-    {
2076
-        EE_Error::doing_it_wrong(
2077
-            __METHOD__,
2078
-            esc_html__(
2079
-                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2080
-                'event_espresso'
2081
-            ),
2082
-            '4.9.17',
2083
-            '5.0.0'
2084
-        );
2085
-        return $this->event()->primary_datetime();
2086
-    }
20
+	/**
21
+	 * Used to reference when a registration has never been checked in.
22
+	 *
23
+	 * @deprecated use \EE_Checkin::status_checked_never instead
24
+	 * @type int
25
+	 */
26
+	const checkin_status_never = 2;
27
+
28
+	/**
29
+	 * Used to reference when a registration has been checked in.
30
+	 *
31
+	 * @deprecated use \EE_Checkin::status_checked_in instead
32
+	 * @type int
33
+	 */
34
+	const checkin_status_in = 1;
35
+
36
+
37
+	/**
38
+	 * Used to reference when a registration has been checked out.
39
+	 *
40
+	 * @deprecated use \EE_Checkin::status_checked_out instead
41
+	 * @type int
42
+	 */
43
+	const checkin_status_out = 0;
44
+
45
+
46
+	/**
47
+	 * extra meta key for tracking reg status os trashed registrations
48
+	 *
49
+	 * @type string
50
+	 */
51
+	const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
+
53
+
54
+	/**
55
+	 * extra meta key for tracking if registration has reserved ticket
56
+	 *
57
+	 * @type string
58
+	 */
59
+	const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
60
+
61
+
62
+	/**
63
+	 * @param array  $props_n_values          incoming values
64
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
65
+	 *                                        used.)
66
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
67
+	 *                                        date_format and the second value is the time format
68
+	 * @return EE_Registration
69
+	 * @throws EE_Error
70
+	 */
71
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
72
+	{
73
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
74
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param array  $props_n_values  incoming values from the database
80
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
+	 *                                the website will be used.
82
+	 * @return EE_Registration
83
+	 */
84
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
85
+	{
86
+		return new self($props_n_values, true, $timezone);
87
+	}
88
+
89
+
90
+	/**
91
+	 *        Set Event ID
92
+	 *
93
+	 * @param        int $EVT_ID Event ID
94
+	 * @throws EE_Error
95
+	 * @throws RuntimeException
96
+	 */
97
+	public function set_event($EVT_ID = 0)
98
+	{
99
+		$this->set('EVT_ID', $EVT_ID);
100
+	}
101
+
102
+
103
+	/**
104
+	 * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
105
+	 * be routed to internal methods
106
+	 *
107
+	 * @param string $field_name
108
+	 * @param mixed  $field_value
109
+	 * @param bool   $use_default
110
+	 * @throws EE_Error
111
+	 * @throws EntityNotFoundException
112
+	 * @throws InvalidArgumentException
113
+	 * @throws InvalidDataTypeException
114
+	 * @throws InvalidInterfaceException
115
+	 * @throws ReflectionException
116
+	 * @throws RuntimeException
117
+	 */
118
+	public function set($field_name, $field_value, $use_default = false)
119
+	{
120
+		switch ($field_name) {
121
+			case 'REG_code':
122
+				if (! empty($field_value) && $this->reg_code() === null) {
123
+					$this->set_reg_code($field_value, $use_default);
124
+				}
125
+				break;
126
+			case 'STS_ID':
127
+				$this->set_status($field_value, $use_default);
128
+				break;
129
+			default:
130
+				parent::set($field_name, $field_value, $use_default);
131
+		}
132
+	}
133
+
134
+
135
+	/**
136
+	 * Set Status ID
137
+	 * updates the registration status and ALSO...
138
+	 * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
139
+	 * calls release_registration_space() if the reg status changes FROM approved to any other reg status
140
+	 *
141
+	 * @param string                $new_STS_ID
142
+	 * @param boolean               $use_default
143
+	 * @param ContextInterface|null $context
144
+	 * @return bool
145
+	 * @throws EE_Error
146
+	 * @throws EntityNotFoundException
147
+	 * @throws InvalidArgumentException
148
+	 * @throws ReflectionException
149
+	 * @throws RuntimeException
150
+	 * @throws InvalidDataTypeException
151
+	 * @throws InvalidInterfaceException
152
+	 */
153
+	public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
154
+	{
155
+		// get current REG_Status
156
+		$old_STS_ID = $this->status_ID();
157
+		// if status has changed
158
+		if ($old_STS_ID !== $new_STS_ID // and that status has actually changed
159
+			&& ! empty($old_STS_ID) // and that old status is actually set
160
+			&& ! empty($new_STS_ID) // as well as the new status
161
+			&& $this->ID() // ensure registration is in the db
162
+		) {
163
+			// TO approved
164
+			if ($new_STS_ID === EEM_Registration::status_id_approved) {
165
+				// reserve a space by incrementing ticket and datetime sold values
166
+				$this->_reserve_registration_space();
167
+				do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
168
+				// OR FROM  approved
169
+			} elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
170
+				// release a space by decrementing ticket and datetime sold values
171
+				$this->_release_registration_space();
172
+				do_action(
173
+					'AHEE__EE_Registration__set_status__from_approved',
174
+					$this,
175
+					$old_STS_ID,
176
+					$new_STS_ID,
177
+					$context
178
+				);
179
+			}
180
+			// update status
181
+			parent::set('STS_ID', $new_STS_ID, $use_default);
182
+			$this->_update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, $context);
183
+			if ($this->statusChangeUpdatesTransaction($context)) {
184
+				$this->updateTransactionAfterStatusChange();
185
+			}
186
+			do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
187
+			return true;
188
+		}
189
+		// even though the old value matches the new value, it's still good to
190
+		// allow the parent set method to have a say
191
+		parent::set('STS_ID', $new_STS_ID, $use_default);
192
+		return true;
193
+	}
194
+
195
+
196
+	/**
197
+	 * update REGs and TXN when cancelled or declined registrations involved
198
+	 *
199
+	 * @param string                $new_STS_ID
200
+	 * @param string                $old_STS_ID
201
+	 * @param ContextInterface|null $context
202
+	 * @throws EE_Error
203
+	 * @throws InvalidArgumentException
204
+	 * @throws InvalidDataTypeException
205
+	 * @throws InvalidInterfaceException
206
+	 * @throws ReflectionException
207
+	 */
208
+	private function _update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
209
+	{
210
+		// these reg statuses should not be considered in any calculations involving monies owing
211
+		$closed_reg_statuses = EEM_Registration::closed_reg_statuses();
212
+		// true if registration has been cancelled or declined
213
+		$this->updateIfCanceled(
214
+			$closed_reg_statuses,
215
+			$new_STS_ID,
216
+			$old_STS_ID,
217
+			$context
218
+		);
219
+		$this->updateIfDeclined(
220
+			$closed_reg_statuses,
221
+			$new_STS_ID,
222
+			$old_STS_ID,
223
+			$context
224
+		);
225
+	}
226
+
227
+
228
+	/**
229
+	 * update REGs and TXN when cancelled or declined registrations involved
230
+	 *
231
+	 * @param array                 $closed_reg_statuses
232
+	 * @param string                $new_STS_ID
233
+	 * @param string                $old_STS_ID
234
+	 * @param ContextInterface|null $context
235
+	 * @throws EE_Error
236
+	 * @throws InvalidArgumentException
237
+	 * @throws InvalidDataTypeException
238
+	 * @throws InvalidInterfaceException
239
+	 * @throws ReflectionException
240
+	 */
241
+	private function updateIfCanceled(
242
+		array $closed_reg_statuses,
243
+		$new_STS_ID,
244
+		$old_STS_ID,
245
+		ContextInterface $context = null
246
+	) {
247
+		// true if registration has been cancelled or declined
248
+		if (in_array($new_STS_ID, $closed_reg_statuses, true)
249
+			&& ! in_array($old_STS_ID, $closed_reg_statuses, true)
250
+		) {
251
+			/** @type EE_Registration_Processor $registration_processor */
252
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
253
+			/** @type EE_Transaction_Processor $transaction_processor */
254
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
255
+			// cancelled or declined registration
256
+			$registration_processor->update_registration_after_being_canceled_or_declined(
257
+				$this,
258
+				$closed_reg_statuses
259
+			);
260
+			$transaction_processor->update_transaction_after_canceled_or_declined_registration(
261
+				$this,
262
+				$closed_reg_statuses,
263
+				false
264
+			);
265
+			do_action(
266
+				'AHEE__EE_Registration__set_status__canceled_or_declined',
267
+				$this,
268
+				$old_STS_ID,
269
+				$new_STS_ID,
270
+				$context
271
+			);
272
+			return;
273
+		}
274
+	}
275
+
276
+
277
+	/**
278
+	 * update REGs and TXN when cancelled or declined registrations involved
279
+	 *
280
+	 * @param array                 $closed_reg_statuses
281
+	 * @param string                $new_STS_ID
282
+	 * @param string                $old_STS_ID
283
+	 * @param ContextInterface|null $context
284
+	 * @throws EE_Error
285
+	 * @throws InvalidArgumentException
286
+	 * @throws InvalidDataTypeException
287
+	 * @throws InvalidInterfaceException
288
+	 * @throws ReflectionException
289
+	 */
290
+	private function updateIfDeclined(
291
+		array $closed_reg_statuses,
292
+		$new_STS_ID,
293
+		$old_STS_ID,
294
+		ContextInterface $context = null
295
+	) {
296
+		// true if reinstating cancelled or declined registration
297
+		if (in_array($old_STS_ID, $closed_reg_statuses, true)
298
+			&& ! in_array($new_STS_ID, $closed_reg_statuses, true)
299
+		) {
300
+			/** @type EE_Registration_Processor $registration_processor */
301
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
302
+			/** @type EE_Transaction_Processor $transaction_processor */
303
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
304
+			// reinstating cancelled or declined registration
305
+			$registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
306
+				$this,
307
+				$closed_reg_statuses
308
+			);
309
+			$transaction_processor->update_transaction_after_reinstating_canceled_registration(
310
+				$this,
311
+				$closed_reg_statuses,
312
+				false
313
+			);
314
+			do_action(
315
+				'AHEE__EE_Registration__set_status__after_reinstated',
316
+				$this,
317
+				$old_STS_ID,
318
+				$new_STS_ID,
319
+				$context
320
+			);
321
+		}
322
+	}
323
+
324
+
325
+	/**
326
+	 * @param ContextInterface|null $context
327
+	 * @return bool
328
+	 */
329
+	private function statusChangeUpdatesTransaction(ContextInterface $context = null)
330
+	{
331
+		$contexts_that_do_not_update_transaction = (array) apply_filters(
332
+			'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
333
+			array('spco_reg_step_attendee_information_process_registrations'),
334
+			$context,
335
+			$this
336
+		);
337
+		return ! (
338
+			$context instanceof ContextInterface
339
+			&& in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
340
+		);
341
+	}
342
+
343
+
344
+	/**
345
+	 * @throws EE_Error
346
+	 * @throws EntityNotFoundException
347
+	 * @throws InvalidArgumentException
348
+	 * @throws InvalidDataTypeException
349
+	 * @throws InvalidInterfaceException
350
+	 * @throws ReflectionException
351
+	 * @throws RuntimeException
352
+	 */
353
+	private function updateTransactionAfterStatusChange()
354
+	{
355
+		/** @type EE_Transaction_Payments $transaction_payments */
356
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
357
+		$transaction_payments->recalculate_transaction_total($this->transaction(), false);
358
+		$this->transaction()->update_status_based_on_total_paid(true);
359
+	}
360
+
361
+
362
+	/**
363
+	 *        get Status ID
364
+	 */
365
+	public function status_ID()
366
+	{
367
+		return $this->get('STS_ID');
368
+	}
369
+
370
+
371
+	/**
372
+	 * Gets the ticket this registration is for
373
+	 *
374
+	 * @param boolean $include_archived whether to include archived tickets or not.
375
+	 *
376
+	 * @return EE_Ticket|EE_Base_Class
377
+	 * @throws EE_Error
378
+	 */
379
+	public function ticket($include_archived = true)
380
+	{
381
+		$query_params = array();
382
+		if ($include_archived) {
383
+			$query_params['default_where_conditions'] = 'none';
384
+		}
385
+		return $this->get_first_related('Ticket', $query_params);
386
+	}
387
+
388
+
389
+	/**
390
+	 * Gets the event this registration is for
391
+	 *
392
+	 * @return EE_Event
393
+	 * @throws EE_Error
394
+	 * @throws EntityNotFoundException
395
+	 */
396
+	public function event()
397
+	{
398
+		$event = $this->get_first_related('Event');
399
+		if (! $event instanceof \EE_Event) {
400
+			throw new EntityNotFoundException('Event ID', $this->event_ID());
401
+		}
402
+		return $event;
403
+	}
404
+
405
+
406
+	/**
407
+	 * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
408
+	 * with the author of the event this registration is for.
409
+	 *
410
+	 * @since 4.5.0
411
+	 * @return int
412
+	 * @throws EE_Error
413
+	 * @throws EntityNotFoundException
414
+	 */
415
+	public function wp_user()
416
+	{
417
+		$event = $this->event();
418
+		if ($event instanceof EE_Event) {
419
+			return $event->wp_user();
420
+		}
421
+		return 0;
422
+	}
423
+
424
+
425
+	/**
426
+	 * increments this registration's related ticket sold and corresponding datetime sold values
427
+	 *
428
+	 * @return void
429
+	 * @throws DomainException
430
+	 * @throws EE_Error
431
+	 * @throws EntityNotFoundException
432
+	 * @throws InvalidArgumentException
433
+	 * @throws InvalidDataTypeException
434
+	 * @throws InvalidInterfaceException
435
+	 * @throws ReflectionException
436
+	 * @throws UnexpectedEntityException
437
+	 */
438
+	private function _reserve_registration_space()
439
+	{
440
+		// reserved ticket and datetime counts will be decremented as sold counts are incremented
441
+		// so stop tracking that this reg has a ticket reserved
442
+		$this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
443
+		$ticket = $this->ticket();
444
+		$ticket->increase_sold();
445
+		$ticket->save();
446
+		// possibly set event status to sold out
447
+		$this->event()->perform_sold_out_status_check();
448
+	}
449
+
450
+
451
+	/**
452
+	 * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
453
+	 *
454
+	 * @return void
455
+	 * @throws DomainException
456
+	 * @throws EE_Error
457
+	 * @throws EntityNotFoundException
458
+	 * @throws InvalidArgumentException
459
+	 * @throws InvalidDataTypeException
460
+	 * @throws InvalidInterfaceException
461
+	 * @throws ReflectionException
462
+	 * @throws UnexpectedEntityException
463
+	 */
464
+	private function _release_registration_space()
465
+	{
466
+		$ticket = $this->ticket();
467
+		$ticket->decrease_sold();
468
+		$ticket->save();
469
+		// possibly change event status from sold out back to previous status
470
+		$this->event()->perform_sold_out_status_check();
471
+	}
472
+
473
+
474
+	/**
475
+	 * tracks this registration's ticket reservation in extra meta
476
+	 * and can increment related ticket reserved and corresponding datetime reserved values
477
+	 *
478
+	 * @param bool $update_ticket if true, will increment ticket and datetime reserved count
479
+	 * @return void
480
+	 * @throws EE_Error
481
+	 * @throws InvalidArgumentException
482
+	 * @throws InvalidDataTypeException
483
+	 * @throws InvalidInterfaceException
484
+	 * @throws ReflectionException
485
+	 */
486
+	public function reserve_ticket($update_ticket = false, $source = 'unknown')
487
+	{
488
+		// only reserve ticket if space is not currently reserved
489
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
490
+			$this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
491
+			// IMPORTANT !!!
492
+			// although checking $update_ticket first would be more efficient,
493
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
494
+			if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
495
+				&& $update_ticket
496
+			) {
497
+				$ticket = $this->ticket();
498
+				$ticket->increase_reserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
499
+				$ticket->save();
500
+			}
501
+		}
502
+	}
503
+
504
+
505
+	/**
506
+	 * stops tracking this registration's ticket reservation in extra meta
507
+	 * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
508
+	 *
509
+	 * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
510
+	 * @return void
511
+	 * @throws EE_Error
512
+	 * @throws InvalidArgumentException
513
+	 * @throws InvalidDataTypeException
514
+	 * @throws InvalidInterfaceException
515
+	 * @throws ReflectionException
516
+	 */
517
+	public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
518
+	{
519
+		// only release ticket if space is currently reserved
520
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
521
+			$this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
522
+			// IMPORTANT !!!
523
+			// although checking $update_ticket first would be more efficient,
524
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
525
+			if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
526
+				&& $update_ticket
527
+			) {
528
+				$ticket = $this->ticket();
529
+				$ticket->decrease_reserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
530
+				$ticket->save();
531
+			}
532
+		}
533
+	}
534
+
535
+
536
+	/**
537
+	 * Set Attendee ID
538
+	 *
539
+	 * @param        int $ATT_ID Attendee ID
540
+	 * @throws EE_Error
541
+	 * @throws RuntimeException
542
+	 */
543
+	public function set_attendee_id($ATT_ID = 0)
544
+	{
545
+		$this->set('ATT_ID', $ATT_ID);
546
+	}
547
+
548
+
549
+	/**
550
+	 *        Set Transaction ID
551
+	 *
552
+	 * @param        int $TXN_ID Transaction ID
553
+	 * @throws EE_Error
554
+	 * @throws RuntimeException
555
+	 */
556
+	public function set_transaction_id($TXN_ID = 0)
557
+	{
558
+		$this->set('TXN_ID', $TXN_ID);
559
+	}
560
+
561
+
562
+	/**
563
+	 *        Set Session
564
+	 *
565
+	 * @param    string $REG_session PHP Session ID
566
+	 * @throws EE_Error
567
+	 * @throws RuntimeException
568
+	 */
569
+	public function set_session($REG_session = '')
570
+	{
571
+		$this->set('REG_session', $REG_session);
572
+	}
573
+
574
+
575
+	/**
576
+	 *        Set Registration URL Link
577
+	 *
578
+	 * @param    string $REG_url_link Registration URL Link
579
+	 * @throws EE_Error
580
+	 * @throws RuntimeException
581
+	 */
582
+	public function set_reg_url_link($REG_url_link = '')
583
+	{
584
+		$this->set('REG_url_link', $REG_url_link);
585
+	}
586
+
587
+
588
+	/**
589
+	 *        Set Attendee Counter
590
+	 *
591
+	 * @param        int $REG_count Primary Attendee
592
+	 * @throws EE_Error
593
+	 * @throws RuntimeException
594
+	 */
595
+	public function set_count($REG_count = 1)
596
+	{
597
+		$this->set('REG_count', $REG_count);
598
+	}
599
+
600
+
601
+	/**
602
+	 *        Set Group Size
603
+	 *
604
+	 * @param        boolean $REG_group_size Group Registration
605
+	 * @throws EE_Error
606
+	 * @throws RuntimeException
607
+	 */
608
+	public function set_group_size($REG_group_size = false)
609
+	{
610
+		$this->set('REG_group_size', $REG_group_size);
611
+	}
612
+
613
+
614
+	/**
615
+	 *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
616
+	 *    EEM_Registration::status_id_not_approved
617
+	 *
618
+	 * @return        boolean
619
+	 */
620
+	public function is_not_approved()
621
+	{
622
+		return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
623
+	}
624
+
625
+
626
+	/**
627
+	 *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
628
+	 *    EEM_Registration::status_id_pending_payment
629
+	 *
630
+	 * @return        boolean
631
+	 */
632
+	public function is_pending_payment()
633
+	{
634
+		return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
635
+	}
636
+
637
+
638
+	/**
639
+	 *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
640
+	 *
641
+	 * @return        boolean
642
+	 */
643
+	public function is_approved()
644
+	{
645
+		return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
646
+	}
647
+
648
+
649
+	/**
650
+	 *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
651
+	 *
652
+	 * @return        boolean
653
+	 */
654
+	public function is_cancelled()
655
+	{
656
+		return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
657
+	}
658
+
659
+
660
+	/**
661
+	 *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
662
+	 *
663
+	 * @return        boolean
664
+	 */
665
+	public function is_declined()
666
+	{
667
+		return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
668
+	}
669
+
670
+
671
+	/**
672
+	 *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
673
+	 *    EEM_Registration::status_id_incomplete
674
+	 *
675
+	 * @return        boolean
676
+	 */
677
+	public function is_incomplete()
678
+	{
679
+		return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
680
+	}
681
+
682
+
683
+	/**
684
+	 *        Set Registration Date
685
+	 *
686
+	 * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
687
+	 *                                                 Date
688
+	 * @throws EE_Error
689
+	 * @throws RuntimeException
690
+	 */
691
+	public function set_reg_date($REG_date = false)
692
+	{
693
+		$this->set('REG_date', $REG_date);
694
+	}
695
+
696
+
697
+	/**
698
+	 *    Set final price owing for this registration after all ticket/price modifications
699
+	 *
700
+	 * @access    public
701
+	 * @param    float $REG_final_price
702
+	 * @throws EE_Error
703
+	 * @throws RuntimeException
704
+	 */
705
+	public function set_final_price($REG_final_price = 0.00)
706
+	{
707
+		$this->set('REG_final_price', $REG_final_price);
708
+	}
709
+
710
+
711
+	/**
712
+	 *    Set amount paid towards this registration's final price
713
+	 *
714
+	 * @access    public
715
+	 * @param    float $REG_paid
716
+	 * @throws EE_Error
717
+	 * @throws RuntimeException
718
+	 */
719
+	public function set_paid($REG_paid = 0.00)
720
+	{
721
+		$this->set('REG_paid', $REG_paid);
722
+	}
723
+
724
+
725
+	/**
726
+	 *        Attendee Is Going
727
+	 *
728
+	 * @param        boolean $REG_att_is_going Attendee Is Going
729
+	 * @throws EE_Error
730
+	 * @throws RuntimeException
731
+	 */
732
+	public function set_att_is_going($REG_att_is_going = false)
733
+	{
734
+		$this->set('REG_att_is_going', $REG_att_is_going);
735
+	}
736
+
737
+
738
+	/**
739
+	 * Gets the related attendee
740
+	 *
741
+	 * @return EE_Attendee
742
+	 * @throws EE_Error
743
+	 */
744
+	public function attendee()
745
+	{
746
+		return $this->get_first_related('Attendee');
747
+	}
748
+
749
+
750
+	/**
751
+	 *        get Event ID
752
+	 */
753
+	public function event_ID()
754
+	{
755
+		return $this->get('EVT_ID');
756
+	}
757
+
758
+
759
+	/**
760
+	 *        get Event ID
761
+	 */
762
+	public function event_name()
763
+	{
764
+		$event = $this->event_obj();
765
+		if ($event) {
766
+			return $event->name();
767
+		} else {
768
+			return null;
769
+		}
770
+	}
771
+
772
+
773
+	/**
774
+	 * Fetches the event this registration is for
775
+	 *
776
+	 * @return EE_Event
777
+	 * @throws EE_Error
778
+	 */
779
+	public function event_obj()
780
+	{
781
+		return $this->get_first_related('Event');
782
+	}
783
+
784
+
785
+	/**
786
+	 *        get Attendee ID
787
+	 */
788
+	public function attendee_ID()
789
+	{
790
+		return $this->get('ATT_ID');
791
+	}
792
+
793
+
794
+	/**
795
+	 *        get PHP Session ID
796
+	 */
797
+	public function session_ID()
798
+	{
799
+		return $this->get('REG_session');
800
+	}
801
+
802
+
803
+	/**
804
+	 * Gets the string which represents the URL trigger for the receipt template in the message template system.
805
+	 *
806
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
807
+	 * @return string
808
+	 */
809
+	public function receipt_url($messenger = 'html')
810
+	{
811
+
812
+		/**
813
+		 * The below will be deprecated one version after this.  We check first if there is a custom receipt template
814
+		 * already in use on old system.  If there is then we just return the standard url for it.
815
+		 *
816
+		 * @since 4.5.0
817
+		 */
818
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
819
+		$has_custom = EEH_Template::locate_template(
820
+			$template_relative_path,
821
+			array(),
822
+			true,
823
+			true,
824
+			true
825
+		);
826
+
827
+		if ($has_custom) {
828
+			return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
829
+		}
830
+		return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
831
+	}
832
+
833
+
834
+	/**
835
+	 * Gets the string which represents the URL trigger for the invoice template in the message template system.
836
+	 *
837
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
838
+	 * @return string
839
+	 * @throws EE_Error
840
+	 */
841
+	public function invoice_url($messenger = 'html')
842
+	{
843
+		/**
844
+		 * The below will be deprecated one version after this.  We check first if there is a custom invoice template
845
+		 * already in use on old system.  If there is then we just return the standard url for it.
846
+		 *
847
+		 * @since 4.5.0
848
+		 */
849
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
850
+		$has_custom = EEH_Template::locate_template(
851
+			$template_relative_path,
852
+			array(),
853
+			true,
854
+			true,
855
+			true
856
+		);
857
+
858
+		if ($has_custom) {
859
+			if ($messenger == 'html') {
860
+				return $this->invoice_url('launch');
861
+			}
862
+			$route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
863
+
864
+			$query_args = array('ee' => $route, 'id' => $this->reg_url_link());
865
+			if ($messenger == 'html') {
866
+				$query_args['html'] = true;
867
+			}
868
+			return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
869
+		}
870
+		return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
871
+	}
872
+
873
+
874
+	/**
875
+	 * get Registration URL Link
876
+	 *
877
+	 * @access public
878
+	 * @return string
879
+	 * @throws EE_Error
880
+	 */
881
+	public function reg_url_link()
882
+	{
883
+		return (string) $this->get('REG_url_link');
884
+	}
885
+
886
+
887
+	/**
888
+	 * Echoes out invoice_url()
889
+	 *
890
+	 * @param string $type 'download','launch', or 'html' (default is 'launch')
891
+	 * @return void
892
+	 * @throws EE_Error
893
+	 */
894
+	public function e_invoice_url($type = 'launch')
895
+	{
896
+		echo $this->invoice_url($type);
897
+	}
898
+
899
+
900
+	/**
901
+	 * Echoes out payment_overview_url
902
+	 */
903
+	public function e_payment_overview_url()
904
+	{
905
+		echo $this->payment_overview_url();
906
+	}
907
+
908
+
909
+	/**
910
+	 * Gets the URL for the checkout payment options reg step
911
+	 * with this registration's REG_url_link added as a query parameter
912
+	 *
913
+	 * @param bool $clear_session Set to true when you want to clear the session on revisiting the
914
+	 *                            payment overview url.
915
+	 * @return string
916
+	 * @throws InvalidInterfaceException
917
+	 * @throws InvalidDataTypeException
918
+	 * @throws EE_Error
919
+	 * @throws InvalidArgumentException
920
+	 */
921
+	public function payment_overview_url($clear_session = false)
922
+	{
923
+		return add_query_arg(
924
+			(array) apply_filters(
925
+				'FHEE__EE_Registration__payment_overview_url__query_args',
926
+				array(
927
+					'e_reg_url_link' => $this->reg_url_link(),
928
+					'step'           => 'payment_options',
929
+					'revisit'        => true,
930
+					'clear_session'  => (bool) $clear_session,
931
+				),
932
+				$this
933
+			),
934
+			EE_Registry::instance()->CFG->core->reg_page_url()
935
+		);
936
+	}
937
+
938
+
939
+	/**
940
+	 * Gets the URL for the checkout attendee information reg step
941
+	 * with this registration's REG_url_link added as a query parameter
942
+	 *
943
+	 * @return string
944
+	 * @throws InvalidInterfaceException
945
+	 * @throws InvalidDataTypeException
946
+	 * @throws EE_Error
947
+	 * @throws InvalidArgumentException
948
+	 */
949
+	public function edit_attendee_information_url()
950
+	{
951
+		return add_query_arg(
952
+			(array) apply_filters(
953
+				'FHEE__EE_Registration__edit_attendee_information_url__query_args',
954
+				array(
955
+					'e_reg_url_link' => $this->reg_url_link(),
956
+					'step'           => 'attendee_information',
957
+					'revisit'        => true,
958
+				),
959
+				$this
960
+			),
961
+			EE_Registry::instance()->CFG->core->reg_page_url()
962
+		);
963
+	}
964
+
965
+
966
+	/**
967
+	 * Simply generates and returns the appropriate admin_url link to edit this registration
968
+	 *
969
+	 * @return string
970
+	 * @throws EE_Error
971
+	 */
972
+	public function get_admin_edit_url()
973
+	{
974
+		return EEH_URL::add_query_args_and_nonce(
975
+			array(
976
+				'page'    => 'espresso_registrations',
977
+				'action'  => 'view_registration',
978
+				'_REG_ID' => $this->ID(),
979
+			),
980
+			admin_url('admin.php')
981
+		);
982
+	}
983
+
984
+
985
+	/**
986
+	 *    is_primary_registrant?
987
+	 */
988
+	public function is_primary_registrant()
989
+	{
990
+		return $this->get('REG_count') == 1 ? true : false;
991
+	}
992
+
993
+
994
+	/**
995
+	 * This returns the primary registration object for this registration group (which may be this object).
996
+	 *
997
+	 * @return EE_Registration
998
+	 * @throws EE_Error
999
+	 */
1000
+	public function get_primary_registration()
1001
+	{
1002
+		if ($this->is_primary_registrant()) {
1003
+			return $this;
1004
+		}
1005
+
1006
+		// k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1007
+		/** @var EE_Registration $primary_registrant */
1008
+		$primary_registrant = EEM_Registration::instance()->get_one(
1009
+			array(
1010
+				array(
1011
+					'TXN_ID'    => $this->transaction_ID(),
1012
+					'REG_count' => 1,
1013
+				),
1014
+			)
1015
+		);
1016
+		return $primary_registrant;
1017
+	}
1018
+
1019
+
1020
+	/**
1021
+	 *        get  Attendee Number
1022
+	 *
1023
+	 * @access        public
1024
+	 */
1025
+	public function count()
1026
+	{
1027
+		return $this->get('REG_count');
1028
+	}
1029
+
1030
+
1031
+	/**
1032
+	 *        get Group Size
1033
+	 */
1034
+	public function group_size()
1035
+	{
1036
+		return $this->get('REG_group_size');
1037
+	}
1038
+
1039
+
1040
+	/**
1041
+	 *        get Registration Date
1042
+	 */
1043
+	public function date()
1044
+	{
1045
+		return $this->get('REG_date');
1046
+	}
1047
+
1048
+
1049
+	/**
1050
+	 * gets a pretty date
1051
+	 *
1052
+	 * @param string $date_format
1053
+	 * @param string $time_format
1054
+	 * @return string
1055
+	 * @throws EE_Error
1056
+	 */
1057
+	public function pretty_date($date_format = null, $time_format = null)
1058
+	{
1059
+		return $this->get_datetime('REG_date', $date_format, $time_format);
1060
+	}
1061
+
1062
+
1063
+	/**
1064
+	 * final_price
1065
+	 * the registration's share of the transaction total, so that the
1066
+	 * sum of all the transaction's REG_final_prices equal the transaction's total
1067
+	 *
1068
+	 * @return float
1069
+	 * @throws EE_Error
1070
+	 */
1071
+	public function final_price()
1072
+	{
1073
+		return $this->get('REG_final_price');
1074
+	}
1075
+
1076
+
1077
+	/**
1078
+	 * pretty_final_price
1079
+	 *  final price as formatted string, with correct decimal places and currency symbol
1080
+	 *
1081
+	 * @return string
1082
+	 * @throws EE_Error
1083
+	 */
1084
+	public function pretty_final_price()
1085
+	{
1086
+		return $this->get_pretty('REG_final_price');
1087
+	}
1088
+
1089
+
1090
+	/**
1091
+	 * get paid (yeah)
1092
+	 *
1093
+	 * @return float
1094
+	 * @throws EE_Error
1095
+	 */
1096
+	public function paid()
1097
+	{
1098
+		return $this->get('REG_paid');
1099
+	}
1100
+
1101
+
1102
+	/**
1103
+	 * pretty_paid
1104
+	 *
1105
+	 * @return float
1106
+	 * @throws EE_Error
1107
+	 */
1108
+	public function pretty_paid()
1109
+	{
1110
+		return $this->get_pretty('REG_paid');
1111
+	}
1112
+
1113
+
1114
+	/**
1115
+	 * owes_monies_and_can_pay
1116
+	 * whether or not this registration has monies owing and it's' status allows payment
1117
+	 *
1118
+	 * @param array $requires_payment
1119
+	 * @return bool
1120
+	 * @throws EE_Error
1121
+	 */
1122
+	public function owes_monies_and_can_pay($requires_payment = array())
1123
+	{
1124
+		// these reg statuses require payment (if event is not free)
1125
+		$requires_payment = ! empty($requires_payment)
1126
+			? $requires_payment
1127
+			: EEM_Registration::reg_statuses_that_allow_payment();
1128
+		if (in_array($this->status_ID(), $requires_payment) &&
1129
+			$this->final_price() != 0 &&
1130
+			$this->final_price() != $this->paid()
1131
+		) {
1132
+			return true;
1133
+		} else {
1134
+			return false;
1135
+		}
1136
+	}
1137
+
1138
+
1139
+	/**
1140
+	 * Prints out the return value of $this->pretty_status()
1141
+	 *
1142
+	 * @param bool $show_icons
1143
+	 * @return void
1144
+	 * @throws EE_Error
1145
+	 */
1146
+	public function e_pretty_status($show_icons = false)
1147
+	{
1148
+		echo $this->pretty_status($show_icons);
1149
+	}
1150
+
1151
+
1152
+	/**
1153
+	 * Returns a nice version of the status for displaying to customers
1154
+	 *
1155
+	 * @param bool $show_icons
1156
+	 * @return string
1157
+	 * @throws EE_Error
1158
+	 */
1159
+	public function pretty_status($show_icons = false)
1160
+	{
1161
+		$status = EEM_Status::instance()->localized_status(
1162
+			array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1163
+			false,
1164
+			'sentence'
1165
+		);
1166
+		$icon = '';
1167
+		switch ($this->status_ID()) {
1168
+			case EEM_Registration::status_id_approved:
1169
+				$icon = $show_icons
1170
+					? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1171
+					: '';
1172
+				break;
1173
+			case EEM_Registration::status_id_pending_payment:
1174
+				$icon = $show_icons
1175
+					? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1176
+					: '';
1177
+				break;
1178
+			case EEM_Registration::status_id_not_approved:
1179
+				$icon = $show_icons
1180
+					? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1181
+					: '';
1182
+				break;
1183
+			case EEM_Registration::status_id_cancelled:
1184
+				$icon = $show_icons
1185
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1186
+					: '';
1187
+				break;
1188
+			case EEM_Registration::status_id_incomplete:
1189
+				$icon = $show_icons
1190
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1191
+					: '';
1192
+				break;
1193
+			case EEM_Registration::status_id_declined:
1194
+				$icon = $show_icons
1195
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1196
+					: '';
1197
+				break;
1198
+			case EEM_Registration::status_id_wait_list:
1199
+				$icon = $show_icons
1200
+					? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1201
+					: '';
1202
+				break;
1203
+		}
1204
+		return $icon . $status[ $this->status_ID() ];
1205
+	}
1206
+
1207
+
1208
+	/**
1209
+	 *        get Attendee Is Going
1210
+	 */
1211
+	public function att_is_going()
1212
+	{
1213
+		return $this->get('REG_att_is_going');
1214
+	}
1215
+
1216
+
1217
+	/**
1218
+	 * Gets related answers
1219
+	 *
1220
+	 * @param array $query_params like EEM_Base::get_all
1221
+	 * @return EE_Answer[]
1222
+	 * @throws EE_Error
1223
+	 */
1224
+	public function answers($query_params = null)
1225
+	{
1226
+		return $this->get_many_related('Answer', $query_params);
1227
+	}
1228
+
1229
+
1230
+	/**
1231
+	 * Gets the registration's answer value to the specified question
1232
+	 * (either the question's ID or a question object)
1233
+	 *
1234
+	 * @param EE_Question|int $question
1235
+	 * @param bool            $pretty_value
1236
+	 * @return array|string if pretty_value= true, the result will always be a string
1237
+	 * (because the answer might be an array of answer values, so passing pretty_value=true
1238
+	 * will convert it into some kind of string)
1239
+	 * @throws EE_Error
1240
+	 */
1241
+	public function answer_value_to_question($question, $pretty_value = true)
1242
+	{
1243
+		$question_id = EEM_Question::instance()->ensure_is_ID($question);
1244
+		return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1245
+	}
1246
+
1247
+
1248
+	/**
1249
+	 * question_groups
1250
+	 * returns an array of EE_Question_Group objects for this registration
1251
+	 *
1252
+	 * @return EE_Question_Group[]
1253
+	 * @throws EE_Error
1254
+	 * @throws EntityNotFoundException
1255
+	 */
1256
+	public function question_groups()
1257
+	{
1258
+		$question_groups = array();
1259
+		if ($this->event() instanceof EE_Event) {
1260
+			$question_groups = $this->event()->question_groups(
1261
+				array(
1262
+					array(
1263
+						'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1264
+					),
1265
+					'order_by' => array('QSG_order' => 'ASC'),
1266
+				)
1267
+			);
1268
+		}
1269
+		return $question_groups;
1270
+	}
1271
+
1272
+
1273
+	/**
1274
+	 * count_question_groups
1275
+	 * returns a count of the number of EE_Question_Group objects for this registration
1276
+	 *
1277
+	 * @return int
1278
+	 * @throws EE_Error
1279
+	 * @throws EntityNotFoundException
1280
+	 */
1281
+	public function count_question_groups()
1282
+	{
1283
+		$qg_count = 0;
1284
+		if ($this->event() instanceof EE_Event) {
1285
+			$qg_count = $this->event()->count_related(
1286
+				'Question_Group',
1287
+				array(
1288
+					array(
1289
+						'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1290
+					),
1291
+				)
1292
+			);
1293
+		}
1294
+		return $qg_count;
1295
+	}
1296
+
1297
+
1298
+	/**
1299
+	 * Returns the registration date in the 'standard' string format
1300
+	 * (function may be improved in the future to allow for different formats and timezones)
1301
+	 *
1302
+	 * @return string
1303
+	 * @throws EE_Error
1304
+	 */
1305
+	public function reg_date()
1306
+	{
1307
+		return $this->get_datetime('REG_date');
1308
+	}
1309
+
1310
+
1311
+	/**
1312
+	 * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1313
+	 * the ticket this registration purchased, or the datetime they have registered
1314
+	 * to attend)
1315
+	 *
1316
+	 * @return EE_Datetime_Ticket
1317
+	 * @throws EE_Error
1318
+	 */
1319
+	public function datetime_ticket()
1320
+	{
1321
+		return $this->get_first_related('Datetime_Ticket');
1322
+	}
1323
+
1324
+
1325
+	/**
1326
+	 * Sets the registration's datetime_ticket.
1327
+	 *
1328
+	 * @param EE_Datetime_Ticket $datetime_ticket
1329
+	 * @return EE_Datetime_Ticket
1330
+	 * @throws EE_Error
1331
+	 */
1332
+	public function set_datetime_ticket($datetime_ticket)
1333
+	{
1334
+		return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1335
+	}
1336
+
1337
+	/**
1338
+	 * Gets deleted
1339
+	 *
1340
+	 * @return bool
1341
+	 * @throws EE_Error
1342
+	 */
1343
+	public function deleted()
1344
+	{
1345
+		return $this->get('REG_deleted');
1346
+	}
1347
+
1348
+	/**
1349
+	 * Sets deleted
1350
+	 *
1351
+	 * @param boolean $deleted
1352
+	 * @return bool
1353
+	 * @throws EE_Error
1354
+	 * @throws RuntimeException
1355
+	 */
1356
+	public function set_deleted($deleted)
1357
+	{
1358
+		if ($deleted) {
1359
+			$this->delete();
1360
+		} else {
1361
+			$this->restore();
1362
+		}
1363
+	}
1364
+
1365
+
1366
+	/**
1367
+	 * Get the status object of this object
1368
+	 *
1369
+	 * @return EE_Status
1370
+	 * @throws EE_Error
1371
+	 */
1372
+	public function status_obj()
1373
+	{
1374
+		return $this->get_first_related('Status');
1375
+	}
1376
+
1377
+
1378
+	/**
1379
+	 * Returns the number of times this registration has checked into any of the datetimes
1380
+	 * its available for
1381
+	 *
1382
+	 * @return int
1383
+	 * @throws EE_Error
1384
+	 */
1385
+	public function count_checkins()
1386
+	{
1387
+		return $this->get_model()->count_related($this, 'Checkin');
1388
+	}
1389
+
1390
+
1391
+	/**
1392
+	 * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1393
+	 * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1394
+	 *
1395
+	 * @return int
1396
+	 * @throws EE_Error
1397
+	 */
1398
+	public function count_checkins_not_checkedout()
1399
+	{
1400
+		return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1401
+	}
1402
+
1403
+
1404
+	/**
1405
+	 * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1406
+	 *
1407
+	 * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1408
+	 * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1409
+	 *                                          consider registration status as well as datetime access.
1410
+	 * @return bool
1411
+	 * @throws EE_Error
1412
+	 */
1413
+	public function can_checkin($DTT_OR_ID, $check_approved = true)
1414
+	{
1415
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1416
+
1417
+		// first check registration status
1418
+		if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1419
+			return false;
1420
+		}
1421
+		// is there a datetime ticket that matches this dtt_ID?
1422
+		if (! (EEM_Datetime_Ticket::instance()->exists(
1423
+			array(
1424
+				array(
1425
+					'TKT_ID' => $this->get('TKT_ID'),
1426
+					'DTT_ID' => $DTT_ID,
1427
+				),
1428
+			)
1429
+		))
1430
+		) {
1431
+			return false;
1432
+		}
1433
+
1434
+		// final check is against TKT_uses
1435
+		return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1436
+	}
1437
+
1438
+
1439
+	/**
1440
+	 * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1441
+	 * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1442
+	 * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1443
+	 * then return false.  Otherwise return true.
1444
+	 *
1445
+	 * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1446
+	 * @return bool true means can checkin.  false means cannot checkin.
1447
+	 * @throws EE_Error
1448
+	 */
1449
+	public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1450
+	{
1451
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1452
+
1453
+		if (! $DTT_ID) {
1454
+			return false;
1455
+		}
1456
+
1457
+		$max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1458
+
1459
+		// if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1460
+		// check-in or not.
1461
+		if (! $max_uses || $max_uses === EE_INF) {
1462
+			return true;
1463
+		}
1464
+
1465
+		// does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1466
+		// go ahead and toggle.
1467
+		if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1468
+			return true;
1469
+		}
1470
+
1471
+		// made it here so the last check is whether the number of checkins per unique datetime on this registration
1472
+		// disallows further check-ins.
1473
+		$count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1474
+			array(
1475
+				array(
1476
+					'REG_ID' => $this->ID(),
1477
+					'CHK_in' => true,
1478
+				),
1479
+			),
1480
+			'DTT_ID',
1481
+			true
1482
+		);
1483
+		// checkins have already reached their max number of uses
1484
+		// so registrant can NOT checkin
1485
+		if ($count_unique_dtt_checkins >= $max_uses) {
1486
+			EE_Error::add_error(
1487
+				esc_html__(
1488
+					'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1489
+					'event_espresso'
1490
+				),
1491
+				__FILE__,
1492
+				__FUNCTION__,
1493
+				__LINE__
1494
+			);
1495
+			return false;
1496
+		}
1497
+		return true;
1498
+	}
1499
+
1500
+
1501
+	/**
1502
+	 * toggle Check-in status for this registration
1503
+	 * Check-ins are toggled in the following order:
1504
+	 * never checked in -> checked in
1505
+	 * checked in -> checked out
1506
+	 * checked out -> checked in
1507
+	 *
1508
+	 * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1509
+	 *                      If not included or null, then it is assumed latest datetime is being toggled.
1510
+	 * @param bool $verify  If true then can_checkin() is used to verify whether the person
1511
+	 *                      can be checked in or not.  Otherwise this forces change in checkin status.
1512
+	 * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1513
+	 * @throws EE_Error
1514
+	 */
1515
+	public function toggle_checkin_status($DTT_ID = null, $verify = false)
1516
+	{
1517
+		if (empty($DTT_ID)) {
1518
+			$datetime = $this->get_latest_related_datetime();
1519
+			$DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1520
+			// verify the registration can checkin for the given DTT_ID
1521
+		} elseif (! $this->can_checkin($DTT_ID, $verify)) {
1522
+			EE_Error::add_error(
1523
+				sprintf(
1524
+					esc_html__(
1525
+						'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1526
+						'event_espresso'
1527
+					),
1528
+					$this->ID(),
1529
+					$DTT_ID
1530
+				),
1531
+				__FILE__,
1532
+				__FUNCTION__,
1533
+				__LINE__
1534
+			);
1535
+			return false;
1536
+		}
1537
+		$status_paths = array(
1538
+			EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1539
+			EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1540
+			EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1541
+		);
1542
+		// start by getting the current status so we know what status we'll be changing to.
1543
+		$cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1544
+		$status_to = $status_paths[ $cur_status ];
1545
+		// database only records true for checked IN or false for checked OUT
1546
+		// no record ( null ) means checked in NEVER, but we obviously don't save that
1547
+		$new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1548
+		// add relation - note Check-ins are always creating new rows
1549
+		// because we are keeping track of Check-ins over time.
1550
+		// Eventually we'll probably want to show a list table
1551
+		// for the individual Check-ins so that they can be managed.
1552
+		$checkin = EE_Checkin::new_instance(
1553
+			array(
1554
+				'REG_ID' => $this->ID(),
1555
+				'DTT_ID' => $DTT_ID,
1556
+				'CHK_in' => $new_status,
1557
+			)
1558
+		);
1559
+		// if the record could not be saved then return false
1560
+		if ($checkin->save() === 0) {
1561
+			if (WP_DEBUG) {
1562
+				global $wpdb;
1563
+				$error = sprintf(
1564
+					esc_html__(
1565
+						'Registration check in update failed because of the following database error: %1$s%2$s',
1566
+						'event_espresso'
1567
+					),
1568
+					'<br />',
1569
+					$wpdb->last_error
1570
+				);
1571
+			} else {
1572
+				$error = esc_html__(
1573
+					'Registration check in update failed because of an unknown database error',
1574
+					'event_espresso'
1575
+				);
1576
+			}
1577
+			EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1578
+			return false;
1579
+		}
1580
+		return $status_to;
1581
+	}
1582
+
1583
+
1584
+	/**
1585
+	 * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1586
+	 * "Latest" is defined by the `DTT_EVT_start` column.
1587
+	 *
1588
+	 * @return EE_Datetime|null
1589
+	 * @throws EE_Error
1590
+	 */
1591
+	public function get_latest_related_datetime()
1592
+	{
1593
+		return EEM_Datetime::instance()->get_one(
1594
+			array(
1595
+				array(
1596
+					'Ticket.Registration.REG_ID' => $this->ID(),
1597
+				),
1598
+				'order_by' => array('DTT_EVT_start' => 'DESC'),
1599
+			)
1600
+		);
1601
+	}
1602
+
1603
+
1604
+	/**
1605
+	 * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1606
+	 * "Earliest" is defined by the `DTT_EVT_start` column.
1607
+	 *
1608
+	 * @throws EE_Error
1609
+	 */
1610
+	public function get_earliest_related_datetime()
1611
+	{
1612
+		return EEM_Datetime::instance()->get_one(
1613
+			array(
1614
+				array(
1615
+					'Ticket.Registration.REG_ID' => $this->ID(),
1616
+				),
1617
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
1618
+			)
1619
+		);
1620
+	}
1621
+
1622
+
1623
+	/**
1624
+	 * This method simply returns the check-in status for this registration and the given datetime.
1625
+	 * If neither the datetime nor the checkin values are provided as arguments,
1626
+	 * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1627
+	 *
1628
+	 * @param  int       $DTT_ID  The ID of the datetime we're checking against
1629
+	 *                            (if empty we'll get the primary datetime for
1630
+	 *                            this registration (via event) and use it's ID);
1631
+	 * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1632
+	 *
1633
+	 * @return int                Integer representing Check-in status.
1634
+	 * @throws EE_Error
1635
+	 */
1636
+	public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1637
+	{
1638
+		$checkin_query_params = array(
1639
+			'order_by' => array('CHK_timestamp' => 'DESC'),
1640
+		);
1641
+
1642
+		if ($DTT_ID > 0) {
1643
+			$checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1644
+		}
1645
+
1646
+		// get checkin object (if exists)
1647
+		$checkin = $checkin instanceof EE_Checkin
1648
+			? $checkin
1649
+			: $this->get_first_related('Checkin', $checkin_query_params);
1650
+		if ($checkin instanceof EE_Checkin) {
1651
+			if ($checkin->get('CHK_in')) {
1652
+				return EE_Checkin::status_checked_in; // checked in
1653
+			}
1654
+			return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1655
+		}
1656
+		return EE_Checkin::status_checked_never; // never been checked in
1657
+	}
1658
+
1659
+
1660
+	/**
1661
+	 * This method returns a localized message for the toggled Check-in message.
1662
+	 *
1663
+	 * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1664
+	 *                     then it is assumed Check-in for primary datetime was toggled.
1665
+	 * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1666
+	 *                     message can be customized with the attendee name.
1667
+	 * @return string internationalized message
1668
+	 * @throws EE_Error
1669
+	 */
1670
+	public function get_checkin_msg($DTT_ID, $error = false)
1671
+	{
1672
+		// let's get the attendee first so we can include the name of the attendee
1673
+		$attendee = $this->get_first_related('Attendee');
1674
+		if ($attendee instanceof EE_Attendee) {
1675
+			if ($error) {
1676
+				return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1677
+			}
1678
+			$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1679
+			// what is the status message going to be?
1680
+			switch ($cur_status) {
1681
+				case EE_Checkin::status_checked_never:
1682
+					return sprintf(
1683
+						__("%s has been removed from Check-in records", "event_espresso"),
1684
+						$attendee->full_name()
1685
+					);
1686
+					break;
1687
+				case EE_Checkin::status_checked_in:
1688
+					return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1689
+					break;
1690
+				case EE_Checkin::status_checked_out:
1691
+					return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1692
+					break;
1693
+			}
1694
+		}
1695
+		return esc_html__("The check-in status could not be determined.", "event_espresso");
1696
+	}
1697
+
1698
+
1699
+	/**
1700
+	 * Returns the related EE_Transaction to this registration
1701
+	 *
1702
+	 * @return EE_Transaction
1703
+	 * @throws EE_Error
1704
+	 * @throws EntityNotFoundException
1705
+	 */
1706
+	public function transaction()
1707
+	{
1708
+		$transaction = $this->get_first_related('Transaction');
1709
+		if (! $transaction instanceof \EE_Transaction) {
1710
+			throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1711
+		}
1712
+		return $transaction;
1713
+	}
1714
+
1715
+
1716
+	/**
1717
+	 *        get Registration Code
1718
+	 */
1719
+	public function reg_code()
1720
+	{
1721
+		return $this->get('REG_code');
1722
+	}
1723
+
1724
+
1725
+	/**
1726
+	 *        get Transaction ID
1727
+	 */
1728
+	public function transaction_ID()
1729
+	{
1730
+		return $this->get('TXN_ID');
1731
+	}
1732
+
1733
+
1734
+	/**
1735
+	 * @return int
1736
+	 * @throws EE_Error
1737
+	 */
1738
+	public function ticket_ID()
1739
+	{
1740
+		return $this->get('TKT_ID');
1741
+	}
1742
+
1743
+
1744
+	/**
1745
+	 *        Set Registration Code
1746
+	 *
1747
+	 * @access    public
1748
+	 * @param    string  $REG_code Registration Code
1749
+	 * @param    boolean $use_default
1750
+	 * @throws EE_Error
1751
+	 */
1752
+	public function set_reg_code($REG_code, $use_default = false)
1753
+	{
1754
+		if (empty($REG_code)) {
1755
+			EE_Error::add_error(
1756
+				esc_html__('REG_code can not be empty.', 'event_espresso'),
1757
+				__FILE__,
1758
+				__FUNCTION__,
1759
+				__LINE__
1760
+			);
1761
+			return;
1762
+		}
1763
+		if (! $this->reg_code()) {
1764
+			parent::set('REG_code', $REG_code, $use_default);
1765
+		} else {
1766
+			EE_Error::doing_it_wrong(
1767
+				__CLASS__ . '::' . __FUNCTION__,
1768
+				esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1769
+				'4.6.0'
1770
+			);
1771
+		}
1772
+	}
1773
+
1774
+
1775
+	/**
1776
+	 * Returns all other registrations in the same group as this registrant who have the same ticket option.
1777
+	 * Note, if you want to just get all registrations in the same transaction (group), use:
1778
+	 *    $registration->transaction()->registrations();
1779
+	 *
1780
+	 * @since 4.5.0
1781
+	 * @return EE_Registration[] or empty array if this isn't a group registration.
1782
+	 * @throws EE_Error
1783
+	 */
1784
+	public function get_all_other_registrations_in_group()
1785
+	{
1786
+		if ($this->group_size() < 2) {
1787
+			return array();
1788
+		}
1789
+
1790
+		$query[0] = array(
1791
+			'TXN_ID' => $this->transaction_ID(),
1792
+			'REG_ID' => array('!=', $this->ID()),
1793
+			'TKT_ID' => $this->ticket_ID(),
1794
+		);
1795
+		/** @var EE_Registration[] $registrations */
1796
+		$registrations = $this->get_model()->get_all($query);
1797
+		return $registrations;
1798
+	}
1799
+
1800
+	/**
1801
+	 * Return the link to the admin details for the object.
1802
+	 *
1803
+	 * @return string
1804
+	 * @throws EE_Error
1805
+	 */
1806
+	public function get_admin_details_link()
1807
+	{
1808
+		EE_Registry::instance()->load_helper('URL');
1809
+		return EEH_URL::add_query_args_and_nonce(
1810
+			array(
1811
+				'page'    => 'espresso_registrations',
1812
+				'action'  => 'view_registration',
1813
+				'_REG_ID' => $this->ID(),
1814
+			),
1815
+			admin_url('admin.php')
1816
+		);
1817
+	}
1818
+
1819
+	/**
1820
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1821
+	 *
1822
+	 * @return string
1823
+	 * @throws EE_Error
1824
+	 */
1825
+	public function get_admin_edit_link()
1826
+	{
1827
+		return $this->get_admin_details_link();
1828
+	}
1829
+
1830
+	/**
1831
+	 * Returns the link to a settings page for the object.
1832
+	 *
1833
+	 * @return string
1834
+	 * @throws EE_Error
1835
+	 */
1836
+	public function get_admin_settings_link()
1837
+	{
1838
+		return $this->get_admin_details_link();
1839
+	}
1840
+
1841
+	/**
1842
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
1843
+	 *
1844
+	 * @return string
1845
+	 */
1846
+	public function get_admin_overview_link()
1847
+	{
1848
+		EE_Registry::instance()->load_helper('URL');
1849
+		return EEH_URL::add_query_args_and_nonce(
1850
+			array(
1851
+				'page' => 'espresso_registrations',
1852
+			),
1853
+			admin_url('admin.php')
1854
+		);
1855
+	}
1856
+
1857
+
1858
+	/**
1859
+	 * @param array $query_params
1860
+	 *
1861
+	 * @return \EE_Registration[]
1862
+	 * @throws EE_Error
1863
+	 */
1864
+	public function payments($query_params = array())
1865
+	{
1866
+		return $this->get_many_related('Payment', $query_params);
1867
+	}
1868
+
1869
+
1870
+	/**
1871
+	 * @param array $query_params
1872
+	 *
1873
+	 * @return \EE_Registration_Payment[]
1874
+	 * @throws EE_Error
1875
+	 */
1876
+	public function registration_payments($query_params = array())
1877
+	{
1878
+		return $this->get_many_related('Registration_Payment', $query_params);
1879
+	}
1880
+
1881
+
1882
+	/**
1883
+	 * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1884
+	 * Note: if there are no payments on the registration there will be no payment method returned.
1885
+	 *
1886
+	 * @return EE_Payment_Method|null
1887
+	 */
1888
+	public function payment_method()
1889
+	{
1890
+		return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1891
+	}
1892
+
1893
+
1894
+	/**
1895
+	 * @return \EE_Line_Item
1896
+	 * @throws EntityNotFoundException
1897
+	 * @throws EE_Error
1898
+	 */
1899
+	public function ticket_line_item()
1900
+	{
1901
+		$ticket = $this->ticket();
1902
+		$transaction = $this->transaction();
1903
+		$line_item = null;
1904
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1905
+			$transaction->total_line_item(),
1906
+			'Ticket',
1907
+			array($ticket->ID())
1908
+		);
1909
+		foreach ($ticket_line_items as $ticket_line_item) {
1910
+			if ($ticket_line_item instanceof \EE_Line_Item
1911
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
1912
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
1913
+			) {
1914
+				$line_item = $ticket_line_item;
1915
+				break;
1916
+			}
1917
+		}
1918
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1919
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1920
+		}
1921
+		return $line_item;
1922
+	}
1923
+
1924
+
1925
+	/**
1926
+	 * Soft Deletes this model object.
1927
+	 *
1928
+	 * @return boolean | int
1929
+	 * @throws RuntimeException
1930
+	 * @throws EE_Error
1931
+	 */
1932
+	public function delete()
1933
+	{
1934
+		if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1935
+			$this->set_status(EEM_Registration::status_id_cancelled);
1936
+		}
1937
+		return parent::delete();
1938
+	}
1939
+
1940
+
1941
+	/**
1942
+	 * Restores whatever the previous status was on a registration before it was trashed (if possible)
1943
+	 *
1944
+	 * @throws EE_Error
1945
+	 * @throws RuntimeException
1946
+	 */
1947
+	public function restore()
1948
+	{
1949
+		$previous_status = $this->get_extra_meta(
1950
+			EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1951
+			true,
1952
+			EEM_Registration::status_id_cancelled
1953
+		);
1954
+		if ($previous_status) {
1955
+			$this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1956
+			$this->set_status($previous_status);
1957
+		}
1958
+		return parent::restore();
1959
+	}
1960
+
1961
+
1962
+	/**
1963
+	 * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1964
+	 *
1965
+	 * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1966
+	 *                                           depending on whether the reg status changes to or from "Approved"
1967
+	 * @return boolean whether the Registration status was updated
1968
+	 * @throws EE_Error
1969
+	 * @throws RuntimeException
1970
+	 */
1971
+	public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
1972
+	{
1973
+		$paid = $this->paid();
1974
+		$price = $this->final_price();
1975
+		switch (true) {
1976
+			// overpaid or paid
1977
+			case EEH_Money::compare_floats($paid, $price, '>'):
1978
+			case EEH_Money::compare_floats($paid, $price):
1979
+				$new_status = EEM_Registration::status_id_approved;
1980
+				break;
1981
+			//  underpaid
1982
+			case EEH_Money::compare_floats($paid, $price, '<'):
1983
+				$new_status = EEM_Registration::status_id_pending_payment;
1984
+				break;
1985
+			// uhhh Houston...
1986
+			default:
1987
+				throw new RuntimeException(
1988
+					esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
1989
+				);
1990
+		}
1991
+		if ($new_status !== $this->status_ID()) {
1992
+			if ($trigger_set_status_logic) {
1993
+				return $this->set_status($new_status);
1994
+			}
1995
+			parent::set('STS_ID', $new_status);
1996
+			return true;
1997
+		}
1998
+		return false;
1999
+	}
2000
+
2001
+
2002
+	/*************************** DEPRECATED ***************************/
2003
+
2004
+
2005
+	/**
2006
+	 * @deprecated
2007
+	 * @since     4.7.0
2008
+	 * @access    public
2009
+	 */
2010
+	public function price_paid()
2011
+	{
2012
+		EE_Error::doing_it_wrong(
2013
+			'EE_Registration::price_paid()',
2014
+			esc_html__(
2015
+				'This method is deprecated, please use EE_Registration::final_price() instead.',
2016
+				'event_espresso'
2017
+			),
2018
+			'4.7.0'
2019
+		);
2020
+		return $this->final_price();
2021
+	}
2022
+
2023
+
2024
+	/**
2025
+	 * @deprecated
2026
+	 * @since     4.7.0
2027
+	 * @access    public
2028
+	 * @param    float $REG_final_price
2029
+	 * @throws EE_Error
2030
+	 * @throws RuntimeException
2031
+	 */
2032
+	public function set_price_paid($REG_final_price = 0.00)
2033
+	{
2034
+		EE_Error::doing_it_wrong(
2035
+			'EE_Registration::set_price_paid()',
2036
+			esc_html__(
2037
+				'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2038
+				'event_espresso'
2039
+			),
2040
+			'4.7.0'
2041
+		);
2042
+		$this->set_final_price($REG_final_price);
2043
+	}
2044
+
2045
+
2046
+	/**
2047
+	 * @deprecated
2048
+	 * @since 4.7.0
2049
+	 * @return string
2050
+	 * @throws EE_Error
2051
+	 */
2052
+	public function pretty_price_paid()
2053
+	{
2054
+		EE_Error::doing_it_wrong(
2055
+			'EE_Registration::pretty_price_paid()',
2056
+			esc_html__(
2057
+				'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2058
+				'event_espresso'
2059
+			),
2060
+			'4.7.0'
2061
+		);
2062
+		return $this->pretty_final_price();
2063
+	}
2064
+
2065
+
2066
+	/**
2067
+	 * Gets the primary datetime related to this registration via the related Event to this registration
2068
+	 *
2069
+	 * @deprecated 4.9.17
2070
+	 * @return EE_Datetime
2071
+	 * @throws EE_Error
2072
+	 * @throws EntityNotFoundException
2073
+	 */
2074
+	public function get_related_primary_datetime()
2075
+	{
2076
+		EE_Error::doing_it_wrong(
2077
+			__METHOD__,
2078
+			esc_html__(
2079
+				'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2080
+				'event_espresso'
2081
+			),
2082
+			'4.9.17',
2083
+			'5.0.0'
2084
+		);
2085
+		return $this->event()->primary_datetime();
2086
+	}
2087 2087
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
     {
120 120
         switch ($field_name) {
121 121
             case 'REG_code':
122
-                if (! empty($field_value) && $this->reg_code() === null) {
122
+                if ( ! empty($field_value) && $this->reg_code() === null) {
123 123
                     $this->set_reg_code($field_value, $use_default);
124 124
                 }
125 125
                 break;
@@ -396,7 +396,7 @@  discard block
 block discarded – undo
396 396
     public function event()
397 397
     {
398 398
         $event = $this->get_first_related('Event');
399
-        if (! $event instanceof \EE_Event) {
399
+        if ( ! $event instanceof \EE_Event) {
400 400
             throw new EntityNotFoundException('Event ID', $this->event_ID());
401 401
         }
402 402
         return $event;
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
     {
440 440
         // reserved ticket and datetime counts will be decremented as sold counts are incremented
441 441
         // so stop tracking that this reg has a ticket reserved
442
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
442
+        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:".__LINE__.')');
443 443
         $ticket = $this->ticket();
444 444
         $ticket->increase_sold();
445 445
         $ticket->save();
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
                 && $update_ticket
496 496
             ) {
497 497
                 $ticket = $this->ticket();
498
-                $ticket->increase_reserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
498
+                $ticket->increase_reserved(1, "REG: {$this->ID()} (ln:".__LINE__.')');
499 499
                 $ticket->save();
500 500
             }
501 501
         }
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
                 && $update_ticket
527 527
             ) {
528 528
                 $ticket = $this->ticket();
529
-                $ticket->decrease_reserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
529
+                $ticket->decrease_reserved(1, true, "REG: {$this->ID()} (ln:".__LINE__.')');
530 530
                 $ticket->save();
531 531
             }
532 532
         }
@@ -1201,7 +1201,7 @@  discard block
 block discarded – undo
1201 1201
                     : '';
1202 1202
                 break;
1203 1203
         }
1204
-        return $icon . $status[ $this->status_ID() ];
1204
+        return $icon.$status[$this->status_ID()];
1205 1205
     }
1206 1206
 
1207 1207
 
@@ -1419,7 +1419,7 @@  discard block
 block discarded – undo
1419 1419
             return false;
1420 1420
         }
1421 1421
         // is there a datetime ticket that matches this dtt_ID?
1422
-        if (! (EEM_Datetime_Ticket::instance()->exists(
1422
+        if ( ! (EEM_Datetime_Ticket::instance()->exists(
1423 1423
             array(
1424 1424
                 array(
1425 1425
                     'TKT_ID' => $this->get('TKT_ID'),
@@ -1450,7 +1450,7 @@  discard block
 block discarded – undo
1450 1450
     {
1451 1451
         $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1452 1452
 
1453
-        if (! $DTT_ID) {
1453
+        if ( ! $DTT_ID) {
1454 1454
             return false;
1455 1455
         }
1456 1456
 
@@ -1458,7 +1458,7 @@  discard block
 block discarded – undo
1458 1458
 
1459 1459
         // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1460 1460
         // check-in or not.
1461
-        if (! $max_uses || $max_uses === EE_INF) {
1461
+        if ( ! $max_uses || $max_uses === EE_INF) {
1462 1462
             return true;
1463 1463
         }
1464 1464
 
@@ -1518,7 +1518,7 @@  discard block
 block discarded – undo
1518 1518
             $datetime = $this->get_latest_related_datetime();
1519 1519
             $DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1520 1520
             // verify the registration can checkin for the given DTT_ID
1521
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1521
+        } elseif ( ! $this->can_checkin($DTT_ID, $verify)) {
1522 1522
             EE_Error::add_error(
1523 1523
                 sprintf(
1524 1524
                     esc_html__(
@@ -1541,7 +1541,7 @@  discard block
 block discarded – undo
1541 1541
         );
1542 1542
         // start by getting the current status so we know what status we'll be changing to.
1543 1543
         $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1544
-        $status_to = $status_paths[ $cur_status ];
1544
+        $status_to = $status_paths[$cur_status];
1545 1545
         // database only records true for checked IN or false for checked OUT
1546 1546
         // no record ( null ) means checked in NEVER, but we obviously don't save that
1547 1547
         $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
@@ -1706,7 +1706,7 @@  discard block
 block discarded – undo
1706 1706
     public function transaction()
1707 1707
     {
1708 1708
         $transaction = $this->get_first_related('Transaction');
1709
-        if (! $transaction instanceof \EE_Transaction) {
1709
+        if ( ! $transaction instanceof \EE_Transaction) {
1710 1710
             throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1711 1711
         }
1712 1712
         return $transaction;
@@ -1760,11 +1760,11 @@  discard block
 block discarded – undo
1760 1760
             );
1761 1761
             return;
1762 1762
         }
1763
-        if (! $this->reg_code()) {
1763
+        if ( ! $this->reg_code()) {
1764 1764
             parent::set('REG_code', $REG_code, $use_default);
1765 1765
         } else {
1766 1766
             EE_Error::doing_it_wrong(
1767
-                __CLASS__ . '::' . __FUNCTION__,
1767
+                __CLASS__.'::'.__FUNCTION__,
1768 1768
                 esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1769 1769
                 '4.6.0'
1770 1770
             );
@@ -1915,7 +1915,7 @@  discard block
 block discarded – undo
1915 1915
                 break;
1916 1916
             }
1917 1917
         }
1918
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1918
+        if ( ! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1919 1919
             throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1920 1920
         }
1921 1921
         return $line_item;
Please login to merge, or discard this patch.