Completed
Branch master (87d3f3)
by
unknown
03:30
created
core/db_classes/EE_Line_Item.class.php 1 patch
Indentation   +1659 added lines, -1659 removed lines patch added patch discarded remove patch
@@ -15,1663 +15,1663 @@
 block discarded – undo
15 15
  */
16 16
 class EE_Line_Item extends EE_Base_Class implements EEI_Line_Item
17 17
 {
18
-    /**
19
-     * for children line items (currently not a normal relation)
20
-     *
21
-     * @type EE_Line_Item[]
22
-     */
23
-    protected $_children = array();
24
-
25
-    /**
26
-     * for the parent line item
27
-     *
28
-     * @var EE_Line_Item
29
-     */
30
-    protected $_parent;
31
-
32
-    /**
33
-     * @var LineItemCalculator
34
-     */
35
-    protected $calculator;
36
-
37
-
38
-    /**
39
-     * @param array  $props_n_values          incoming values
40
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
41
-     *                                        used.)
42
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
43
-     *                                        date_format and the second value is the time format
44
-     * @return EE_Line_Item
45
-     * @throws EE_Error
46
-     * @throws InvalidArgumentException
47
-     * @throws InvalidDataTypeException
48
-     * @throws InvalidInterfaceException
49
-     * @throws ReflectionException
50
-     */
51
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
-    {
53
-        $has_object = parent::_check_for_object(
54
-            $props_n_values,
55
-            __CLASS__,
56
-            $timezone,
57
-            $date_formats
58
-        );
59
-        return $has_object
60
-            ? $has_object
61
-            : new self($props_n_values, false, $timezone);
62
-    }
63
-
64
-
65
-    /**
66
-     * @param array  $props_n_values  incoming values from the database
67
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
68
-     *                                the website will be used.
69
-     * @return EE_Line_Item
70
-     * @throws EE_Error
71
-     * @throws InvalidArgumentException
72
-     * @throws InvalidDataTypeException
73
-     * @throws InvalidInterfaceException
74
-     * @throws ReflectionException
75
-     */
76
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
77
-    {
78
-        return new self($props_n_values, true, $timezone);
79
-    }
80
-
81
-
82
-    /**
83
-     * Adds some defaults if they're not specified
84
-     *
85
-     * @param array  $fieldValues
86
-     * @param bool   $bydb
87
-     * @param string $timezone
88
-     * @throws EE_Error
89
-     * @throws InvalidArgumentException
90
-     * @throws InvalidDataTypeException
91
-     * @throws InvalidInterfaceException
92
-     * @throws ReflectionException
93
-     */
94
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
95
-    {
96
-        $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
97
-        parent::__construct($fieldValues, $bydb, $timezone);
98
-        if (! $this->get('LIN_code')) {
99
-            $this->set_code($this->generate_code());
100
-        }
101
-    }
102
-
103
-
104
-    public function __wakeup()
105
-    {
106
-        $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
107
-        parent::__wakeup();
108
-    }
109
-
110
-
111
-    /**
112
-     * Gets ID
113
-     *
114
-     * @return int
115
-     * @throws EE_Error
116
-     * @throws InvalidArgumentException
117
-     * @throws InvalidDataTypeException
118
-     * @throws InvalidInterfaceException
119
-     * @throws ReflectionException
120
-     */
121
-    public function ID()
122
-    {
123
-        return $this->get('LIN_ID');
124
-    }
125
-
126
-
127
-    /**
128
-     * Gets TXN_ID
129
-     *
130
-     * @return int
131
-     * @throws EE_Error
132
-     * @throws InvalidArgumentException
133
-     * @throws InvalidDataTypeException
134
-     * @throws InvalidInterfaceException
135
-     * @throws ReflectionException
136
-     */
137
-    public function TXN_ID()
138
-    {
139
-        return $this->get('TXN_ID');
140
-    }
141
-
142
-
143
-    /**
144
-     * Sets TXN_ID
145
-     *
146
-     * @param int $TXN_ID
147
-     * @throws EE_Error
148
-     * @throws InvalidArgumentException
149
-     * @throws InvalidDataTypeException
150
-     * @throws InvalidInterfaceException
151
-     * @throws ReflectionException
152
-     */
153
-    public function set_TXN_ID($TXN_ID)
154
-    {
155
-        $this->set('TXN_ID', $TXN_ID);
156
-    }
157
-
158
-
159
-    /**
160
-     * Gets name
161
-     *
162
-     * @return string
163
-     * @throws EE_Error
164
-     * @throws InvalidArgumentException
165
-     * @throws InvalidDataTypeException
166
-     * @throws InvalidInterfaceException
167
-     * @throws ReflectionException
168
-     */
169
-    public function name()
170
-    {
171
-        $name = $this->get('LIN_name');
172
-        if (! $name) {
173
-            $name = ucwords(str_replace('-', ' ', $this->type()));
174
-        }
175
-        return $name;
176
-    }
177
-
178
-
179
-    /**
180
-     * Sets name
181
-     *
182
-     * @param string $name
183
-     * @throws EE_Error
184
-     * @throws InvalidArgumentException
185
-     * @throws InvalidDataTypeException
186
-     * @throws InvalidInterfaceException
187
-     * @throws ReflectionException
188
-     */
189
-    public function set_name($name)
190
-    {
191
-        $this->set('LIN_name', $name);
192
-    }
193
-
194
-
195
-    /**
196
-     * Gets desc
197
-     *
198
-     * @return string
199
-     * @throws EE_Error
200
-     * @throws InvalidArgumentException
201
-     * @throws InvalidDataTypeException
202
-     * @throws InvalidInterfaceException
203
-     * @throws ReflectionException
204
-     */
205
-    public function desc()
206
-    {
207
-        return $this->get('LIN_desc');
208
-    }
209
-
210
-
211
-    /**
212
-     * Sets desc
213
-     *
214
-     * @param string $desc
215
-     * @throws EE_Error
216
-     * @throws InvalidArgumentException
217
-     * @throws InvalidDataTypeException
218
-     * @throws InvalidInterfaceException
219
-     * @throws ReflectionException
220
-     */
221
-    public function set_desc($desc)
222
-    {
223
-        $this->set('LIN_desc', $desc);
224
-    }
225
-
226
-
227
-    /**
228
-     * Gets quantity
229
-     *
230
-     * @return int
231
-     * @throws EE_Error
232
-     * @throws InvalidArgumentException
233
-     * @throws InvalidDataTypeException
234
-     * @throws InvalidInterfaceException
235
-     * @throws ReflectionException
236
-     */
237
-    public function quantity(): int
238
-    {
239
-        return (int) $this->get('LIN_quantity');
240
-    }
241
-
242
-
243
-    /**
244
-     * Sets quantity
245
-     *
246
-     * @param int $quantity
247
-     * @throws EE_Error
248
-     * @throws InvalidArgumentException
249
-     * @throws InvalidDataTypeException
250
-     * @throws InvalidInterfaceException
251
-     * @throws ReflectionException
252
-     */
253
-    public function set_quantity($quantity)
254
-    {
255
-        $this->set('LIN_quantity', max($quantity, 0));
256
-    }
257
-
258
-
259
-    /**
260
-     * Gets item_id
261
-     *
262
-     * @return int
263
-     * @throws EE_Error
264
-     * @throws InvalidArgumentException
265
-     * @throws InvalidDataTypeException
266
-     * @throws InvalidInterfaceException
267
-     * @throws ReflectionException
268
-     */
269
-    public function OBJ_ID()
270
-    {
271
-        return $this->get('OBJ_ID');
272
-    }
273
-
274
-
275
-    /**
276
-     * Sets item_id
277
-     *
278
-     * @param int $item_id
279
-     * @throws EE_Error
280
-     * @throws InvalidArgumentException
281
-     * @throws InvalidDataTypeException
282
-     * @throws InvalidInterfaceException
283
-     * @throws ReflectionException
284
-     */
285
-    public function set_OBJ_ID($item_id)
286
-    {
287
-        $this->set('OBJ_ID', $item_id);
288
-    }
289
-
290
-
291
-    /**
292
-     * Gets item_type
293
-     *
294
-     * @return string
295
-     * @throws EE_Error
296
-     * @throws InvalidArgumentException
297
-     * @throws InvalidDataTypeException
298
-     * @throws InvalidInterfaceException
299
-     * @throws ReflectionException
300
-     */
301
-    public function OBJ_type()
302
-    {
303
-        return $this->get('OBJ_type');
304
-    }
305
-
306
-
307
-    /**
308
-     * Gets item_type
309
-     *
310
-     * @return string
311
-     * @throws EE_Error
312
-     * @throws InvalidArgumentException
313
-     * @throws InvalidDataTypeException
314
-     * @throws InvalidInterfaceException
315
-     * @throws ReflectionException
316
-     */
317
-    public function OBJ_type_i18n()
318
-    {
319
-        $obj_type = $this->OBJ_type();
320
-        switch ($obj_type) {
321
-            case EEM_Line_Item::OBJ_TYPE_EVENT:
322
-                $obj_type = esc_html__('Event', 'event_espresso');
323
-                break;
324
-            case EEM_Line_Item::OBJ_TYPE_PRICE:
325
-                $obj_type = esc_html__('Price', 'event_espresso');
326
-                break;
327
-            case EEM_Line_Item::OBJ_TYPE_PROMOTION:
328
-                $obj_type = esc_html__('Promotion', 'event_espresso');
329
-                break;
330
-            case EEM_Line_Item::OBJ_TYPE_TICKET:
331
-                $obj_type = esc_html__('Ticket', 'event_espresso');
332
-                break;
333
-            case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
334
-                $obj_type = esc_html__('Transaction', 'event_espresso');
335
-                break;
336
-        }
337
-        return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
338
-    }
339
-
340
-
341
-    /**
342
-     * Sets item_type
343
-     *
344
-     * @param string $OBJ_type
345
-     * @throws EE_Error
346
-     * @throws InvalidArgumentException
347
-     * @throws InvalidDataTypeException
348
-     * @throws InvalidInterfaceException
349
-     * @throws ReflectionException
350
-     */
351
-    public function set_OBJ_type($OBJ_type)
352
-    {
353
-        $this->set('OBJ_type', $OBJ_type);
354
-    }
355
-
356
-
357
-    /**
358
-     * Gets unit_price
359
-     *
360
-     * @return float
361
-     * @throws EE_Error
362
-     * @throws InvalidArgumentException
363
-     * @throws InvalidDataTypeException
364
-     * @throws InvalidInterfaceException
365
-     * @throws ReflectionException
366
-     */
367
-    public function unit_price()
368
-    {
369
-        return $this->get('LIN_unit_price');
370
-    }
371
-
372
-
373
-    /**
374
-     * Sets unit_price
375
-     *
376
-     * @param float $unit_price
377
-     * @throws EE_Error
378
-     * @throws InvalidArgumentException
379
-     * @throws InvalidDataTypeException
380
-     * @throws InvalidInterfaceException
381
-     * @throws ReflectionException
382
-     */
383
-    public function set_unit_price($unit_price)
384
-    {
385
-        $this->set('LIN_unit_price', $unit_price);
386
-    }
387
-
388
-
389
-    /**
390
-     * Checks if this item is a percentage modifier or not
391
-     *
392
-     * @return boolean
393
-     * @throws EE_Error
394
-     * @throws InvalidArgumentException
395
-     * @throws InvalidDataTypeException
396
-     * @throws InvalidInterfaceException
397
-     * @throws ReflectionException
398
-     */
399
-    public function is_percent()
400
-    {
401
-        if ($this->is_tax_sub_total()) {
402
-            // tax subtotals HAVE a percent on them, that percentage only applies
403
-            // to taxable items, so its' an exception. Treat it like a flat line item
404
-            return false;
405
-        }
406
-        $unit_price = abs($this->get('LIN_unit_price'));
407
-        $percent = abs($this->get('LIN_percent'));
408
-        if ($unit_price < .001 && $percent) {
409
-            return true;
410
-        }
411
-        if ($unit_price >= .001 && ! $percent) {
412
-            return false;
413
-        }
414
-        if ($unit_price >= .001 && $percent) {
415
-            throw new EE_Error(
416
-                sprintf(
417
-                    esc_html__(
418
-                        'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
419
-                        'event_espresso'
420
-                    ),
421
-                    $unit_price,
422
-                    $percent
423
-                )
424
-            );
425
-        }
426
-        // if they're both 0, assume its not a percent item
427
-        return false;
428
-    }
429
-
430
-
431
-    /**
432
-     * Gets percent (between 100-.001)
433
-     *
434
-     * @return float
435
-     * @throws EE_Error
436
-     * @throws InvalidArgumentException
437
-     * @throws InvalidDataTypeException
438
-     * @throws InvalidInterfaceException
439
-     * @throws ReflectionException
440
-     */
441
-    public function percent()
442
-    {
443
-        return $this->get('LIN_percent');
444
-    }
445
-
446
-
447
-    /**
448
-     * @return string
449
-     * @throws EE_Error
450
-     * @throws ReflectionException
451
-     * @since $VID:$
452
-     */
453
-    public function prettyPercent(): string
454
-    {
455
-        return $this->get_pretty('LIN_percent');
456
-    }
457
-
458
-
459
-    /**
460
-     * Sets percent (between 100-0.01)
461
-     *
462
-     * @param float $percent
463
-     * @throws EE_Error
464
-     * @throws InvalidArgumentException
465
-     * @throws InvalidDataTypeException
466
-     * @throws InvalidInterfaceException
467
-     * @throws ReflectionException
468
-     */
469
-    public function set_percent($percent)
470
-    {
471
-        $this->set('LIN_percent', $percent);
472
-    }
473
-
474
-
475
-    /**
476
-     * Gets total
477
-     *
478
-     * @return float
479
-     * @throws EE_Error
480
-     * @throws InvalidArgumentException
481
-     * @throws InvalidDataTypeException
482
-     * @throws InvalidInterfaceException
483
-     * @throws ReflectionException
484
-     */
485
-    public function pretaxTotal(): float
486
-    {
487
-        return (float) $this->get('LIN_pretax');
488
-    }
489
-
490
-
491
-    /**
492
-     * Sets total
493
-     *
494
-     * @param float $pretax_total
495
-     * @throws EE_Error
496
-     * @throws InvalidArgumentException
497
-     * @throws InvalidDataTypeException
498
-     * @throws InvalidInterfaceException
499
-     * @throws ReflectionException
500
-     */
501
-    public function setPretaxTotal(float $pretax_total)
502
-    {
503
-        $this->set('LIN_pretax', $pretax_total);
504
-    }
505
-
506
-
507
-    /**
508
-     * @return float
509
-     * @throws EE_Error
510
-     * @throws ReflectionException
511
-     * @since  $VID:$
512
-     */
513
-    public function totalWithTax(): float
514
-    {
515
-        return (float) $this->get('LIN_total');
516
-    }
517
-
518
-
519
-    /**
520
-     * Sets total
521
-     *
522
-     * @param float $total
523
-     * @throws EE_Error
524
-     * @throws ReflectionException
525
-     * @since  $VID:$
526
-     */
527
-    public function setTotalWithTax(float $total)
528
-    {
529
-        $this->set('LIN_total', $total);
530
-    }
531
-
532
-
533
-    /**
534
-     * Gets total
535
-     *
536
-     * @return float
537
-     * @throws EE_Error
538
-     * @throws ReflectionException
539
-     * @deprecatd $VID:$
540
-     */
541
-    public function total(): float
542
-    {
543
-        return $this->totalWithTax();
544
-    }
545
-
546
-
547
-    /**
548
-     * Sets total
549
-     *
550
-     * @param float $total
551
-     * @throws EE_Error
552
-     * @throws ReflectionException
553
-     * @deprecatd $VID:$
554
-     */
555
-    public function set_total($total)
556
-    {
557
-        $this->setTotalWithTax($total);
558
-    }
559
-
560
-
561
-    /**
562
-     * Gets order
563
-     *
564
-     * @return int
565
-     * @throws EE_Error
566
-     * @throws InvalidArgumentException
567
-     * @throws InvalidDataTypeException
568
-     * @throws InvalidInterfaceException
569
-     * @throws ReflectionException
570
-     */
571
-    public function order()
572
-    {
573
-        return $this->get('LIN_order');
574
-    }
575
-
576
-
577
-    /**
578
-     * Sets order
579
-     *
580
-     * @param int $order
581
-     * @throws EE_Error
582
-     * @throws InvalidArgumentException
583
-     * @throws InvalidDataTypeException
584
-     * @throws InvalidInterfaceException
585
-     * @throws ReflectionException
586
-     */
587
-    public function set_order($order)
588
-    {
589
-        $this->set('LIN_order', $order);
590
-    }
591
-
592
-
593
-    /**
594
-     * Gets parent
595
-     *
596
-     * @return int
597
-     * @throws EE_Error
598
-     * @throws InvalidArgumentException
599
-     * @throws InvalidDataTypeException
600
-     * @throws InvalidInterfaceException
601
-     * @throws ReflectionException
602
-     */
603
-    public function parent_ID()
604
-    {
605
-        return $this->get('LIN_parent');
606
-    }
607
-
608
-
609
-    /**
610
-     * Sets parent
611
-     *
612
-     * @param int $parent
613
-     * @throws EE_Error
614
-     * @throws InvalidArgumentException
615
-     * @throws InvalidDataTypeException
616
-     * @throws InvalidInterfaceException
617
-     * @throws ReflectionException
618
-     */
619
-    public function set_parent_ID($parent)
620
-    {
621
-        $this->set('LIN_parent', $parent);
622
-    }
623
-
624
-
625
-    /**
626
-     * Gets type
627
-     *
628
-     * @return string
629
-     * @throws EE_Error
630
-     * @throws InvalidArgumentException
631
-     * @throws InvalidDataTypeException
632
-     * @throws InvalidInterfaceException
633
-     * @throws ReflectionException
634
-     */
635
-    public function type()
636
-    {
637
-        return $this->get('LIN_type');
638
-    }
639
-
640
-
641
-    /**
642
-     * Sets type
643
-     *
644
-     * @param string $type
645
-     * @throws EE_Error
646
-     * @throws InvalidArgumentException
647
-     * @throws InvalidDataTypeException
648
-     * @throws InvalidInterfaceException
649
-     * @throws ReflectionException
650
-     */
651
-    public function set_type($type)
652
-    {
653
-        $this->set('LIN_type', $type);
654
-    }
655
-
656
-
657
-    /**
658
-     * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
659
-     * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
660
-     * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
661
-     * or indirectly by `EE_Line_item::add_child_line_item()`)
662
-     *
663
-     * @return EE_Base_Class|EE_Line_Item
664
-     * @throws EE_Error
665
-     * @throws InvalidArgumentException
666
-     * @throws InvalidDataTypeException
667
-     * @throws InvalidInterfaceException
668
-     * @throws ReflectionException
669
-     */
670
-    public function parent()
671
-    {
672
-        return $this->ID()
673
-            ? $this->get_model()->get_one_by_ID($this->parent_ID())
674
-            : $this->_parent;
675
-    }
676
-
677
-
678
-    /**
679
-     * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
680
-     *
681
-     * @return EE_Line_Item[]
682
-     * @throws EE_Error
683
-     * @throws InvalidArgumentException
684
-     * @throws InvalidDataTypeException
685
-     * @throws InvalidInterfaceException
686
-     * @throws ReflectionException
687
-     */
688
-    public function children(array $query_params = []): array
689
-    {
690
-        if ($this->ID()) {
691
-            // ensure where params are an array
692
-            $query_params[0] = $query_params[0] ?? [];
693
-            // add defaults for line item parent and orderby
694
-            $query_params[0] += ['LIN_parent' => $this->ID()];
695
-            $query_params += ['order_by' => ['LIN_order' => 'ASC']];
696
-            return $this->get_model()->get_all($query_params);
697
-        }
698
-        if (! is_array($this->_children)) {
699
-            $this->_children = array();
700
-        }
701
-        return $this->_children;
702
-    }
703
-
704
-
705
-    /**
706
-     * Gets code
707
-     *
708
-     * @return string
709
-     * @throws EE_Error
710
-     * @throws InvalidArgumentException
711
-     * @throws InvalidDataTypeException
712
-     * @throws InvalidInterfaceException
713
-     * @throws ReflectionException
714
-     */
715
-    public function code()
716
-    {
717
-        return $this->get('LIN_code');
718
-    }
719
-
720
-
721
-    /**
722
-     * Sets code
723
-     *
724
-     * @param string $code
725
-     * @throws EE_Error
726
-     * @throws InvalidArgumentException
727
-     * @throws InvalidDataTypeException
728
-     * @throws InvalidInterfaceException
729
-     * @throws ReflectionException
730
-     */
731
-    public function set_code($code)
732
-    {
733
-        $this->set('LIN_code', $code);
734
-    }
735
-
736
-
737
-    /**
738
-     * Gets is_taxable
739
-     *
740
-     * @return boolean
741
-     * @throws EE_Error
742
-     * @throws InvalidArgumentException
743
-     * @throws InvalidDataTypeException
744
-     * @throws InvalidInterfaceException
745
-     * @throws ReflectionException
746
-     */
747
-    public function is_taxable()
748
-    {
749
-        return $this->get('LIN_is_taxable');
750
-    }
751
-
752
-
753
-    /**
754
-     * Sets is_taxable
755
-     *
756
-     * @param boolean $is_taxable
757
-     * @throws EE_Error
758
-     * @throws InvalidArgumentException
759
-     * @throws InvalidDataTypeException
760
-     * @throws InvalidInterfaceException
761
-     * @throws ReflectionException
762
-     */
763
-    public function set_is_taxable($is_taxable)
764
-    {
765
-        $this->set('LIN_is_taxable', $is_taxable);
766
-    }
767
-
768
-
769
-    /**
770
-     * @param int $timestamp
771
-     * @throws EE_Error
772
-     * @throws ReflectionException
773
-     * @since $VID:$
774
-     */
775
-    public function setTimestamp(int $timestamp)
776
-    {
777
-        $this->set('LIN_timestamp', $timestamp);
778
-    }
779
-
780
-
781
-    /**
782
-     * Gets the object that this model-joins-to.
783
-     * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
784
-     * EEM_Promotion_Object
785
-     *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
786
-     *
787
-     * @return EE_Base_Class | NULL
788
-     * @throws EE_Error
789
-     * @throws InvalidArgumentException
790
-     * @throws InvalidDataTypeException
791
-     * @throws InvalidInterfaceException
792
-     * @throws ReflectionException
793
-     */
794
-    public function get_object()
795
-    {
796
-        $model_name_of_related_obj = $this->OBJ_type();
797
-        return $this->get_model()->has_relation($model_name_of_related_obj)
798
-            ? $this->get_first_related($model_name_of_related_obj)
799
-            : null;
800
-    }
801
-
802
-
803
-    /**
804
-     * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
805
-     * (IE, if this line item is for a price or something else, will return NULL)
806
-     *
807
-     * @param array $query_params
808
-     * @return EE_Base_Class|EE_Ticket
809
-     * @throws EE_Error
810
-     * @throws InvalidArgumentException
811
-     * @throws InvalidDataTypeException
812
-     * @throws InvalidInterfaceException
813
-     * @throws ReflectionException
814
-     */
815
-    public function ticket($query_params = array())
816
-    {
817
-        // we're going to assume that when this method is called
818
-        // we always want to receive the attached ticket EVEN if that ticket is archived.
819
-        // This can be overridden via the incoming $query_params argument
820
-        $remove_defaults = array('default_where_conditions' => 'none');
821
-        $query_params = array_merge($remove_defaults, $query_params);
822
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
823
-    }
824
-
825
-
826
-    /**
827
-     * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
828
-     *
829
-     * @return EE_Datetime | NULL
830
-     * @throws EE_Error
831
-     * @throws InvalidArgumentException
832
-     * @throws InvalidDataTypeException
833
-     * @throws InvalidInterfaceException
834
-     * @throws ReflectionException
835
-     */
836
-    public function get_ticket_datetime()
837
-    {
838
-        if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
839
-            $ticket = $this->ticket();
840
-            if ($ticket instanceof EE_Ticket) {
841
-                $datetime = $ticket->first_datetime();
842
-                if ($datetime instanceof EE_Datetime) {
843
-                    return $datetime;
844
-                }
845
-            }
846
-        }
847
-        return null;
848
-    }
849
-
850
-
851
-    /**
852
-     * Gets the event's name that's related to the ticket, if this is for
853
-     * a ticket
854
-     *
855
-     * @return string
856
-     * @throws EE_Error
857
-     * @throws InvalidArgumentException
858
-     * @throws InvalidDataTypeException
859
-     * @throws InvalidInterfaceException
860
-     * @throws ReflectionException
861
-     */
862
-    public function ticket_event_name()
863
-    {
864
-        $event_name = esc_html__('Unknown', 'event_espresso');
865
-        $event = $this->ticket_event();
866
-        if ($event instanceof EE_Event) {
867
-            $event_name = $event->name();
868
-        }
869
-        return $event_name;
870
-    }
871
-
872
-
873
-    /**
874
-     * Gets the event that's related to the ticket, if this line item represents a ticket.
875
-     *
876
-     * @return EE_Event|null
877
-     * @throws EE_Error
878
-     * @throws InvalidArgumentException
879
-     * @throws InvalidDataTypeException
880
-     * @throws InvalidInterfaceException
881
-     * @throws ReflectionException
882
-     */
883
-    public function ticket_event()
884
-    {
885
-        $event = null;
886
-        $ticket = $this->ticket();
887
-        if ($ticket instanceof EE_Ticket) {
888
-            $datetime = $ticket->first_datetime();
889
-            if ($datetime instanceof EE_Datetime) {
890
-                $event = $datetime->event();
891
-            }
892
-        }
893
-        return $event;
894
-    }
895
-
896
-
897
-    /**
898
-     * Gets the first datetime for this lien item, assuming it's for a ticket
899
-     *
900
-     * @param string $date_format
901
-     * @param string $time_format
902
-     * @return string
903
-     * @throws EE_Error
904
-     * @throws InvalidArgumentException
905
-     * @throws InvalidDataTypeException
906
-     * @throws InvalidInterfaceException
907
-     * @throws ReflectionException
908
-     */
909
-    public function ticket_datetime_start($date_format = '', $time_format = '')
910
-    {
911
-        $first_datetime_string = esc_html__('Unknown', 'event_espresso');
912
-        $datetime = $this->get_ticket_datetime();
913
-        if ($datetime) {
914
-            $first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
915
-        }
916
-        return $first_datetime_string;
917
-    }
918
-
919
-
920
-    /**
921
-     * Adds the line item as a child to this line item. If there is another child line
922
-     * item with the same LIN_code, it is overwritten by this new one
923
-     *
924
-     * @param EE_Line_Item $line_item
925
-     * @param bool          $set_order
926
-     * @return bool success
927
-     * @throws EE_Error
928
-     * @throws InvalidArgumentException
929
-     * @throws InvalidDataTypeException
930
-     * @throws InvalidInterfaceException
931
-     * @throws ReflectionException
932
-     */
933
-    public function add_child_line_item(EE_Line_Item $line_item, $set_order = true)
934
-    {
935
-        // should we calculate the LIN_order for this line item ?
936
-        if ($set_order || $line_item->order() === null) {
937
-            $line_item->set_order(count($this->children()));
938
-        }
939
-        if ($this->ID()) {
940
-            // check for any duplicate line items (with the same code), if so, this replaces it
941
-            $line_item_with_same_code = $this->get_child_line_item($line_item->code());
942
-            if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
943
-                $this->delete_child_line_item($line_item_with_same_code->code());
944
-            }
945
-            $line_item->set_parent_ID($this->ID());
946
-            if ($this->TXN_ID()) {
947
-                $line_item->set_TXN_ID($this->TXN_ID());
948
-            }
949
-            return $line_item->save();
950
-        }
951
-        $this->_children[ $line_item->code() ] = $line_item;
952
-        if ($line_item->parent() !== $this) {
953
-            $line_item->set_parent($this);
954
-        }
955
-        return true;
956
-    }
957
-
958
-
959
-    /**
960
-     * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
961
-     * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
962
-     * However, if this line item is NOT saved to the DB, this just caches the parent on
963
-     * the EE_Line_Item::_parent property.
964
-     *
965
-     * @param EE_Line_Item $line_item
966
-     * @throws EE_Error
967
-     * @throws InvalidArgumentException
968
-     * @throws InvalidDataTypeException
969
-     * @throws InvalidInterfaceException
970
-     * @throws ReflectionException
971
-     */
972
-    public function set_parent($line_item)
973
-    {
974
-        if ($this->ID()) {
975
-            if (! $line_item->ID()) {
976
-                $line_item->save();
977
-            }
978
-            $this->set_parent_ID($line_item->ID());
979
-            $this->save();
980
-        } else {
981
-            $this->_parent = $line_item;
982
-            $this->set_parent_ID($line_item->ID());
983
-        }
984
-    }
985
-
986
-
987
-    /**
988
-     * Gets the child line item as specified by its code. Because this returns an object (by reference)
989
-     * you can modify this child line item and the parent (this object) can know about them
990
-     * because it also has a reference to that line item
991
-     *
992
-     * @param string $code
993
-     * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
994
-     * @throws EE_Error
995
-     * @throws InvalidArgumentException
996
-     * @throws InvalidDataTypeException
997
-     * @throws InvalidInterfaceException
998
-     * @throws ReflectionException
999
-     */
1000
-    public function get_child_line_item($code)
1001
-    {
1002
-        if ($this->ID()) {
1003
-            return $this->get_model()->get_one(
1004
-                array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
1005
-            );
1006
-        }
1007
-        return isset($this->_children[ $code ])
1008
-            ? $this->_children[ $code ]
1009
-            : null;
1010
-    }
1011
-
1012
-
1013
-    /**
1014
-     * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
1015
-     * cached on it)
1016
-     *
1017
-     * @return int
1018
-     * @throws EE_Error
1019
-     * @throws InvalidArgumentException
1020
-     * @throws InvalidDataTypeException
1021
-     * @throws InvalidInterfaceException
1022
-     * @throws ReflectionException
1023
-     */
1024
-    public function delete_children_line_items()
1025
-    {
1026
-        if ($this->ID()) {
1027
-            return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
1028
-        }
1029
-        $count = count($this->_children);
1030
-        $this->_children = array();
1031
-        return $count;
1032
-    }
1033
-
1034
-
1035
-    /**
1036
-     * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
1037
-     * HAS NOT been saved to the DB, removes the child line item with index $code.
1038
-     * Also searches through the child's children for a matching line item. However, once a line item has been found
1039
-     * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
1040
-     * deleted)
1041
-     *
1042
-     * @param string $code
1043
-     * @param bool   $stop_search_once_found
1044
-     * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
1045
-     *             the DB yet)
1046
-     * @throws EE_Error
1047
-     * @throws InvalidArgumentException
1048
-     * @throws InvalidDataTypeException
1049
-     * @throws InvalidInterfaceException
1050
-     * @throws ReflectionException
1051
-     */
1052
-    public function delete_child_line_item($code, $stop_search_once_found = true)
1053
-    {
1054
-        if ($this->ID()) {
1055
-            $items_deleted = 0;
1056
-            if ($this->code() === $code) {
1057
-                $items_deleted += EEH_Line_Item::delete_all_child_items($this);
1058
-                $items_deleted += (int) $this->delete();
1059
-                if ($stop_search_once_found) {
1060
-                    return $items_deleted;
1061
-                }
1062
-            }
1063
-            foreach ($this->children() as $child_line_item) {
1064
-                $items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
1065
-            }
1066
-            return $items_deleted;
1067
-        }
1068
-        if (isset($this->_children[ $code ])) {
1069
-            unset($this->_children[ $code ]);
1070
-            return 1;
1071
-        }
1072
-        return 0;
1073
-    }
1074
-
1075
-
1076
-    /**
1077
-     * If this line item is in the database, is of the type subtotal, and
1078
-     * has no children, why do we have it? It should be deleted so this function
1079
-     * does that
1080
-     *
1081
-     * @return boolean
1082
-     * @throws EE_Error
1083
-     * @throws InvalidArgumentException
1084
-     * @throws InvalidDataTypeException
1085
-     * @throws InvalidInterfaceException
1086
-     * @throws ReflectionException
1087
-     */
1088
-    public function delete_if_childless_subtotal()
1089
-    {
1090
-        if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
1091
-            return $this->delete();
1092
-        }
1093
-        return false;
1094
-    }
1095
-
1096
-
1097
-    /**
1098
-     * Creates a code and returns a string. doesn't assign the code to this model object
1099
-     *
1100
-     * @return string
1101
-     * @throws EE_Error
1102
-     * @throws InvalidArgumentException
1103
-     * @throws InvalidDataTypeException
1104
-     * @throws InvalidInterfaceException
1105
-     * @throws ReflectionException
1106
-     */
1107
-    public function generate_code()
1108
-    {
1109
-        // each line item in the cart requires a unique identifier
1110
-        return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1111
-    }
1112
-
1113
-
1114
-    /**
1115
-     * @return bool
1116
-     * @throws EE_Error
1117
-     * @throws InvalidArgumentException
1118
-     * @throws InvalidDataTypeException
1119
-     * @throws InvalidInterfaceException
1120
-     * @throws ReflectionException
1121
-     */
1122
-    public function isGlobalTax(): bool
1123
-    {
1124
-        return $this->type() === EEM_Line_Item::type_tax;
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * @return bool
1130
-     * @throws EE_Error
1131
-     * @throws InvalidArgumentException
1132
-     * @throws InvalidDataTypeException
1133
-     * @throws InvalidInterfaceException
1134
-     * @throws ReflectionException
1135
-     */
1136
-    public function isSubTax(): bool
1137
-    {
1138
-        return $this->type() === EEM_Line_Item::type_sub_tax;
1139
-    }
1140
-
1141
-
1142
-    /**
1143
-     * returns true if this is a line item with a direct descendent of the type sub-tax
1144
-     *
1145
-     * @return array
1146
-     * @throws EE_Error
1147
-     * @throws InvalidArgumentException
1148
-     * @throws InvalidDataTypeException
1149
-     * @throws InvalidInterfaceException
1150
-     * @throws ReflectionException
1151
-     */
1152
-    public function getSubTaxes(): array
1153
-    {
1154
-        if (! $this->is_line_item()) {
1155
-            return [];
1156
-        }
1157
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
1158
-    }
1159
-
1160
-
1161
-    /**
1162
-     * returns true if this is a line item with a direct descendent of the type sub-tax
1163
-     *
1164
-     * @return bool
1165
-     * @throws EE_Error
1166
-     * @throws InvalidArgumentException
1167
-     * @throws InvalidDataTypeException
1168
-     * @throws InvalidInterfaceException
1169
-     * @throws ReflectionException
1170
-     */
1171
-    public function hasSubTaxes(): bool
1172
-    {
1173
-        if (! $this->is_line_item()) {
1174
-            return false;
1175
-        }
1176
-        $sub_taxes = $this->getSubTaxes();
1177
-        return ! empty($sub_taxes);
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * @return bool
1183
-     * @throws EE_Error
1184
-     * @throws ReflectionException
1185
-     * @deprecated   $VID:$
1186
-     */
1187
-    public function is_tax(): bool
1188
-    {
1189
-        return $this->isGlobalTax();
1190
-    }
1191
-
1192
-
1193
-    /**
1194
-     * @return bool
1195
-     * @throws EE_Error
1196
-     * @throws InvalidArgumentException
1197
-     * @throws InvalidDataTypeException
1198
-     * @throws InvalidInterfaceException
1199
-     * @throws ReflectionException
1200
-     */
1201
-    public function is_tax_sub_total()
1202
-    {
1203
-        return $this->type() === EEM_Line_Item::type_tax_sub_total;
1204
-    }
1205
-
1206
-
1207
-    /**
1208
-     * @return bool
1209
-     * @throws EE_Error
1210
-     * @throws InvalidArgumentException
1211
-     * @throws InvalidDataTypeException
1212
-     * @throws InvalidInterfaceException
1213
-     * @throws ReflectionException
1214
-     */
1215
-    public function is_line_item()
1216
-    {
1217
-        return $this->type() === EEM_Line_Item::type_line_item;
1218
-    }
1219
-
1220
-
1221
-    /**
1222
-     * @return bool
1223
-     * @throws EE_Error
1224
-     * @throws InvalidArgumentException
1225
-     * @throws InvalidDataTypeException
1226
-     * @throws InvalidInterfaceException
1227
-     * @throws ReflectionException
1228
-     */
1229
-    public function is_sub_line_item()
1230
-    {
1231
-        return $this->type() === EEM_Line_Item::type_sub_line_item;
1232
-    }
1233
-
1234
-
1235
-    /**
1236
-     * @return bool
1237
-     * @throws EE_Error
1238
-     * @throws InvalidArgumentException
1239
-     * @throws InvalidDataTypeException
1240
-     * @throws InvalidInterfaceException
1241
-     * @throws ReflectionException
1242
-     */
1243
-    public function is_sub_total()
1244
-    {
1245
-        return $this->type() === EEM_Line_Item::type_sub_total;
1246
-    }
1247
-
1248
-
1249
-    /**
1250
-     * Whether or not this line item is a cancellation line item
1251
-     *
1252
-     * @return boolean
1253
-     * @throws EE_Error
1254
-     * @throws InvalidArgumentException
1255
-     * @throws InvalidDataTypeException
1256
-     * @throws InvalidInterfaceException
1257
-     * @throws ReflectionException
1258
-     */
1259
-    public function is_cancellation()
1260
-    {
1261
-        return EEM_Line_Item::type_cancellation === $this->type();
1262
-    }
1263
-
1264
-
1265
-    /**
1266
-     * @return bool
1267
-     * @throws EE_Error
1268
-     * @throws InvalidArgumentException
1269
-     * @throws InvalidDataTypeException
1270
-     * @throws InvalidInterfaceException
1271
-     * @throws ReflectionException
1272
-     */
1273
-    public function is_total()
1274
-    {
1275
-        return $this->type() === EEM_Line_Item::type_total;
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * @return bool
1281
-     * @throws EE_Error
1282
-     * @throws InvalidArgumentException
1283
-     * @throws InvalidDataTypeException
1284
-     * @throws InvalidInterfaceException
1285
-     * @throws ReflectionException
1286
-     */
1287
-    public function is_cancelled()
1288
-    {
1289
-        return $this->type() === EEM_Line_Item::type_cancellation;
1290
-    }
1291
-
1292
-
1293
-    /**
1294
-     * @return string like '2, 004.00', formatted according to the localized currency
1295
-     * @throws EE_Error
1296
-     * @throws ReflectionException
1297
-     */
1298
-    public function unit_price_no_code(): string
1299
-    {
1300
-        return $this->prettyUnitPrice();
1301
-    }
1302
-
1303
-
1304
-    /**
1305
-     * @return string like '2, 004.00', formatted according to the localized currency
1306
-     * @throws EE_Error
1307
-     * @throws ReflectionException
1308
-     * @since $VID:$
1309
-     */
1310
-    public function prettyUnitPrice(): string
1311
-    {
1312
-        return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1313
-    }
1314
-
1315
-
1316
-    /**
1317
-     * @return string like '2, 004.00', formatted according to the localized currency
1318
-     * @throws EE_Error
1319
-     * @throws ReflectionException
1320
-     */
1321
-    public function total_no_code(): string
1322
-    {
1323
-        return $this->prettyTotal();
1324
-    }
1325
-
1326
-
1327
-    /**
1328
-     * @return string like '2, 004.00', formatted according to the localized currency
1329
-     * @throws EE_Error
1330
-     * @throws ReflectionException
1331
-     * @since $VID:$
1332
-     */
1333
-    public function prettyTotal(): string
1334
-    {
1335
-        return $this->get_pretty('LIN_total', 'no_currency_code');
1336
-    }
1337
-
1338
-
1339
-    /**
1340
-     * Gets the final total on this item, taking taxes into account.
1341
-     * Has the side-effect of setting the sub-total as it was just calculated.
1342
-     * If this is used on a grand-total line item, also updates the transaction's
1343
-     * TXN_total (provided this line item is allowed to persist, otherwise we don't
1344
-     * want to change a persistable transaction with info from a non-persistent line item)
1345
-     *
1346
-     * @param bool $update_txn_status
1347
-     * @return float
1348
-     * @throws EE_Error
1349
-     * @throws InvalidArgumentException
1350
-     * @throws InvalidDataTypeException
1351
-     * @throws InvalidInterfaceException
1352
-     * @throws ReflectionException
1353
-     * @throws RuntimeException
1354
-     */
1355
-    public function recalculate_total_including_taxes(bool $update_txn_status = false): float
1356
-    {
1357
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1358
-        return $this->calculator->recalculateTotalIncludingTaxes($grand_total_line_item, $update_txn_status);
1359
-    }
1360
-
1361
-
1362
-    /**
1363
-     * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1364
-     * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1365
-     * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1366
-     * when this is called on the grand total
1367
-     *
1368
-     * @return float
1369
-     * @throws EE_Error
1370
-     * @throws InvalidArgumentException
1371
-     * @throws InvalidDataTypeException
1372
-     * @throws InvalidInterfaceException
1373
-     * @throws ReflectionException
1374
-     */
1375
-    public function recalculate_pre_tax_total(): float
1376
-    {
1377
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1378
-        [$total] = $this->calculator->recalculateLineItemTotals($grand_total_line_item);
1379
-        return (float) $total;
1380
-    }
1381
-
1382
-
1383
-    /**
1384
-     * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1385
-     * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1386
-     * and tax sub-total if already in the DB
1387
-     *
1388
-     * @return float
1389
-     * @throws EE_Error
1390
-     * @throws InvalidArgumentException
1391
-     * @throws InvalidDataTypeException
1392
-     * @throws InvalidInterfaceException
1393
-     * @throws ReflectionException
1394
-     */
1395
-    public function recalculate_taxes_and_tax_total(): float
1396
-    {
1397
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1398
-        return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1399
-    }
1400
-
1401
-
1402
-    /**
1403
-     * Gets the total tax on this line item. Assumes taxes have already been calculated using
1404
-     * recalculate_taxes_and_total
1405
-     *
1406
-     * @return float
1407
-     * @throws EE_Error
1408
-     * @throws InvalidArgumentException
1409
-     * @throws InvalidDataTypeException
1410
-     * @throws InvalidInterfaceException
1411
-     * @throws ReflectionException
1412
-     */
1413
-    public function get_total_tax()
1414
-    {
1415
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1416
-        return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1417
-    }
1418
-
1419
-
1420
-    /**
1421
-     * Gets the total for all the items purchased only
1422
-     *
1423
-     * @return float
1424
-     * @throws EE_Error
1425
-     * @throws InvalidArgumentException
1426
-     * @throws InvalidDataTypeException
1427
-     * @throws InvalidInterfaceException
1428
-     * @throws ReflectionException
1429
-     */
1430
-    public function get_items_total()
1431
-    {
1432
-        // by default, let's make sure we're consistent with the existing line item
1433
-        if ($this->is_total()) {
1434
-            return $this->pretaxTotal();
1435
-        }
1436
-        $total = 0;
1437
-        foreach ($this->get_items() as $item) {
1438
-            if ($item instanceof EE_Line_Item) {
1439
-                $total += $item->pretaxTotal();
1440
-            }
1441
-        }
1442
-        return $total;
1443
-    }
1444
-
1445
-
1446
-    /**
1447
-     * Gets all the descendants (ie, children or children of children etc) that
1448
-     * are of the type 'tax'
1449
-     *
1450
-     * @return EE_Line_Item[]
1451
-     * @throws EE_Error
1452
-     */
1453
-    public function tax_descendants()
1454
-    {
1455
-        return EEH_Line_Item::get_tax_descendants($this);
1456
-    }
1457
-
1458
-
1459
-    /**
1460
-     * Gets all the real items purchased which are children of this item
1461
-     *
1462
-     * @return EE_Line_Item[]
1463
-     * @throws EE_Error
1464
-     */
1465
-    public function get_items()
1466
-    {
1467
-        return EEH_Line_Item::get_line_item_descendants($this);
1468
-    }
1469
-
1470
-
1471
-    /**
1472
-     * Returns the amount taxable among this line item's children (or if it has no children,
1473
-     * how much of it is taxable). Does not recalculate totals or subtotals.
1474
-     * If the taxable total is negative, (eg, if none of the tickets were taxable,
1475
-     * but there is a "Taxable" discount), returns 0.
1476
-     *
1477
-     * @return float
1478
-     * @throws EE_Error
1479
-     * @throws InvalidArgumentException
1480
-     * @throws InvalidDataTypeException
1481
-     * @throws InvalidInterfaceException
1482
-     * @throws ReflectionException
1483
-     */
1484
-    public function taxable_total(): float
1485
-    {
1486
-        return $this->calculator->taxableAmountForGlobalTaxes($this);
1487
-    }
1488
-
1489
-
1490
-    /**
1491
-     * Gets the transaction for this line item
1492
-     *
1493
-     * @return EE_Base_Class|EE_Transaction
1494
-     * @throws EE_Error
1495
-     * @throws InvalidArgumentException
1496
-     * @throws InvalidDataTypeException
1497
-     * @throws InvalidInterfaceException
1498
-     * @throws ReflectionException
1499
-     */
1500
-    public function transaction()
1501
-    {
1502
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1503
-    }
1504
-
1505
-
1506
-    /**
1507
-     * Saves this line item to the DB, and recursively saves its descendants.
1508
-     * Because there currently is no proper parent-child relation on the model,
1509
-     * save_this_and_cached() will NOT save the descendants.
1510
-     * Also sets the transaction on this line item and all its descendants before saving
1511
-     *
1512
-     * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1513
-     * @return int count of items saved
1514
-     * @throws EE_Error
1515
-     * @throws InvalidArgumentException
1516
-     * @throws InvalidDataTypeException
1517
-     * @throws InvalidInterfaceException
1518
-     * @throws ReflectionException
1519
-     */
1520
-    public function save_this_and_descendants_to_txn($txn_id = null)
1521
-    {
1522
-        $count = 0;
1523
-        if (! $txn_id) {
1524
-            $txn_id = $this->TXN_ID();
1525
-        }
1526
-        $this->set_TXN_ID($txn_id);
1527
-        $children = $this->children();
1528
-        $count += $this->save()
1529
-            ? 1
1530
-            : 0;
1531
-        foreach ($children as $child_line_item) {
1532
-            if ($child_line_item instanceof EE_Line_Item) {
1533
-                $child_line_item->set_parent_ID($this->ID());
1534
-                $count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1535
-            }
1536
-        }
1537
-        return $count;
1538
-    }
1539
-
1540
-
1541
-    /**
1542
-     * Saves this line item to the DB, and recursively saves its descendants.
1543
-     *
1544
-     * @return int count of items saved
1545
-     * @throws EE_Error
1546
-     * @throws InvalidArgumentException
1547
-     * @throws InvalidDataTypeException
1548
-     * @throws InvalidInterfaceException
1549
-     * @throws ReflectionException
1550
-     */
1551
-    public function save_this_and_descendants()
1552
-    {
1553
-        $count = 0;
1554
-        $children = $this->children();
1555
-        $count += $this->save()
1556
-            ? 1
1557
-            : 0;
1558
-        foreach ($children as $child_line_item) {
1559
-            if ($child_line_item instanceof EE_Line_Item) {
1560
-                $child_line_item->set_parent_ID($this->ID());
1561
-                $count += $child_line_item->save_this_and_descendants();
1562
-            }
1563
-        }
1564
-        return $count;
1565
-    }
1566
-
1567
-
1568
-    /**
1569
-     * returns the cancellation line item if this item was cancelled
1570
-     *
1571
-     * @return EE_Line_Item[]
1572
-     * @throws InvalidArgumentException
1573
-     * @throws InvalidInterfaceException
1574
-     * @throws InvalidDataTypeException
1575
-     * @throws ReflectionException
1576
-     * @throws EE_Error
1577
-     */
1578
-    public function get_cancellations()
1579
-    {
1580
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1581
-    }
1582
-
1583
-
1584
-    /**
1585
-     * If this item has an ID, then this saves it again to update the db
1586
-     *
1587
-     * @return int count of items saved
1588
-     * @throws EE_Error
1589
-     * @throws InvalidArgumentException
1590
-     * @throws InvalidDataTypeException
1591
-     * @throws InvalidInterfaceException
1592
-     * @throws ReflectionException
1593
-     */
1594
-    public function maybe_save()
1595
-    {
1596
-        if ($this->ID()) {
1597
-            return $this->save();
1598
-        }
1599
-        return false;
1600
-    }
1601
-
1602
-
1603
-    /**
1604
-     * clears the cached children and parent from the line item
1605
-     *
1606
-     * @return void
1607
-     */
1608
-    public function clear_related_line_item_cache()
1609
-    {
1610
-        $this->_children = array();
1611
-        $this->_parent = null;
1612
-    }
1613
-
1614
-
1615
-    /**
1616
-     * @param bool $raw
1617
-     * @return int
1618
-     * @throws EE_Error
1619
-     * @throws InvalidArgumentException
1620
-     * @throws InvalidDataTypeException
1621
-     * @throws InvalidInterfaceException
1622
-     * @throws ReflectionException
1623
-     */
1624
-    public function timestamp($raw = false)
1625
-    {
1626
-        return $raw
1627
-            ? $this->get_raw('LIN_timestamp')
1628
-            : $this->get('LIN_timestamp');
1629
-    }
1630
-
1631
-
1632
-
1633
-
1634
-    /************************* DEPRECATED *************************/
1635
-    /**
1636
-     * @deprecated 4.6.0
1637
-     * @param string $type one of the constants on EEM_Line_Item
1638
-     * @return EE_Line_Item[]
1639
-     * @throws EE_Error
1640
-     */
1641
-    protected function _get_descendants_of_type($type)
1642
-    {
1643
-        EE_Error::doing_it_wrong(
1644
-            'EE_Line_Item::_get_descendants_of_type()',
1645
-            sprintf(
1646
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1647
-                'EEH_Line_Item::get_descendants_of_type()'
1648
-            ),
1649
-            '4.6.0'
1650
-        );
1651
-        return EEH_Line_Item::get_descendants_of_type($this, $type);
1652
-    }
1653
-
1654
-
1655
-    /**
1656
-     * @deprecated 4.6.0
1657
-     * @param string $type like one of the EEM_Line_Item::type_*
1658
-     * @return EE_Line_Item
1659
-     * @throws EE_Error
1660
-     * @throws InvalidArgumentException
1661
-     * @throws InvalidDataTypeException
1662
-     * @throws InvalidInterfaceException
1663
-     * @throws ReflectionException
1664
-     */
1665
-    public function get_nearest_descendant_of_type(string $type): EE_Line_Item
1666
-    {
1667
-        EE_Error::doing_it_wrong(
1668
-            'EE_Line_Item::get_nearest_descendant_of_type()',
1669
-            sprintf(
1670
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1671
-                'EEH_Line_Item::get_nearest_descendant_of_type()'
1672
-            ),
1673
-            '4.6.0'
1674
-        );
1675
-        return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1676
-    }
18
+	/**
19
+	 * for children line items (currently not a normal relation)
20
+	 *
21
+	 * @type EE_Line_Item[]
22
+	 */
23
+	protected $_children = array();
24
+
25
+	/**
26
+	 * for the parent line item
27
+	 *
28
+	 * @var EE_Line_Item
29
+	 */
30
+	protected $_parent;
31
+
32
+	/**
33
+	 * @var LineItemCalculator
34
+	 */
35
+	protected $calculator;
36
+
37
+
38
+	/**
39
+	 * @param array  $props_n_values          incoming values
40
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
41
+	 *                                        used.)
42
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
43
+	 *                                        date_format and the second value is the time format
44
+	 * @return EE_Line_Item
45
+	 * @throws EE_Error
46
+	 * @throws InvalidArgumentException
47
+	 * @throws InvalidDataTypeException
48
+	 * @throws InvalidInterfaceException
49
+	 * @throws ReflectionException
50
+	 */
51
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
+	{
53
+		$has_object = parent::_check_for_object(
54
+			$props_n_values,
55
+			__CLASS__,
56
+			$timezone,
57
+			$date_formats
58
+		);
59
+		return $has_object
60
+			? $has_object
61
+			: new self($props_n_values, false, $timezone);
62
+	}
63
+
64
+
65
+	/**
66
+	 * @param array  $props_n_values  incoming values from the database
67
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
68
+	 *                                the website will be used.
69
+	 * @return EE_Line_Item
70
+	 * @throws EE_Error
71
+	 * @throws InvalidArgumentException
72
+	 * @throws InvalidDataTypeException
73
+	 * @throws InvalidInterfaceException
74
+	 * @throws ReflectionException
75
+	 */
76
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
77
+	{
78
+		return new self($props_n_values, true, $timezone);
79
+	}
80
+
81
+
82
+	/**
83
+	 * Adds some defaults if they're not specified
84
+	 *
85
+	 * @param array  $fieldValues
86
+	 * @param bool   $bydb
87
+	 * @param string $timezone
88
+	 * @throws EE_Error
89
+	 * @throws InvalidArgumentException
90
+	 * @throws InvalidDataTypeException
91
+	 * @throws InvalidInterfaceException
92
+	 * @throws ReflectionException
93
+	 */
94
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
95
+	{
96
+		$this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
97
+		parent::__construct($fieldValues, $bydb, $timezone);
98
+		if (! $this->get('LIN_code')) {
99
+			$this->set_code($this->generate_code());
100
+		}
101
+	}
102
+
103
+
104
+	public function __wakeup()
105
+	{
106
+		$this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
107
+		parent::__wakeup();
108
+	}
109
+
110
+
111
+	/**
112
+	 * Gets ID
113
+	 *
114
+	 * @return int
115
+	 * @throws EE_Error
116
+	 * @throws InvalidArgumentException
117
+	 * @throws InvalidDataTypeException
118
+	 * @throws InvalidInterfaceException
119
+	 * @throws ReflectionException
120
+	 */
121
+	public function ID()
122
+	{
123
+		return $this->get('LIN_ID');
124
+	}
125
+
126
+
127
+	/**
128
+	 * Gets TXN_ID
129
+	 *
130
+	 * @return int
131
+	 * @throws EE_Error
132
+	 * @throws InvalidArgumentException
133
+	 * @throws InvalidDataTypeException
134
+	 * @throws InvalidInterfaceException
135
+	 * @throws ReflectionException
136
+	 */
137
+	public function TXN_ID()
138
+	{
139
+		return $this->get('TXN_ID');
140
+	}
141
+
142
+
143
+	/**
144
+	 * Sets TXN_ID
145
+	 *
146
+	 * @param int $TXN_ID
147
+	 * @throws EE_Error
148
+	 * @throws InvalidArgumentException
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws InvalidInterfaceException
151
+	 * @throws ReflectionException
152
+	 */
153
+	public function set_TXN_ID($TXN_ID)
154
+	{
155
+		$this->set('TXN_ID', $TXN_ID);
156
+	}
157
+
158
+
159
+	/**
160
+	 * Gets name
161
+	 *
162
+	 * @return string
163
+	 * @throws EE_Error
164
+	 * @throws InvalidArgumentException
165
+	 * @throws InvalidDataTypeException
166
+	 * @throws InvalidInterfaceException
167
+	 * @throws ReflectionException
168
+	 */
169
+	public function name()
170
+	{
171
+		$name = $this->get('LIN_name');
172
+		if (! $name) {
173
+			$name = ucwords(str_replace('-', ' ', $this->type()));
174
+		}
175
+		return $name;
176
+	}
177
+
178
+
179
+	/**
180
+	 * Sets name
181
+	 *
182
+	 * @param string $name
183
+	 * @throws EE_Error
184
+	 * @throws InvalidArgumentException
185
+	 * @throws InvalidDataTypeException
186
+	 * @throws InvalidInterfaceException
187
+	 * @throws ReflectionException
188
+	 */
189
+	public function set_name($name)
190
+	{
191
+		$this->set('LIN_name', $name);
192
+	}
193
+
194
+
195
+	/**
196
+	 * Gets desc
197
+	 *
198
+	 * @return string
199
+	 * @throws EE_Error
200
+	 * @throws InvalidArgumentException
201
+	 * @throws InvalidDataTypeException
202
+	 * @throws InvalidInterfaceException
203
+	 * @throws ReflectionException
204
+	 */
205
+	public function desc()
206
+	{
207
+		return $this->get('LIN_desc');
208
+	}
209
+
210
+
211
+	/**
212
+	 * Sets desc
213
+	 *
214
+	 * @param string $desc
215
+	 * @throws EE_Error
216
+	 * @throws InvalidArgumentException
217
+	 * @throws InvalidDataTypeException
218
+	 * @throws InvalidInterfaceException
219
+	 * @throws ReflectionException
220
+	 */
221
+	public function set_desc($desc)
222
+	{
223
+		$this->set('LIN_desc', $desc);
224
+	}
225
+
226
+
227
+	/**
228
+	 * Gets quantity
229
+	 *
230
+	 * @return int
231
+	 * @throws EE_Error
232
+	 * @throws InvalidArgumentException
233
+	 * @throws InvalidDataTypeException
234
+	 * @throws InvalidInterfaceException
235
+	 * @throws ReflectionException
236
+	 */
237
+	public function quantity(): int
238
+	{
239
+		return (int) $this->get('LIN_quantity');
240
+	}
241
+
242
+
243
+	/**
244
+	 * Sets quantity
245
+	 *
246
+	 * @param int $quantity
247
+	 * @throws EE_Error
248
+	 * @throws InvalidArgumentException
249
+	 * @throws InvalidDataTypeException
250
+	 * @throws InvalidInterfaceException
251
+	 * @throws ReflectionException
252
+	 */
253
+	public function set_quantity($quantity)
254
+	{
255
+		$this->set('LIN_quantity', max($quantity, 0));
256
+	}
257
+
258
+
259
+	/**
260
+	 * Gets item_id
261
+	 *
262
+	 * @return int
263
+	 * @throws EE_Error
264
+	 * @throws InvalidArgumentException
265
+	 * @throws InvalidDataTypeException
266
+	 * @throws InvalidInterfaceException
267
+	 * @throws ReflectionException
268
+	 */
269
+	public function OBJ_ID()
270
+	{
271
+		return $this->get('OBJ_ID');
272
+	}
273
+
274
+
275
+	/**
276
+	 * Sets item_id
277
+	 *
278
+	 * @param int $item_id
279
+	 * @throws EE_Error
280
+	 * @throws InvalidArgumentException
281
+	 * @throws InvalidDataTypeException
282
+	 * @throws InvalidInterfaceException
283
+	 * @throws ReflectionException
284
+	 */
285
+	public function set_OBJ_ID($item_id)
286
+	{
287
+		$this->set('OBJ_ID', $item_id);
288
+	}
289
+
290
+
291
+	/**
292
+	 * Gets item_type
293
+	 *
294
+	 * @return string
295
+	 * @throws EE_Error
296
+	 * @throws InvalidArgumentException
297
+	 * @throws InvalidDataTypeException
298
+	 * @throws InvalidInterfaceException
299
+	 * @throws ReflectionException
300
+	 */
301
+	public function OBJ_type()
302
+	{
303
+		return $this->get('OBJ_type');
304
+	}
305
+
306
+
307
+	/**
308
+	 * Gets item_type
309
+	 *
310
+	 * @return string
311
+	 * @throws EE_Error
312
+	 * @throws InvalidArgumentException
313
+	 * @throws InvalidDataTypeException
314
+	 * @throws InvalidInterfaceException
315
+	 * @throws ReflectionException
316
+	 */
317
+	public function OBJ_type_i18n()
318
+	{
319
+		$obj_type = $this->OBJ_type();
320
+		switch ($obj_type) {
321
+			case EEM_Line_Item::OBJ_TYPE_EVENT:
322
+				$obj_type = esc_html__('Event', 'event_espresso');
323
+				break;
324
+			case EEM_Line_Item::OBJ_TYPE_PRICE:
325
+				$obj_type = esc_html__('Price', 'event_espresso');
326
+				break;
327
+			case EEM_Line_Item::OBJ_TYPE_PROMOTION:
328
+				$obj_type = esc_html__('Promotion', 'event_espresso');
329
+				break;
330
+			case EEM_Line_Item::OBJ_TYPE_TICKET:
331
+				$obj_type = esc_html__('Ticket', 'event_espresso');
332
+				break;
333
+			case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
334
+				$obj_type = esc_html__('Transaction', 'event_espresso');
335
+				break;
336
+		}
337
+		return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
338
+	}
339
+
340
+
341
+	/**
342
+	 * Sets item_type
343
+	 *
344
+	 * @param string $OBJ_type
345
+	 * @throws EE_Error
346
+	 * @throws InvalidArgumentException
347
+	 * @throws InvalidDataTypeException
348
+	 * @throws InvalidInterfaceException
349
+	 * @throws ReflectionException
350
+	 */
351
+	public function set_OBJ_type($OBJ_type)
352
+	{
353
+		$this->set('OBJ_type', $OBJ_type);
354
+	}
355
+
356
+
357
+	/**
358
+	 * Gets unit_price
359
+	 *
360
+	 * @return float
361
+	 * @throws EE_Error
362
+	 * @throws InvalidArgumentException
363
+	 * @throws InvalidDataTypeException
364
+	 * @throws InvalidInterfaceException
365
+	 * @throws ReflectionException
366
+	 */
367
+	public function unit_price()
368
+	{
369
+		return $this->get('LIN_unit_price');
370
+	}
371
+
372
+
373
+	/**
374
+	 * Sets unit_price
375
+	 *
376
+	 * @param float $unit_price
377
+	 * @throws EE_Error
378
+	 * @throws InvalidArgumentException
379
+	 * @throws InvalidDataTypeException
380
+	 * @throws InvalidInterfaceException
381
+	 * @throws ReflectionException
382
+	 */
383
+	public function set_unit_price($unit_price)
384
+	{
385
+		$this->set('LIN_unit_price', $unit_price);
386
+	}
387
+
388
+
389
+	/**
390
+	 * Checks if this item is a percentage modifier or not
391
+	 *
392
+	 * @return boolean
393
+	 * @throws EE_Error
394
+	 * @throws InvalidArgumentException
395
+	 * @throws InvalidDataTypeException
396
+	 * @throws InvalidInterfaceException
397
+	 * @throws ReflectionException
398
+	 */
399
+	public function is_percent()
400
+	{
401
+		if ($this->is_tax_sub_total()) {
402
+			// tax subtotals HAVE a percent on them, that percentage only applies
403
+			// to taxable items, so its' an exception. Treat it like a flat line item
404
+			return false;
405
+		}
406
+		$unit_price = abs($this->get('LIN_unit_price'));
407
+		$percent = abs($this->get('LIN_percent'));
408
+		if ($unit_price < .001 && $percent) {
409
+			return true;
410
+		}
411
+		if ($unit_price >= .001 && ! $percent) {
412
+			return false;
413
+		}
414
+		if ($unit_price >= .001 && $percent) {
415
+			throw new EE_Error(
416
+				sprintf(
417
+					esc_html__(
418
+						'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
419
+						'event_espresso'
420
+					),
421
+					$unit_price,
422
+					$percent
423
+				)
424
+			);
425
+		}
426
+		// if they're both 0, assume its not a percent item
427
+		return false;
428
+	}
429
+
430
+
431
+	/**
432
+	 * Gets percent (between 100-.001)
433
+	 *
434
+	 * @return float
435
+	 * @throws EE_Error
436
+	 * @throws InvalidArgumentException
437
+	 * @throws InvalidDataTypeException
438
+	 * @throws InvalidInterfaceException
439
+	 * @throws ReflectionException
440
+	 */
441
+	public function percent()
442
+	{
443
+		return $this->get('LIN_percent');
444
+	}
445
+
446
+
447
+	/**
448
+	 * @return string
449
+	 * @throws EE_Error
450
+	 * @throws ReflectionException
451
+	 * @since $VID:$
452
+	 */
453
+	public function prettyPercent(): string
454
+	{
455
+		return $this->get_pretty('LIN_percent');
456
+	}
457
+
458
+
459
+	/**
460
+	 * Sets percent (between 100-0.01)
461
+	 *
462
+	 * @param float $percent
463
+	 * @throws EE_Error
464
+	 * @throws InvalidArgumentException
465
+	 * @throws InvalidDataTypeException
466
+	 * @throws InvalidInterfaceException
467
+	 * @throws ReflectionException
468
+	 */
469
+	public function set_percent($percent)
470
+	{
471
+		$this->set('LIN_percent', $percent);
472
+	}
473
+
474
+
475
+	/**
476
+	 * Gets total
477
+	 *
478
+	 * @return float
479
+	 * @throws EE_Error
480
+	 * @throws InvalidArgumentException
481
+	 * @throws InvalidDataTypeException
482
+	 * @throws InvalidInterfaceException
483
+	 * @throws ReflectionException
484
+	 */
485
+	public function pretaxTotal(): float
486
+	{
487
+		return (float) $this->get('LIN_pretax');
488
+	}
489
+
490
+
491
+	/**
492
+	 * Sets total
493
+	 *
494
+	 * @param float $pretax_total
495
+	 * @throws EE_Error
496
+	 * @throws InvalidArgumentException
497
+	 * @throws InvalidDataTypeException
498
+	 * @throws InvalidInterfaceException
499
+	 * @throws ReflectionException
500
+	 */
501
+	public function setPretaxTotal(float $pretax_total)
502
+	{
503
+		$this->set('LIN_pretax', $pretax_total);
504
+	}
505
+
506
+
507
+	/**
508
+	 * @return float
509
+	 * @throws EE_Error
510
+	 * @throws ReflectionException
511
+	 * @since  $VID:$
512
+	 */
513
+	public function totalWithTax(): float
514
+	{
515
+		return (float) $this->get('LIN_total');
516
+	}
517
+
518
+
519
+	/**
520
+	 * Sets total
521
+	 *
522
+	 * @param float $total
523
+	 * @throws EE_Error
524
+	 * @throws ReflectionException
525
+	 * @since  $VID:$
526
+	 */
527
+	public function setTotalWithTax(float $total)
528
+	{
529
+		$this->set('LIN_total', $total);
530
+	}
531
+
532
+
533
+	/**
534
+	 * Gets total
535
+	 *
536
+	 * @return float
537
+	 * @throws EE_Error
538
+	 * @throws ReflectionException
539
+	 * @deprecatd $VID:$
540
+	 */
541
+	public function total(): float
542
+	{
543
+		return $this->totalWithTax();
544
+	}
545
+
546
+
547
+	/**
548
+	 * Sets total
549
+	 *
550
+	 * @param float $total
551
+	 * @throws EE_Error
552
+	 * @throws ReflectionException
553
+	 * @deprecatd $VID:$
554
+	 */
555
+	public function set_total($total)
556
+	{
557
+		$this->setTotalWithTax($total);
558
+	}
559
+
560
+
561
+	/**
562
+	 * Gets order
563
+	 *
564
+	 * @return int
565
+	 * @throws EE_Error
566
+	 * @throws InvalidArgumentException
567
+	 * @throws InvalidDataTypeException
568
+	 * @throws InvalidInterfaceException
569
+	 * @throws ReflectionException
570
+	 */
571
+	public function order()
572
+	{
573
+		return $this->get('LIN_order');
574
+	}
575
+
576
+
577
+	/**
578
+	 * Sets order
579
+	 *
580
+	 * @param int $order
581
+	 * @throws EE_Error
582
+	 * @throws InvalidArgumentException
583
+	 * @throws InvalidDataTypeException
584
+	 * @throws InvalidInterfaceException
585
+	 * @throws ReflectionException
586
+	 */
587
+	public function set_order($order)
588
+	{
589
+		$this->set('LIN_order', $order);
590
+	}
591
+
592
+
593
+	/**
594
+	 * Gets parent
595
+	 *
596
+	 * @return int
597
+	 * @throws EE_Error
598
+	 * @throws InvalidArgumentException
599
+	 * @throws InvalidDataTypeException
600
+	 * @throws InvalidInterfaceException
601
+	 * @throws ReflectionException
602
+	 */
603
+	public function parent_ID()
604
+	{
605
+		return $this->get('LIN_parent');
606
+	}
607
+
608
+
609
+	/**
610
+	 * Sets parent
611
+	 *
612
+	 * @param int $parent
613
+	 * @throws EE_Error
614
+	 * @throws InvalidArgumentException
615
+	 * @throws InvalidDataTypeException
616
+	 * @throws InvalidInterfaceException
617
+	 * @throws ReflectionException
618
+	 */
619
+	public function set_parent_ID($parent)
620
+	{
621
+		$this->set('LIN_parent', $parent);
622
+	}
623
+
624
+
625
+	/**
626
+	 * Gets type
627
+	 *
628
+	 * @return string
629
+	 * @throws EE_Error
630
+	 * @throws InvalidArgumentException
631
+	 * @throws InvalidDataTypeException
632
+	 * @throws InvalidInterfaceException
633
+	 * @throws ReflectionException
634
+	 */
635
+	public function type()
636
+	{
637
+		return $this->get('LIN_type');
638
+	}
639
+
640
+
641
+	/**
642
+	 * Sets type
643
+	 *
644
+	 * @param string $type
645
+	 * @throws EE_Error
646
+	 * @throws InvalidArgumentException
647
+	 * @throws InvalidDataTypeException
648
+	 * @throws InvalidInterfaceException
649
+	 * @throws ReflectionException
650
+	 */
651
+	public function set_type($type)
652
+	{
653
+		$this->set('LIN_type', $type);
654
+	}
655
+
656
+
657
+	/**
658
+	 * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
659
+	 * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
660
+	 * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
661
+	 * or indirectly by `EE_Line_item::add_child_line_item()`)
662
+	 *
663
+	 * @return EE_Base_Class|EE_Line_Item
664
+	 * @throws EE_Error
665
+	 * @throws InvalidArgumentException
666
+	 * @throws InvalidDataTypeException
667
+	 * @throws InvalidInterfaceException
668
+	 * @throws ReflectionException
669
+	 */
670
+	public function parent()
671
+	{
672
+		return $this->ID()
673
+			? $this->get_model()->get_one_by_ID($this->parent_ID())
674
+			: $this->_parent;
675
+	}
676
+
677
+
678
+	/**
679
+	 * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
680
+	 *
681
+	 * @return EE_Line_Item[]
682
+	 * @throws EE_Error
683
+	 * @throws InvalidArgumentException
684
+	 * @throws InvalidDataTypeException
685
+	 * @throws InvalidInterfaceException
686
+	 * @throws ReflectionException
687
+	 */
688
+	public function children(array $query_params = []): array
689
+	{
690
+		if ($this->ID()) {
691
+			// ensure where params are an array
692
+			$query_params[0] = $query_params[0] ?? [];
693
+			// add defaults for line item parent and orderby
694
+			$query_params[0] += ['LIN_parent' => $this->ID()];
695
+			$query_params += ['order_by' => ['LIN_order' => 'ASC']];
696
+			return $this->get_model()->get_all($query_params);
697
+		}
698
+		if (! is_array($this->_children)) {
699
+			$this->_children = array();
700
+		}
701
+		return $this->_children;
702
+	}
703
+
704
+
705
+	/**
706
+	 * Gets code
707
+	 *
708
+	 * @return string
709
+	 * @throws EE_Error
710
+	 * @throws InvalidArgumentException
711
+	 * @throws InvalidDataTypeException
712
+	 * @throws InvalidInterfaceException
713
+	 * @throws ReflectionException
714
+	 */
715
+	public function code()
716
+	{
717
+		return $this->get('LIN_code');
718
+	}
719
+
720
+
721
+	/**
722
+	 * Sets code
723
+	 *
724
+	 * @param string $code
725
+	 * @throws EE_Error
726
+	 * @throws InvalidArgumentException
727
+	 * @throws InvalidDataTypeException
728
+	 * @throws InvalidInterfaceException
729
+	 * @throws ReflectionException
730
+	 */
731
+	public function set_code($code)
732
+	{
733
+		$this->set('LIN_code', $code);
734
+	}
735
+
736
+
737
+	/**
738
+	 * Gets is_taxable
739
+	 *
740
+	 * @return boolean
741
+	 * @throws EE_Error
742
+	 * @throws InvalidArgumentException
743
+	 * @throws InvalidDataTypeException
744
+	 * @throws InvalidInterfaceException
745
+	 * @throws ReflectionException
746
+	 */
747
+	public function is_taxable()
748
+	{
749
+		return $this->get('LIN_is_taxable');
750
+	}
751
+
752
+
753
+	/**
754
+	 * Sets is_taxable
755
+	 *
756
+	 * @param boolean $is_taxable
757
+	 * @throws EE_Error
758
+	 * @throws InvalidArgumentException
759
+	 * @throws InvalidDataTypeException
760
+	 * @throws InvalidInterfaceException
761
+	 * @throws ReflectionException
762
+	 */
763
+	public function set_is_taxable($is_taxable)
764
+	{
765
+		$this->set('LIN_is_taxable', $is_taxable);
766
+	}
767
+
768
+
769
+	/**
770
+	 * @param int $timestamp
771
+	 * @throws EE_Error
772
+	 * @throws ReflectionException
773
+	 * @since $VID:$
774
+	 */
775
+	public function setTimestamp(int $timestamp)
776
+	{
777
+		$this->set('LIN_timestamp', $timestamp);
778
+	}
779
+
780
+
781
+	/**
782
+	 * Gets the object that this model-joins-to.
783
+	 * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
784
+	 * EEM_Promotion_Object
785
+	 *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
786
+	 *
787
+	 * @return EE_Base_Class | NULL
788
+	 * @throws EE_Error
789
+	 * @throws InvalidArgumentException
790
+	 * @throws InvalidDataTypeException
791
+	 * @throws InvalidInterfaceException
792
+	 * @throws ReflectionException
793
+	 */
794
+	public function get_object()
795
+	{
796
+		$model_name_of_related_obj = $this->OBJ_type();
797
+		return $this->get_model()->has_relation($model_name_of_related_obj)
798
+			? $this->get_first_related($model_name_of_related_obj)
799
+			: null;
800
+	}
801
+
802
+
803
+	/**
804
+	 * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
805
+	 * (IE, if this line item is for a price or something else, will return NULL)
806
+	 *
807
+	 * @param array $query_params
808
+	 * @return EE_Base_Class|EE_Ticket
809
+	 * @throws EE_Error
810
+	 * @throws InvalidArgumentException
811
+	 * @throws InvalidDataTypeException
812
+	 * @throws InvalidInterfaceException
813
+	 * @throws ReflectionException
814
+	 */
815
+	public function ticket($query_params = array())
816
+	{
817
+		// we're going to assume that when this method is called
818
+		// we always want to receive the attached ticket EVEN if that ticket is archived.
819
+		// This can be overridden via the incoming $query_params argument
820
+		$remove_defaults = array('default_where_conditions' => 'none');
821
+		$query_params = array_merge($remove_defaults, $query_params);
822
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
823
+	}
824
+
825
+
826
+	/**
827
+	 * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
828
+	 *
829
+	 * @return EE_Datetime | NULL
830
+	 * @throws EE_Error
831
+	 * @throws InvalidArgumentException
832
+	 * @throws InvalidDataTypeException
833
+	 * @throws InvalidInterfaceException
834
+	 * @throws ReflectionException
835
+	 */
836
+	public function get_ticket_datetime()
837
+	{
838
+		if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
839
+			$ticket = $this->ticket();
840
+			if ($ticket instanceof EE_Ticket) {
841
+				$datetime = $ticket->first_datetime();
842
+				if ($datetime instanceof EE_Datetime) {
843
+					return $datetime;
844
+				}
845
+			}
846
+		}
847
+		return null;
848
+	}
849
+
850
+
851
+	/**
852
+	 * Gets the event's name that's related to the ticket, if this is for
853
+	 * a ticket
854
+	 *
855
+	 * @return string
856
+	 * @throws EE_Error
857
+	 * @throws InvalidArgumentException
858
+	 * @throws InvalidDataTypeException
859
+	 * @throws InvalidInterfaceException
860
+	 * @throws ReflectionException
861
+	 */
862
+	public function ticket_event_name()
863
+	{
864
+		$event_name = esc_html__('Unknown', 'event_espresso');
865
+		$event = $this->ticket_event();
866
+		if ($event instanceof EE_Event) {
867
+			$event_name = $event->name();
868
+		}
869
+		return $event_name;
870
+	}
871
+
872
+
873
+	/**
874
+	 * Gets the event that's related to the ticket, if this line item represents a ticket.
875
+	 *
876
+	 * @return EE_Event|null
877
+	 * @throws EE_Error
878
+	 * @throws InvalidArgumentException
879
+	 * @throws InvalidDataTypeException
880
+	 * @throws InvalidInterfaceException
881
+	 * @throws ReflectionException
882
+	 */
883
+	public function ticket_event()
884
+	{
885
+		$event = null;
886
+		$ticket = $this->ticket();
887
+		if ($ticket instanceof EE_Ticket) {
888
+			$datetime = $ticket->first_datetime();
889
+			if ($datetime instanceof EE_Datetime) {
890
+				$event = $datetime->event();
891
+			}
892
+		}
893
+		return $event;
894
+	}
895
+
896
+
897
+	/**
898
+	 * Gets the first datetime for this lien item, assuming it's for a ticket
899
+	 *
900
+	 * @param string $date_format
901
+	 * @param string $time_format
902
+	 * @return string
903
+	 * @throws EE_Error
904
+	 * @throws InvalidArgumentException
905
+	 * @throws InvalidDataTypeException
906
+	 * @throws InvalidInterfaceException
907
+	 * @throws ReflectionException
908
+	 */
909
+	public function ticket_datetime_start($date_format = '', $time_format = '')
910
+	{
911
+		$first_datetime_string = esc_html__('Unknown', 'event_espresso');
912
+		$datetime = $this->get_ticket_datetime();
913
+		if ($datetime) {
914
+			$first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
915
+		}
916
+		return $first_datetime_string;
917
+	}
918
+
919
+
920
+	/**
921
+	 * Adds the line item as a child to this line item. If there is another child line
922
+	 * item with the same LIN_code, it is overwritten by this new one
923
+	 *
924
+	 * @param EE_Line_Item $line_item
925
+	 * @param bool          $set_order
926
+	 * @return bool success
927
+	 * @throws EE_Error
928
+	 * @throws InvalidArgumentException
929
+	 * @throws InvalidDataTypeException
930
+	 * @throws InvalidInterfaceException
931
+	 * @throws ReflectionException
932
+	 */
933
+	public function add_child_line_item(EE_Line_Item $line_item, $set_order = true)
934
+	{
935
+		// should we calculate the LIN_order for this line item ?
936
+		if ($set_order || $line_item->order() === null) {
937
+			$line_item->set_order(count($this->children()));
938
+		}
939
+		if ($this->ID()) {
940
+			// check for any duplicate line items (with the same code), if so, this replaces it
941
+			$line_item_with_same_code = $this->get_child_line_item($line_item->code());
942
+			if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
943
+				$this->delete_child_line_item($line_item_with_same_code->code());
944
+			}
945
+			$line_item->set_parent_ID($this->ID());
946
+			if ($this->TXN_ID()) {
947
+				$line_item->set_TXN_ID($this->TXN_ID());
948
+			}
949
+			return $line_item->save();
950
+		}
951
+		$this->_children[ $line_item->code() ] = $line_item;
952
+		if ($line_item->parent() !== $this) {
953
+			$line_item->set_parent($this);
954
+		}
955
+		return true;
956
+	}
957
+
958
+
959
+	/**
960
+	 * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
961
+	 * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
962
+	 * However, if this line item is NOT saved to the DB, this just caches the parent on
963
+	 * the EE_Line_Item::_parent property.
964
+	 *
965
+	 * @param EE_Line_Item $line_item
966
+	 * @throws EE_Error
967
+	 * @throws InvalidArgumentException
968
+	 * @throws InvalidDataTypeException
969
+	 * @throws InvalidInterfaceException
970
+	 * @throws ReflectionException
971
+	 */
972
+	public function set_parent($line_item)
973
+	{
974
+		if ($this->ID()) {
975
+			if (! $line_item->ID()) {
976
+				$line_item->save();
977
+			}
978
+			$this->set_parent_ID($line_item->ID());
979
+			$this->save();
980
+		} else {
981
+			$this->_parent = $line_item;
982
+			$this->set_parent_ID($line_item->ID());
983
+		}
984
+	}
985
+
986
+
987
+	/**
988
+	 * Gets the child line item as specified by its code. Because this returns an object (by reference)
989
+	 * you can modify this child line item and the parent (this object) can know about them
990
+	 * because it also has a reference to that line item
991
+	 *
992
+	 * @param string $code
993
+	 * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
994
+	 * @throws EE_Error
995
+	 * @throws InvalidArgumentException
996
+	 * @throws InvalidDataTypeException
997
+	 * @throws InvalidInterfaceException
998
+	 * @throws ReflectionException
999
+	 */
1000
+	public function get_child_line_item($code)
1001
+	{
1002
+		if ($this->ID()) {
1003
+			return $this->get_model()->get_one(
1004
+				array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
1005
+			);
1006
+		}
1007
+		return isset($this->_children[ $code ])
1008
+			? $this->_children[ $code ]
1009
+			: null;
1010
+	}
1011
+
1012
+
1013
+	/**
1014
+	 * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
1015
+	 * cached on it)
1016
+	 *
1017
+	 * @return int
1018
+	 * @throws EE_Error
1019
+	 * @throws InvalidArgumentException
1020
+	 * @throws InvalidDataTypeException
1021
+	 * @throws InvalidInterfaceException
1022
+	 * @throws ReflectionException
1023
+	 */
1024
+	public function delete_children_line_items()
1025
+	{
1026
+		if ($this->ID()) {
1027
+			return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
1028
+		}
1029
+		$count = count($this->_children);
1030
+		$this->_children = array();
1031
+		return $count;
1032
+	}
1033
+
1034
+
1035
+	/**
1036
+	 * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
1037
+	 * HAS NOT been saved to the DB, removes the child line item with index $code.
1038
+	 * Also searches through the child's children for a matching line item. However, once a line item has been found
1039
+	 * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
1040
+	 * deleted)
1041
+	 *
1042
+	 * @param string $code
1043
+	 * @param bool   $stop_search_once_found
1044
+	 * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
1045
+	 *             the DB yet)
1046
+	 * @throws EE_Error
1047
+	 * @throws InvalidArgumentException
1048
+	 * @throws InvalidDataTypeException
1049
+	 * @throws InvalidInterfaceException
1050
+	 * @throws ReflectionException
1051
+	 */
1052
+	public function delete_child_line_item($code, $stop_search_once_found = true)
1053
+	{
1054
+		if ($this->ID()) {
1055
+			$items_deleted = 0;
1056
+			if ($this->code() === $code) {
1057
+				$items_deleted += EEH_Line_Item::delete_all_child_items($this);
1058
+				$items_deleted += (int) $this->delete();
1059
+				if ($stop_search_once_found) {
1060
+					return $items_deleted;
1061
+				}
1062
+			}
1063
+			foreach ($this->children() as $child_line_item) {
1064
+				$items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
1065
+			}
1066
+			return $items_deleted;
1067
+		}
1068
+		if (isset($this->_children[ $code ])) {
1069
+			unset($this->_children[ $code ]);
1070
+			return 1;
1071
+		}
1072
+		return 0;
1073
+	}
1074
+
1075
+
1076
+	/**
1077
+	 * If this line item is in the database, is of the type subtotal, and
1078
+	 * has no children, why do we have it? It should be deleted so this function
1079
+	 * does that
1080
+	 *
1081
+	 * @return boolean
1082
+	 * @throws EE_Error
1083
+	 * @throws InvalidArgumentException
1084
+	 * @throws InvalidDataTypeException
1085
+	 * @throws InvalidInterfaceException
1086
+	 * @throws ReflectionException
1087
+	 */
1088
+	public function delete_if_childless_subtotal()
1089
+	{
1090
+		if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
1091
+			return $this->delete();
1092
+		}
1093
+		return false;
1094
+	}
1095
+
1096
+
1097
+	/**
1098
+	 * Creates a code and returns a string. doesn't assign the code to this model object
1099
+	 *
1100
+	 * @return string
1101
+	 * @throws EE_Error
1102
+	 * @throws InvalidArgumentException
1103
+	 * @throws InvalidDataTypeException
1104
+	 * @throws InvalidInterfaceException
1105
+	 * @throws ReflectionException
1106
+	 */
1107
+	public function generate_code()
1108
+	{
1109
+		// each line item in the cart requires a unique identifier
1110
+		return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1111
+	}
1112
+
1113
+
1114
+	/**
1115
+	 * @return bool
1116
+	 * @throws EE_Error
1117
+	 * @throws InvalidArgumentException
1118
+	 * @throws InvalidDataTypeException
1119
+	 * @throws InvalidInterfaceException
1120
+	 * @throws ReflectionException
1121
+	 */
1122
+	public function isGlobalTax(): bool
1123
+	{
1124
+		return $this->type() === EEM_Line_Item::type_tax;
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * @return bool
1130
+	 * @throws EE_Error
1131
+	 * @throws InvalidArgumentException
1132
+	 * @throws InvalidDataTypeException
1133
+	 * @throws InvalidInterfaceException
1134
+	 * @throws ReflectionException
1135
+	 */
1136
+	public function isSubTax(): bool
1137
+	{
1138
+		return $this->type() === EEM_Line_Item::type_sub_tax;
1139
+	}
1140
+
1141
+
1142
+	/**
1143
+	 * returns true if this is a line item with a direct descendent of the type sub-tax
1144
+	 *
1145
+	 * @return array
1146
+	 * @throws EE_Error
1147
+	 * @throws InvalidArgumentException
1148
+	 * @throws InvalidDataTypeException
1149
+	 * @throws InvalidInterfaceException
1150
+	 * @throws ReflectionException
1151
+	 */
1152
+	public function getSubTaxes(): array
1153
+	{
1154
+		if (! $this->is_line_item()) {
1155
+			return [];
1156
+		}
1157
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
1158
+	}
1159
+
1160
+
1161
+	/**
1162
+	 * returns true if this is a line item with a direct descendent of the type sub-tax
1163
+	 *
1164
+	 * @return bool
1165
+	 * @throws EE_Error
1166
+	 * @throws InvalidArgumentException
1167
+	 * @throws InvalidDataTypeException
1168
+	 * @throws InvalidInterfaceException
1169
+	 * @throws ReflectionException
1170
+	 */
1171
+	public function hasSubTaxes(): bool
1172
+	{
1173
+		if (! $this->is_line_item()) {
1174
+			return false;
1175
+		}
1176
+		$sub_taxes = $this->getSubTaxes();
1177
+		return ! empty($sub_taxes);
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * @return bool
1183
+	 * @throws EE_Error
1184
+	 * @throws ReflectionException
1185
+	 * @deprecated   $VID:$
1186
+	 */
1187
+	public function is_tax(): bool
1188
+	{
1189
+		return $this->isGlobalTax();
1190
+	}
1191
+
1192
+
1193
+	/**
1194
+	 * @return bool
1195
+	 * @throws EE_Error
1196
+	 * @throws InvalidArgumentException
1197
+	 * @throws InvalidDataTypeException
1198
+	 * @throws InvalidInterfaceException
1199
+	 * @throws ReflectionException
1200
+	 */
1201
+	public function is_tax_sub_total()
1202
+	{
1203
+		return $this->type() === EEM_Line_Item::type_tax_sub_total;
1204
+	}
1205
+
1206
+
1207
+	/**
1208
+	 * @return bool
1209
+	 * @throws EE_Error
1210
+	 * @throws InvalidArgumentException
1211
+	 * @throws InvalidDataTypeException
1212
+	 * @throws InvalidInterfaceException
1213
+	 * @throws ReflectionException
1214
+	 */
1215
+	public function is_line_item()
1216
+	{
1217
+		return $this->type() === EEM_Line_Item::type_line_item;
1218
+	}
1219
+
1220
+
1221
+	/**
1222
+	 * @return bool
1223
+	 * @throws EE_Error
1224
+	 * @throws InvalidArgumentException
1225
+	 * @throws InvalidDataTypeException
1226
+	 * @throws InvalidInterfaceException
1227
+	 * @throws ReflectionException
1228
+	 */
1229
+	public function is_sub_line_item()
1230
+	{
1231
+		return $this->type() === EEM_Line_Item::type_sub_line_item;
1232
+	}
1233
+
1234
+
1235
+	/**
1236
+	 * @return bool
1237
+	 * @throws EE_Error
1238
+	 * @throws InvalidArgumentException
1239
+	 * @throws InvalidDataTypeException
1240
+	 * @throws InvalidInterfaceException
1241
+	 * @throws ReflectionException
1242
+	 */
1243
+	public function is_sub_total()
1244
+	{
1245
+		return $this->type() === EEM_Line_Item::type_sub_total;
1246
+	}
1247
+
1248
+
1249
+	/**
1250
+	 * Whether or not this line item is a cancellation line item
1251
+	 *
1252
+	 * @return boolean
1253
+	 * @throws EE_Error
1254
+	 * @throws InvalidArgumentException
1255
+	 * @throws InvalidDataTypeException
1256
+	 * @throws InvalidInterfaceException
1257
+	 * @throws ReflectionException
1258
+	 */
1259
+	public function is_cancellation()
1260
+	{
1261
+		return EEM_Line_Item::type_cancellation === $this->type();
1262
+	}
1263
+
1264
+
1265
+	/**
1266
+	 * @return bool
1267
+	 * @throws EE_Error
1268
+	 * @throws InvalidArgumentException
1269
+	 * @throws InvalidDataTypeException
1270
+	 * @throws InvalidInterfaceException
1271
+	 * @throws ReflectionException
1272
+	 */
1273
+	public function is_total()
1274
+	{
1275
+		return $this->type() === EEM_Line_Item::type_total;
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * @return bool
1281
+	 * @throws EE_Error
1282
+	 * @throws InvalidArgumentException
1283
+	 * @throws InvalidDataTypeException
1284
+	 * @throws InvalidInterfaceException
1285
+	 * @throws ReflectionException
1286
+	 */
1287
+	public function is_cancelled()
1288
+	{
1289
+		return $this->type() === EEM_Line_Item::type_cancellation;
1290
+	}
1291
+
1292
+
1293
+	/**
1294
+	 * @return string like '2, 004.00', formatted according to the localized currency
1295
+	 * @throws EE_Error
1296
+	 * @throws ReflectionException
1297
+	 */
1298
+	public function unit_price_no_code(): string
1299
+	{
1300
+		return $this->prettyUnitPrice();
1301
+	}
1302
+
1303
+
1304
+	/**
1305
+	 * @return string like '2, 004.00', formatted according to the localized currency
1306
+	 * @throws EE_Error
1307
+	 * @throws ReflectionException
1308
+	 * @since $VID:$
1309
+	 */
1310
+	public function prettyUnitPrice(): string
1311
+	{
1312
+		return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1313
+	}
1314
+
1315
+
1316
+	/**
1317
+	 * @return string like '2, 004.00', formatted according to the localized currency
1318
+	 * @throws EE_Error
1319
+	 * @throws ReflectionException
1320
+	 */
1321
+	public function total_no_code(): string
1322
+	{
1323
+		return $this->prettyTotal();
1324
+	}
1325
+
1326
+
1327
+	/**
1328
+	 * @return string like '2, 004.00', formatted according to the localized currency
1329
+	 * @throws EE_Error
1330
+	 * @throws ReflectionException
1331
+	 * @since $VID:$
1332
+	 */
1333
+	public function prettyTotal(): string
1334
+	{
1335
+		return $this->get_pretty('LIN_total', 'no_currency_code');
1336
+	}
1337
+
1338
+
1339
+	/**
1340
+	 * Gets the final total on this item, taking taxes into account.
1341
+	 * Has the side-effect of setting the sub-total as it was just calculated.
1342
+	 * If this is used on a grand-total line item, also updates the transaction's
1343
+	 * TXN_total (provided this line item is allowed to persist, otherwise we don't
1344
+	 * want to change a persistable transaction with info from a non-persistent line item)
1345
+	 *
1346
+	 * @param bool $update_txn_status
1347
+	 * @return float
1348
+	 * @throws EE_Error
1349
+	 * @throws InvalidArgumentException
1350
+	 * @throws InvalidDataTypeException
1351
+	 * @throws InvalidInterfaceException
1352
+	 * @throws ReflectionException
1353
+	 * @throws RuntimeException
1354
+	 */
1355
+	public function recalculate_total_including_taxes(bool $update_txn_status = false): float
1356
+	{
1357
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1358
+		return $this->calculator->recalculateTotalIncludingTaxes($grand_total_line_item, $update_txn_status);
1359
+	}
1360
+
1361
+
1362
+	/**
1363
+	 * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1364
+	 * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1365
+	 * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1366
+	 * when this is called on the grand total
1367
+	 *
1368
+	 * @return float
1369
+	 * @throws EE_Error
1370
+	 * @throws InvalidArgumentException
1371
+	 * @throws InvalidDataTypeException
1372
+	 * @throws InvalidInterfaceException
1373
+	 * @throws ReflectionException
1374
+	 */
1375
+	public function recalculate_pre_tax_total(): float
1376
+	{
1377
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1378
+		[$total] = $this->calculator->recalculateLineItemTotals($grand_total_line_item);
1379
+		return (float) $total;
1380
+	}
1381
+
1382
+
1383
+	/**
1384
+	 * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1385
+	 * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1386
+	 * and tax sub-total if already in the DB
1387
+	 *
1388
+	 * @return float
1389
+	 * @throws EE_Error
1390
+	 * @throws InvalidArgumentException
1391
+	 * @throws InvalidDataTypeException
1392
+	 * @throws InvalidInterfaceException
1393
+	 * @throws ReflectionException
1394
+	 */
1395
+	public function recalculate_taxes_and_tax_total(): float
1396
+	{
1397
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1398
+		return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1399
+	}
1400
+
1401
+
1402
+	/**
1403
+	 * Gets the total tax on this line item. Assumes taxes have already been calculated using
1404
+	 * recalculate_taxes_and_total
1405
+	 *
1406
+	 * @return float
1407
+	 * @throws EE_Error
1408
+	 * @throws InvalidArgumentException
1409
+	 * @throws InvalidDataTypeException
1410
+	 * @throws InvalidInterfaceException
1411
+	 * @throws ReflectionException
1412
+	 */
1413
+	public function get_total_tax()
1414
+	{
1415
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1416
+		return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1417
+	}
1418
+
1419
+
1420
+	/**
1421
+	 * Gets the total for all the items purchased only
1422
+	 *
1423
+	 * @return float
1424
+	 * @throws EE_Error
1425
+	 * @throws InvalidArgumentException
1426
+	 * @throws InvalidDataTypeException
1427
+	 * @throws InvalidInterfaceException
1428
+	 * @throws ReflectionException
1429
+	 */
1430
+	public function get_items_total()
1431
+	{
1432
+		// by default, let's make sure we're consistent with the existing line item
1433
+		if ($this->is_total()) {
1434
+			return $this->pretaxTotal();
1435
+		}
1436
+		$total = 0;
1437
+		foreach ($this->get_items() as $item) {
1438
+			if ($item instanceof EE_Line_Item) {
1439
+				$total += $item->pretaxTotal();
1440
+			}
1441
+		}
1442
+		return $total;
1443
+	}
1444
+
1445
+
1446
+	/**
1447
+	 * Gets all the descendants (ie, children or children of children etc) that
1448
+	 * are of the type 'tax'
1449
+	 *
1450
+	 * @return EE_Line_Item[]
1451
+	 * @throws EE_Error
1452
+	 */
1453
+	public function tax_descendants()
1454
+	{
1455
+		return EEH_Line_Item::get_tax_descendants($this);
1456
+	}
1457
+
1458
+
1459
+	/**
1460
+	 * Gets all the real items purchased which are children of this item
1461
+	 *
1462
+	 * @return EE_Line_Item[]
1463
+	 * @throws EE_Error
1464
+	 */
1465
+	public function get_items()
1466
+	{
1467
+		return EEH_Line_Item::get_line_item_descendants($this);
1468
+	}
1469
+
1470
+
1471
+	/**
1472
+	 * Returns the amount taxable among this line item's children (or if it has no children,
1473
+	 * how much of it is taxable). Does not recalculate totals or subtotals.
1474
+	 * If the taxable total is negative, (eg, if none of the tickets were taxable,
1475
+	 * but there is a "Taxable" discount), returns 0.
1476
+	 *
1477
+	 * @return float
1478
+	 * @throws EE_Error
1479
+	 * @throws InvalidArgumentException
1480
+	 * @throws InvalidDataTypeException
1481
+	 * @throws InvalidInterfaceException
1482
+	 * @throws ReflectionException
1483
+	 */
1484
+	public function taxable_total(): float
1485
+	{
1486
+		return $this->calculator->taxableAmountForGlobalTaxes($this);
1487
+	}
1488
+
1489
+
1490
+	/**
1491
+	 * Gets the transaction for this line item
1492
+	 *
1493
+	 * @return EE_Base_Class|EE_Transaction
1494
+	 * @throws EE_Error
1495
+	 * @throws InvalidArgumentException
1496
+	 * @throws InvalidDataTypeException
1497
+	 * @throws InvalidInterfaceException
1498
+	 * @throws ReflectionException
1499
+	 */
1500
+	public function transaction()
1501
+	{
1502
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1503
+	}
1504
+
1505
+
1506
+	/**
1507
+	 * Saves this line item to the DB, and recursively saves its descendants.
1508
+	 * Because there currently is no proper parent-child relation on the model,
1509
+	 * save_this_and_cached() will NOT save the descendants.
1510
+	 * Also sets the transaction on this line item and all its descendants before saving
1511
+	 *
1512
+	 * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1513
+	 * @return int count of items saved
1514
+	 * @throws EE_Error
1515
+	 * @throws InvalidArgumentException
1516
+	 * @throws InvalidDataTypeException
1517
+	 * @throws InvalidInterfaceException
1518
+	 * @throws ReflectionException
1519
+	 */
1520
+	public function save_this_and_descendants_to_txn($txn_id = null)
1521
+	{
1522
+		$count = 0;
1523
+		if (! $txn_id) {
1524
+			$txn_id = $this->TXN_ID();
1525
+		}
1526
+		$this->set_TXN_ID($txn_id);
1527
+		$children = $this->children();
1528
+		$count += $this->save()
1529
+			? 1
1530
+			: 0;
1531
+		foreach ($children as $child_line_item) {
1532
+			if ($child_line_item instanceof EE_Line_Item) {
1533
+				$child_line_item->set_parent_ID($this->ID());
1534
+				$count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1535
+			}
1536
+		}
1537
+		return $count;
1538
+	}
1539
+
1540
+
1541
+	/**
1542
+	 * Saves this line item to the DB, and recursively saves its descendants.
1543
+	 *
1544
+	 * @return int count of items saved
1545
+	 * @throws EE_Error
1546
+	 * @throws InvalidArgumentException
1547
+	 * @throws InvalidDataTypeException
1548
+	 * @throws InvalidInterfaceException
1549
+	 * @throws ReflectionException
1550
+	 */
1551
+	public function save_this_and_descendants()
1552
+	{
1553
+		$count = 0;
1554
+		$children = $this->children();
1555
+		$count += $this->save()
1556
+			? 1
1557
+			: 0;
1558
+		foreach ($children as $child_line_item) {
1559
+			if ($child_line_item instanceof EE_Line_Item) {
1560
+				$child_line_item->set_parent_ID($this->ID());
1561
+				$count += $child_line_item->save_this_and_descendants();
1562
+			}
1563
+		}
1564
+		return $count;
1565
+	}
1566
+
1567
+
1568
+	/**
1569
+	 * returns the cancellation line item if this item was cancelled
1570
+	 *
1571
+	 * @return EE_Line_Item[]
1572
+	 * @throws InvalidArgumentException
1573
+	 * @throws InvalidInterfaceException
1574
+	 * @throws InvalidDataTypeException
1575
+	 * @throws ReflectionException
1576
+	 * @throws EE_Error
1577
+	 */
1578
+	public function get_cancellations()
1579
+	{
1580
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1581
+	}
1582
+
1583
+
1584
+	/**
1585
+	 * If this item has an ID, then this saves it again to update the db
1586
+	 *
1587
+	 * @return int count of items saved
1588
+	 * @throws EE_Error
1589
+	 * @throws InvalidArgumentException
1590
+	 * @throws InvalidDataTypeException
1591
+	 * @throws InvalidInterfaceException
1592
+	 * @throws ReflectionException
1593
+	 */
1594
+	public function maybe_save()
1595
+	{
1596
+		if ($this->ID()) {
1597
+			return $this->save();
1598
+		}
1599
+		return false;
1600
+	}
1601
+
1602
+
1603
+	/**
1604
+	 * clears the cached children and parent from the line item
1605
+	 *
1606
+	 * @return void
1607
+	 */
1608
+	public function clear_related_line_item_cache()
1609
+	{
1610
+		$this->_children = array();
1611
+		$this->_parent = null;
1612
+	}
1613
+
1614
+
1615
+	/**
1616
+	 * @param bool $raw
1617
+	 * @return int
1618
+	 * @throws EE_Error
1619
+	 * @throws InvalidArgumentException
1620
+	 * @throws InvalidDataTypeException
1621
+	 * @throws InvalidInterfaceException
1622
+	 * @throws ReflectionException
1623
+	 */
1624
+	public function timestamp($raw = false)
1625
+	{
1626
+		return $raw
1627
+			? $this->get_raw('LIN_timestamp')
1628
+			: $this->get('LIN_timestamp');
1629
+	}
1630
+
1631
+
1632
+
1633
+
1634
+	/************************* DEPRECATED *************************/
1635
+	/**
1636
+	 * @deprecated 4.6.0
1637
+	 * @param string $type one of the constants on EEM_Line_Item
1638
+	 * @return EE_Line_Item[]
1639
+	 * @throws EE_Error
1640
+	 */
1641
+	protected function _get_descendants_of_type($type)
1642
+	{
1643
+		EE_Error::doing_it_wrong(
1644
+			'EE_Line_Item::_get_descendants_of_type()',
1645
+			sprintf(
1646
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1647
+				'EEH_Line_Item::get_descendants_of_type()'
1648
+			),
1649
+			'4.6.0'
1650
+		);
1651
+		return EEH_Line_Item::get_descendants_of_type($this, $type);
1652
+	}
1653
+
1654
+
1655
+	/**
1656
+	 * @deprecated 4.6.0
1657
+	 * @param string $type like one of the EEM_Line_Item::type_*
1658
+	 * @return EE_Line_Item
1659
+	 * @throws EE_Error
1660
+	 * @throws InvalidArgumentException
1661
+	 * @throws InvalidDataTypeException
1662
+	 * @throws InvalidInterfaceException
1663
+	 * @throws ReflectionException
1664
+	 */
1665
+	public function get_nearest_descendant_of_type(string $type): EE_Line_Item
1666
+	{
1667
+		EE_Error::doing_it_wrong(
1668
+			'EE_Line_Item::get_nearest_descendant_of_type()',
1669
+			sprintf(
1670
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1671
+				'EEH_Line_Item::get_nearest_descendant_of_type()'
1672
+			),
1673
+			'4.6.0'
1674
+		);
1675
+		return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1676
+	}
1677 1677
 }
Please login to merge, or discard this patch.
core/helpers/EEH_Line_Item.helper.php 1 patch
Indentation   +2128 added lines, -2128 removed lines patch added patch discarded remove patch
@@ -21,2132 +21,2132 @@
 block discarded – undo
21 21
  */
22 22
 class EEH_Line_Item
23 23
 {
24
-    /**
25
-     * @var EE_Line_Item[]
26
-    */
27
-    private static $global_taxes;
28
-
29
-
30
-    /**
31
-     * Adds a simple item (unrelated to any other model object) to the provided PARENT line item.
32
-     * Does NOT automatically re-calculate the line item totals or update the related transaction.
33
-     * You should call recalculate_total_including_taxes() on the grant total line item after this
34
-     * to update the subtotals, and EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
35
-     * to keep the registration final prices in-sync with the transaction's total.
36
-     *
37
-     * @param EE_Line_Item $parent_line_item
38
-     * @param string       $name
39
-     * @param float        $unit_price
40
-     * @param string       $description
41
-     * @param int          $quantity
42
-     * @param boolean      $taxable
43
-     * @param string|null  $code if set to a value, ensures there is only one line item with that code
44
-     * @param bool         $return_item
45
-     * @param bool         $recalculate_totals
46
-     * @return boolean|EE_Line_Item success
47
-     * @throws EE_Error
48
-     * @throws ReflectionException
49
-     */
50
-    public static function add_unrelated_item(
51
-        EE_Line_Item $parent_line_item,
52
-        string $name,
53
-        float $unit_price,
54
-        string $description = '',
55
-        int $quantity = 1,
56
-        bool $taxable = false,
57
-        ?string $code = null,
58
-        bool $return_item = false,
59
-        bool $recalculate_totals = true
60
-    ) {
61
-        $items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
62
-        $line_item      = EE_Line_Item::new_instance(
63
-            [
64
-                'LIN_name'       => $name,
65
-                'LIN_desc'       => $description,
66
-                'LIN_unit_price' => $unit_price,
67
-                'LIN_quantity'   => $quantity,
68
-                'LIN_percent'    => null,
69
-                'LIN_is_taxable' => $taxable,
70
-                'LIN_order'      => $items_subtotal instanceof EE_Line_Item
71
-                    ? count($items_subtotal->children())
72
-                    : 0,
73
-                'LIN_total'      => (float) $unit_price * (int) $quantity,
74
-                'LIN_type'       => EEM_Line_Item::type_line_item,
75
-                'LIN_code'       => $code,
76
-            ]
77
-        );
78
-        $line_item      = apply_filters(
79
-            'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
80
-            $line_item,
81
-            $parent_line_item
82
-        );
83
-        $added          = self::add_item($parent_line_item, $line_item, $recalculate_totals);
84
-        return $return_item ? $line_item : $added;
85
-    }
86
-
87
-
88
-    /**
89
-     * Adds a simple item ( unrelated to any other model object) to the total line item,
90
-     * in the correct spot in the line item tree. Does not automatically
91
-     * re-calculate the line item totals, nor update the related transaction, nor upgrade the transaction's
92
-     * registrations' final prices (which should probably change because of this).
93
-     * You should call recalculate_total_including_taxes() on the grand total line item, then
94
-     * update the transaction's total, and EE_Registration_Processor::update_registration_final_prices()
95
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
96
-     *
97
-     * @param EE_Line_Item $parent_line_item
98
-     * @param string       $name
99
-     * @param float        $percentage_amount
100
-     * @param string       $description
101
-     * @param boolean      $taxable
102
-     * @param string|null  $code
103
-     * @param bool         $return_item
104
-     * @return boolean|EE_Line_Item success
105
-     * @throws EE_Error
106
-     * @throws ReflectionException
107
-     */
108
-    public static function add_percentage_based_item(
109
-        EE_Line_Item $parent_line_item,
110
-        string $name,
111
-        float $percentage_amount,
112
-        string $description = '',
113
-        bool $taxable = false,
114
-        ?string $code = null,
115
-        bool $return_item = false
116
-    ) {
117
-        $total = $percentage_amount * $parent_line_item->total() / 100;
118
-        $line_item = EE_Line_Item::new_instance(
119
-            [
120
-                'LIN_name'       => $name,
121
-                'LIN_desc'       => $description,
122
-                'LIN_unit_price' => 0,
123
-                'LIN_percent'    => $percentage_amount,
124
-                'LIN_quantity'   => 1,
125
-                'LIN_is_taxable' => $taxable,
126
-                'LIN_total'      => (float) $total,
127
-                'LIN_type'       => EEM_Line_Item::type_line_item,
128
-                'LIN_parent'     => $parent_line_item->ID(),
129
-                'LIN_code'       => $code,
130
-            ]
131
-        );
132
-        $line_item = apply_filters(
133
-            'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
134
-            $line_item
135
-        );
136
-        $added     = $parent_line_item->add_child_line_item($line_item, false);
137
-        return $return_item ? $line_item : $added;
138
-    }
139
-
140
-
141
-    /**
142
-     * Returns the new line item created by adding a purchase of the ticket
143
-     * ensures that ticket line item is saved, and that cart total has been recalculated.
144
-     * If this ticket has already been purchased, just increments its count.
145
-     * Automatically re-calculates the line item totals and updates the related transaction. But
146
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
147
-     * should probably change because of this).
148
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
149
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
150
-     *
151
-     * @param EE_Line_Item|null $total_line_item grand total line item of type EEM_Line_Item::type_total
152
-     * @param EE_Ticket         $ticket
153
-     * @param int               $qty
154
-     * @return EE_Line_Item
155
-     * @throws EE_Error
156
-     * @throws ReflectionException
157
-     */
158
-    public static function add_ticket_purchase(
159
-        ?EE_Line_Item $total_line_item,
160
-        EE_Ticket $ticket,
161
-        int $qty = 1
162
-    ): ?EE_Line_Item {
163
-        if (! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
164
-            throw new EE_Error(
165
-                sprintf(
166
-                    esc_html__(
167
-                        'A valid line item total is required in order to add tickets. A line item of type "%s" was passed.',
168
-                        'event_espresso'
169
-                    ),
170
-                    $ticket->ID(),
171
-                    $total_line_item->ID()
172
-                )
173
-            );
174
-        }
175
-        // either increment the qty for an existing ticket
176
-        $line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
177
-        // or add a new one
178
-        if (! $line_item instanceof EE_Line_Item) {
179
-            $line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
180
-        }
181
-        $total_line_item->recalculate_total_including_taxes();
182
-        return $line_item;
183
-    }
184
-
185
-
186
-    /**
187
-     * Returns the new line item created by adding a purchase of the ticket
188
-     *
189
-     * @param EE_Line_Item $total_line_item
190
-     * @param EE_Ticket    $ticket
191
-     * @param int          $qty
192
-     * @return EE_Line_Item
193
-     * @throws EE_Error
194
-     * @throws InvalidArgumentException
195
-     * @throws InvalidDataTypeException
196
-     * @throws InvalidInterfaceException
197
-     * @throws ReflectionException
198
-     */
199
-    public static function increment_ticket_qty_if_already_in_cart(
200
-        EE_Line_Item $total_line_item,
201
-        EE_Ticket $ticket,
202
-        $qty = 1
203
-    ) {
204
-        $line_item = null;
205
-        if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
206
-            $ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
207
-            foreach ($ticket_line_items as $ticket_line_item) {
208
-                if (
209
-                    $ticket_line_item instanceof EE_Line_Item
210
-                    && (int) $ticket_line_item->OBJ_ID() === (int) $ticket->ID()
211
-                ) {
212
-                    $line_item = $ticket_line_item;
213
-                    break;
214
-                }
215
-            }
216
-        }
217
-        if ($line_item instanceof EE_Line_Item) {
218
-            EEH_Line_Item::increment_quantity($line_item, $qty);
219
-            return $line_item;
220
-        }
221
-        return null;
222
-    }
223
-
224
-
225
-    /**
226
-     * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
227
-     * Does NOT save or recalculate other line items totals
228
-     *
229
-     * @param EE_Line_Item $line_item
230
-     * @param int          $qty
231
-     * @return void
232
-     * @throws EE_Error
233
-     * @throws InvalidArgumentException
234
-     * @throws InvalidDataTypeException
235
-     * @throws InvalidInterfaceException
236
-     * @throws ReflectionException
237
-     */
238
-    public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
239
-    {
240
-        if (! $line_item->is_percent()) {
241
-            $qty += $line_item->quantity();
242
-            $line_item->set_quantity($qty);
243
-            $line_item->set_total($line_item->unit_price() * $qty);
244
-            $line_item->save();
245
-        }
246
-        foreach ($line_item->children() as $child) {
247
-            if ($child->is_sub_line_item()) {
248
-                EEH_Line_Item::update_quantity($child, $qty);
249
-            }
250
-        }
251
-    }
252
-
253
-
254
-    /**
255
-     * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
256
-     * Does NOT save or recalculate other line items totals
257
-     *
258
-     * @param EE_Line_Item $line_item
259
-     * @param int          $qty
260
-     * @return void
261
-     * @throws EE_Error
262
-     * @throws InvalidArgumentException
263
-     * @throws InvalidDataTypeException
264
-     * @throws InvalidInterfaceException
265
-     * @throws ReflectionException
266
-     */
267
-    public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
268
-    {
269
-        if (! $line_item->is_percent()) {
270
-            $qty = $line_item->quantity() - $qty;
271
-            $qty = max($qty, 0);
272
-            $line_item->set_quantity($qty);
273
-            $line_item->set_total($line_item->unit_price() * $qty);
274
-            $line_item->save();
275
-        }
276
-        foreach ($line_item->children() as $child) {
277
-            if ($child->is_sub_line_item()) {
278
-                EEH_Line_Item::update_quantity($child, $qty);
279
-            }
280
-        }
281
-    }
282
-
283
-
284
-    /**
285
-     * Updates the line item and its children's quantities to the specified number.
286
-     * Does NOT save them or recalculate totals.
287
-     *
288
-     * @param EE_Line_Item $line_item
289
-     * @param int          $new_quantity
290
-     * @throws EE_Error
291
-     * @throws InvalidArgumentException
292
-     * @throws InvalidDataTypeException
293
-     * @throws InvalidInterfaceException
294
-     * @throws ReflectionException
295
-     */
296
-    public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
297
-    {
298
-        if (! $line_item->is_percent()) {
299
-            $line_item->set_quantity($new_quantity);
300
-            $line_item->set_total($line_item->unit_price() * $new_quantity);
301
-            $line_item->save();
302
-        }
303
-        foreach ($line_item->children() as $child) {
304
-            if ($child->is_sub_line_item()) {
305
-                EEH_Line_Item::update_quantity($child, $new_quantity);
306
-            }
307
-        }
308
-    }
309
-
310
-
311
-    /**
312
-     * Returns the new line item created by adding a purchase of the ticket
313
-     *
314
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
315
-     * @param EE_Ticket    $ticket
316
-     * @param int          $qty
317
-     * @return EE_Line_Item
318
-     * @throws EE_Error
319
-     * @throws InvalidArgumentException
320
-     * @throws InvalidDataTypeException
321
-     * @throws InvalidInterfaceException
322
-     * @throws ReflectionException
323
-     */
324
-    public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
325
-    {
326
-        $datetimes = $ticket->datetimes();
327
-        $first_datetime = reset($datetimes);
328
-        $first_datetime_name = esc_html__('Event', 'event_espresso');
329
-        if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
330
-            $first_datetime_name = $first_datetime->event()->name();
331
-        }
332
-        $event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
333
-        // get event subtotal line
334
-        $events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
335
-        $taxes = $ticket->tax_price_modifiers();
336
-        // add $ticket to cart
337
-        $line_item = EE_Line_Item::new_instance(array(
338
-            'LIN_name'       => $ticket->name(),
339
-            'LIN_desc'       => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
340
-            'LIN_unit_price' => $ticket->price(),
341
-            'LIN_quantity'   => $qty,
342
-            'LIN_is_taxable' => empty($taxes) && $ticket->taxable(),
343
-            'LIN_order'      => count($events_sub_total->children()),
344
-            'LIN_total'      => $ticket->price() * $qty,
345
-            'LIN_type'       => EEM_Line_Item::type_line_item,
346
-            'OBJ_ID'         => $ticket->ID(),
347
-            'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_TICKET,
348
-        ));
349
-        $line_item = apply_filters(
350
-            'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
351
-            $line_item
352
-        );
353
-        if (!$line_item instanceof EE_Line_Item) {
354
-            throw new DomainException(
355
-                esc_html__('Invalid EE_Line_Item received.', 'event_espresso')
356
-            );
357
-        }
358
-        $events_sub_total->add_child_line_item($line_item);
359
-        // now add the sub-line items
360
-        $running_total = 0;
361
-        $running_pre_tax_total = 0;
362
-        foreach ($ticket->prices() as $price) {
363
-            $sign = $price->is_discount() ? -1 : 1;
364
-            $price_total = $price->is_percent()
365
-                ? $running_pre_tax_total * $price->amount() / 100
366
-                : $price->amount() * $qty;
367
-            if ($price->is_percent()) {
368
-                $percent = $sign * $price->amount();
369
-                $unit_price = 0;
370
-            } else {
371
-                $percent    = 0;
372
-                $unit_price = $sign * $price->amount();
373
-            }
374
-            $sub_line_item = EE_Line_Item::new_instance(array(
375
-                'LIN_name'       => $price->name(),
376
-                'LIN_desc'       => $price->desc(),
377
-                'LIN_quantity'   => $price->is_percent() ? null : $qty,
378
-                'LIN_is_taxable' => false,
379
-                'LIN_order'      => $price->order(),
380
-                'LIN_total'      => $price_total,
381
-                'LIN_pretax'     => 0,
382
-                'LIN_unit_price' => $unit_price,
383
-                'LIN_percent'    => $percent,
384
-                'LIN_type'       => $price->is_tax() ? EEM_Line_Item::type_sub_tax : EEM_Line_Item::type_sub_line_item,
385
-                'OBJ_ID'         => $price->ID(),
386
-                'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
387
-            ));
388
-            $sub_line_item = apply_filters(
389
-                'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
390
-                $sub_line_item
391
-            );
392
-            $running_total += $sign * $price_total;
393
-            $running_pre_tax_total += ! $price->is_tax() ? $sign * $price_total : 0;
394
-            $line_item->add_child_line_item($sub_line_item);
395
-        }
396
-        $line_item->setPretaxTotal($running_pre_tax_total);
397
-        return $line_item;
398
-    }
399
-
400
-
401
-    /**
402
-     * Adds the specified item under the pre-tax-sub-total line item. Automatically
403
-     * re-calculates the line item totals and updates the related transaction. But
404
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
405
-     * should probably change because of this).
406
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
407
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
408
-     *
409
-     * @param EE_Line_Item $total_line_item
410
-     * @param EE_Line_Item $item to be added
411
-     * @return boolean
412
-     * @throws EE_Error
413
-     * @throws InvalidArgumentException
414
-     * @throws InvalidDataTypeException
415
-     * @throws InvalidInterfaceException
416
-     * @throws ReflectionException
417
-     */
418
-    public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item, $recalculate_totals = true)
419
-    {
420
-        $pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
421
-        if ($pre_tax_subtotal instanceof EE_Line_Item) {
422
-            $success = $pre_tax_subtotal->add_child_line_item($item);
423
-        } else {
424
-            return false;
425
-        }
426
-        if ($recalculate_totals) {
427
-            $total_line_item->recalculate_total_including_taxes();
428
-        }
429
-        return $success;
430
-    }
431
-
432
-
433
-    /**
434
-     * cancels an existing ticket line item,
435
-     * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
436
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
437
-     *
438
-     * @param EE_Line_Item $ticket_line_item
439
-     * @param int          $qty
440
-     * @return bool success
441
-     * @throws EE_Error
442
-     * @throws InvalidArgumentException
443
-     * @throws InvalidDataTypeException
444
-     * @throws InvalidInterfaceException
445
-     * @throws ReflectionException
446
-     */
447
-    public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
448
-    {
449
-        // validate incoming line_item
450
-        if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
451
-            throw new EE_Error(
452
-                sprintf(
453
-                    esc_html__(
454
-                        'The supplied line item must have an Object Type of "Ticket", not %1$s.',
455
-                        'event_espresso'
456
-                    ),
457
-                    $ticket_line_item->type()
458
-                )
459
-            );
460
-        }
461
-        if ($ticket_line_item->quantity() < $qty) {
462
-            throw new EE_Error(
463
-                sprintf(
464
-                    esc_html__(
465
-                        'Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.',
466
-                        'event_espresso'
467
-                    ),
468
-                    $qty,
469
-                    $ticket_line_item->quantity()
470
-                )
471
-            );
472
-        }
473
-        // decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
474
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
475
-        foreach ($ticket_line_item->children() as $child_line_item) {
476
-            if (
477
-                $child_line_item->is_sub_line_item()
478
-                && ! $child_line_item->is_percent()
479
-                && ! $child_line_item->is_cancellation()
480
-            ) {
481
-                $child_line_item->set_quantity($child_line_item->quantity() - $qty);
482
-            }
483
-        }
484
-        // get cancellation sub line item
485
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
486
-            $ticket_line_item,
487
-            EEM_Line_Item::type_cancellation
488
-        );
489
-        $cancellation_line_item = reset($cancellation_line_item);
490
-        // verify that this ticket was indeed previously cancelled
491
-        if ($cancellation_line_item instanceof EE_Line_Item) {
492
-            // increment cancelled quantity
493
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
494
-        } else {
495
-            // create cancellation sub line item
496
-            $cancellation_line_item = EE_Line_Item::new_instance(array(
497
-                'LIN_name'       => esc_html__('Cancellation', 'event_espresso'),
498
-                'LIN_desc'       => sprintf(
499
-                    esc_html_x(
500
-                        'Cancelled %1$s : %2$s',
501
-                        'Cancelled Ticket Name : 2015-01-01 11:11',
502
-                        'event_espresso'
503
-                    ),
504
-                    $ticket_line_item->name(),
505
-                    current_time(get_option('date_format') . ' ' . get_option('time_format'))
506
-                ),
507
-                'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
508
-                'LIN_quantity'   => $qty,
509
-                'LIN_is_taxable' => $ticket_line_item->is_taxable(),
510
-                'LIN_order'      => count($ticket_line_item->children()),
511
-                'LIN_total'      => 0, // $ticket_line_item->unit_price()
512
-                'LIN_type'       => EEM_Line_Item::type_cancellation,
513
-            ));
514
-            $ticket_line_item->add_child_line_item($cancellation_line_item);
515
-        }
516
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
517
-            // decrement parent line item quantity
518
-            $event_line_item = $ticket_line_item->parent();
519
-            if (
520
-                $event_line_item instanceof EE_Line_Item
521
-                && $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
522
-            ) {
523
-                $event_line_item->set_quantity($event_line_item->quantity() - $qty);
524
-                $event_line_item->save();
525
-            }
526
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
527
-            return true;
528
-        }
529
-        return false;
530
-    }
531
-
532
-
533
-    /**
534
-     * reinstates (un-cancels?) a previously canceled ticket line item,
535
-     * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
536
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
537
-     *
538
-     * @param EE_Line_Item $ticket_line_item
539
-     * @param int          $qty
540
-     * @return bool success
541
-     * @throws EE_Error
542
-     * @throws InvalidArgumentException
543
-     * @throws InvalidDataTypeException
544
-     * @throws InvalidInterfaceException
545
-     * @throws ReflectionException
546
-     */
547
-    public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
548
-    {
549
-        // validate incoming line_item
550
-        if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
551
-            throw new EE_Error(
552
-                sprintf(
553
-                    esc_html__(
554
-                        'The supplied line item must have an Object Type of "Ticket", not %1$s.',
555
-                        'event_espresso'
556
-                    ),
557
-                    $ticket_line_item->type()
558
-                )
559
-            );
560
-        }
561
-        // get cancellation sub line item
562
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
563
-            $ticket_line_item,
564
-            EEM_Line_Item::type_cancellation
565
-        );
566
-        $cancellation_line_item = reset($cancellation_line_item);
567
-        // verify that this ticket was indeed previously cancelled
568
-        if (! $cancellation_line_item instanceof EE_Line_Item) {
569
-            return false;
570
-        }
571
-        if ($cancellation_line_item->quantity() > $qty) {
572
-            // decrement cancelled quantity
573
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
574
-        } elseif ($cancellation_line_item->quantity() === $qty) {
575
-            // decrement cancelled quantity in case anyone still has the object kicking around
576
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
577
-            // delete because quantity will end up as 0
578
-            $cancellation_line_item->delete();
579
-            // and attempt to destroy the object,
580
-            // even though PHP won't actually destroy it until it needs the memory
581
-            unset($cancellation_line_item);
582
-        } else {
583
-            // what ?!?! negative quantity ?!?!
584
-            throw new EE_Error(
585
-                sprintf(
586
-                    esc_html__(
587
-                        'Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
588
-                        'event_espresso'
589
-                    ),
590
-                    $qty,
591
-                    $cancellation_line_item->quantity()
592
-                )
593
-            );
594
-        }
595
-        // increment ticket quantity
596
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
597
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
598
-            // increment parent line item quantity
599
-            $event_line_item = $ticket_line_item->parent();
600
-            if (
601
-                $event_line_item instanceof EE_Line_Item
602
-                && $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
603
-            ) {
604
-                $event_line_item->set_quantity($event_line_item->quantity() + $qty);
605
-            }
606
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
607
-            return true;
608
-        }
609
-        return false;
610
-    }
611
-
612
-
613
-    /**
614
-     * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
615
-     * then EE_Line_Item::recalculate_total_including_taxes() on the result
616
-     *
617
-     * @param EE_Line_Item $line_item
618
-     * @return float
619
-     * @throws EE_Error
620
-     * @throws InvalidArgumentException
621
-     * @throws InvalidDataTypeException
622
-     * @throws InvalidInterfaceException
623
-     * @throws ReflectionException
624
-     */
625
-    public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
626
-    {
627
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
628
-        return $grand_total_line_item->recalculate_total_including_taxes();
629
-    }
630
-
631
-
632
-    /**
633
-     * Gets the line item which contains the subtotal of all the items
634
-     *
635
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
636
-     * @return EE_Line_Item
637
-     * @throws EE_Error
638
-     * @throws InvalidArgumentException
639
-     * @throws InvalidDataTypeException
640
-     * @throws InvalidInterfaceException
641
-     * @throws ReflectionException
642
-     */
643
-    public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
644
-    {
645
-        $pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
646
-        return $pre_tax_subtotal instanceof EE_Line_Item
647
-            ? $pre_tax_subtotal
648
-            : self::create_pre_tax_subtotal($total_line_item);
649
-    }
650
-
651
-
652
-    /**
653
-     * Gets the line item for the taxes subtotal
654
-     *
655
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
656
-     * @return EE_Line_Item
657
-     * @throws EE_Error
658
-     * @throws InvalidArgumentException
659
-     * @throws InvalidDataTypeException
660
-     * @throws InvalidInterfaceException
661
-     * @throws ReflectionException
662
-     */
663
-    public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
664
-    {
665
-        $taxes = $total_line_item->get_child_line_item('taxes');
666
-        return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
667
-    }
668
-
669
-
670
-    /**
671
-     * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
672
-     *
673
-     * @param EE_Line_Item   $line_item
674
-     * @param EE_Transaction $transaction
675
-     * @return void
676
-     * @throws EE_Error
677
-     * @throws InvalidArgumentException
678
-     * @throws InvalidDataTypeException
679
-     * @throws InvalidInterfaceException
680
-     * @throws ReflectionException
681
-     */
682
-    public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = null)
683
-    {
684
-        if ($transaction) {
685
-            /** @type EEM_Transaction $EEM_Transaction */
686
-            $EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
687
-            $TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
688
-            $line_item->set_TXN_ID($TXN_ID);
689
-        }
690
-    }
691
-
692
-
693
-    /**
694
-     * Creates a new default total line item for the transaction,
695
-     * and its tickets subtotal and taxes subtotal line items (and adds the
696
-     * existing taxes as children of the taxes subtotal line item)
697
-     *
698
-     * @param EE_Transaction $transaction
699
-     * @return EE_Line_Item of type total
700
-     * @throws EE_Error
701
-     * @throws InvalidArgumentException
702
-     * @throws InvalidDataTypeException
703
-     * @throws InvalidInterfaceException
704
-     * @throws ReflectionException
705
-     */
706
-    public static function create_total_line_item($transaction = null)
707
-    {
708
-        $total_line_item = EE_Line_Item::new_instance(array(
709
-            'LIN_code' => 'total',
710
-            'LIN_name' => esc_html__('Grand Total', 'event_espresso'),
711
-            'LIN_type' => EEM_Line_Item::type_total,
712
-            'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TRANSACTION,
713
-        ));
714
-        $total_line_item = apply_filters(
715
-            'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
716
-            $total_line_item
717
-        );
718
-        self::set_TXN_ID($total_line_item, $transaction);
719
-        self::create_pre_tax_subtotal($total_line_item, $transaction);
720
-        self::create_taxes_subtotal($total_line_item, $transaction);
721
-        return $total_line_item;
722
-    }
723
-
724
-
725
-    /**
726
-     * Creates a default items subtotal line item
727
-     *
728
-     * @param EE_Line_Item   $total_line_item
729
-     * @param EE_Transaction $transaction
730
-     * @return EE_Line_Item
731
-     * @throws EE_Error
732
-     * @throws InvalidArgumentException
733
-     * @throws InvalidDataTypeException
734
-     * @throws InvalidInterfaceException
735
-     * @throws ReflectionException
736
-     */
737
-    protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = null)
738
-    {
739
-        $pre_tax_line_item = EE_Line_Item::new_instance(array(
740
-            'LIN_code' => 'pre-tax-subtotal',
741
-            'LIN_name' => esc_html__('Pre-Tax Subtotal', 'event_espresso'),
742
-            'LIN_type' => EEM_Line_Item::type_sub_total,
743
-        ));
744
-        $pre_tax_line_item = apply_filters(
745
-            'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
746
-            $pre_tax_line_item
747
-        );
748
-        self::set_TXN_ID($pre_tax_line_item, $transaction);
749
-        $total_line_item->add_child_line_item($pre_tax_line_item);
750
-        self::create_event_subtotal($pre_tax_line_item, $transaction);
751
-        return $pre_tax_line_item;
752
-    }
753
-
754
-
755
-    /**
756
-     * Creates a line item for the taxes subtotal and finds all the tax prices
757
-     * and applies taxes to it
758
-     *
759
-     * @param EE_Line_Item   $total_line_item of type EEM_Line_Item::type_total
760
-     * @param EE_Transaction $transaction
761
-     * @return EE_Line_Item
762
-     * @throws EE_Error
763
-     * @throws InvalidArgumentException
764
-     * @throws InvalidDataTypeException
765
-     * @throws InvalidInterfaceException
766
-     * @throws ReflectionException
767
-     */
768
-    protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
769
-    {
770
-        $tax_line_item = EE_Line_Item::new_instance(array(
771
-            'LIN_code'  => 'taxes',
772
-            'LIN_name'  => esc_html__('Taxes', 'event_espresso'),
773
-            'LIN_type'  => EEM_Line_Item::type_tax_sub_total,
774
-            'LIN_order' => 1000,// this should always come last
775
-        ));
776
-        $tax_line_item = apply_filters(
777
-            'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
778
-            $tax_line_item
779
-        );
780
-        self::set_TXN_ID($tax_line_item, $transaction);
781
-        $total_line_item->add_child_line_item($tax_line_item);
782
-        // and lastly, add the actual taxes
783
-        self::apply_taxes($total_line_item);
784
-        return $tax_line_item;
785
-    }
786
-
787
-
788
-    /**
789
-     * Creates a default items subtotal line item
790
-     *
791
-     * @param EE_Line_Item   $pre_tax_line_item
792
-     * @param EE_Transaction $transaction
793
-     * @param EE_Event       $event
794
-     * @return EE_Line_Item
795
-     * @throws EE_Error
796
-     * @throws InvalidArgumentException
797
-     * @throws InvalidDataTypeException
798
-     * @throws InvalidInterfaceException
799
-     * @throws ReflectionException
800
-     */
801
-    public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = null, $event = null)
802
-    {
803
-        $event_line_item = EE_Line_Item::new_instance(array(
804
-            'LIN_code' => self::get_event_code($event),
805
-            'LIN_name' => self::get_event_name($event),
806
-            'LIN_desc' => self::get_event_desc($event),
807
-            'LIN_type' => EEM_Line_Item::type_sub_total,
808
-            'OBJ_type' => EEM_Line_Item::OBJ_TYPE_EVENT,
809
-            'OBJ_ID'   => $event instanceof EE_Event ? $event->ID() : 0,
810
-        ));
811
-        $event_line_item = apply_filters(
812
-            'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
813
-            $event_line_item
814
-        );
815
-        self::set_TXN_ID($event_line_item, $transaction);
816
-        $pre_tax_line_item->add_child_line_item($event_line_item);
817
-        return $event_line_item;
818
-    }
819
-
820
-
821
-    /**
822
-     * Gets what the event ticket's code SHOULD be
823
-     *
824
-     * @param EE_Event $event
825
-     * @return string
826
-     * @throws EE_Error
827
-     */
828
-    public static function get_event_code($event)
829
-    {
830
-        return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
831
-    }
832
-
833
-
834
-    /**
835
-     * Gets the event name
836
-     *
837
-     * @param EE_Event $event
838
-     * @return string
839
-     * @throws EE_Error
840
-     */
841
-    public static function get_event_name($event)
842
-    {
843
-        return $event instanceof EE_Event
844
-            ? mb_substr($event->name(), 0, 245)
845
-            : esc_html__('Event', 'event_espresso');
846
-    }
847
-
848
-
849
-    /**
850
-     * Gets the event excerpt
851
-     *
852
-     * @param EE_Event $event
853
-     * @return string
854
-     * @throws EE_Error
855
-     */
856
-    public static function get_event_desc($event)
857
-    {
858
-        return $event instanceof EE_Event ? $event->short_description() : '';
859
-    }
860
-
861
-
862
-    /**
863
-     * Given the grand total line item and a ticket, finds the event sub-total
864
-     * line item the ticket's purchase should be added onto
865
-     *
866
-     * @access public
867
-     * @param EE_Line_Item $grand_total the grand total line item
868
-     * @param EE_Ticket    $ticket
869
-     * @return EE_Line_Item
870
-     * @throws EE_Error
871
-     * @throws InvalidArgumentException
872
-     * @throws InvalidDataTypeException
873
-     * @throws InvalidInterfaceException
874
-     * @throws ReflectionException
875
-     */
876
-    public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
877
-    {
878
-        $first_datetime = $ticket->first_datetime();
879
-        if (! $first_datetime instanceof EE_Datetime) {
880
-            throw new EE_Error(
881
-                sprintf(
882
-                    esc_html__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'),
883
-                    $ticket->ID()
884
-                )
885
-            );
886
-        }
887
-        $event = $first_datetime->event();
888
-        if (! $event instanceof EE_Event) {
889
-            throw new EE_Error(
890
-                sprintf(
891
-                    esc_html__(
892
-                        'The supplied ticket (ID %d) has no event data associated with it.',
893
-                        'event_espresso'
894
-                    ),
895
-                    $ticket->ID()
896
-                )
897
-            );
898
-        }
899
-        $events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
900
-        if (! $events_sub_total instanceof EE_Line_Item) {
901
-            throw new EE_Error(
902
-                sprintf(
903
-                    esc_html__(
904
-                        'There is no events sub-total for ticket %s on total line item %d',
905
-                        'event_espresso'
906
-                    ),
907
-                    $ticket->ID(),
908
-                    $grand_total->ID()
909
-                )
910
-            );
911
-        }
912
-        return $events_sub_total;
913
-    }
914
-
915
-
916
-    /**
917
-     * Gets the event line item
918
-     *
919
-     * @param EE_Line_Item $grand_total
920
-     * @param EE_Event     $event
921
-     * @return EE_Line_Item for the event subtotal which is a child of $grand_total
922
-     * @throws EE_Error
923
-     * @throws InvalidArgumentException
924
-     * @throws InvalidDataTypeException
925
-     * @throws InvalidInterfaceException
926
-     * @throws ReflectionException
927
-     */
928
-    public static function get_event_line_item(EE_Line_Item $grand_total, $event)
929
-    {
930
-        /** @type EE_Event $event */
931
-        $event = EEM_Event::instance()->ensure_is_obj($event, true);
932
-        $event_line_item = null;
933
-        $found = false;
934
-        foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
935
-            // default event subtotal, we should only ever find this the first time this method is called
936
-            if (! $event_line_item->OBJ_ID()) {
937
-                // let's use this! but first... set the event details
938
-                EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
939
-                $found = true;
940
-                break;
941
-            }
942
-            if ($event_line_item->OBJ_ID() === $event->ID()) {
943
-                // found existing line item for this event in the cart, so break out of loop and use this one
944
-                $found = true;
945
-                break;
946
-            }
947
-        }
948
-        if (! $found) {
949
-            // there is no event sub-total yet, so add it
950
-            $pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
951
-            // create a new "event" subtotal below that
952
-            $event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
953
-            // and set the event details
954
-            EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
955
-        }
956
-        return $event_line_item;
957
-    }
958
-
959
-
960
-    /**
961
-     * Creates a default items subtotal line item
962
-     *
963
-     * @param EE_Line_Item   $event_line_item
964
-     * @param EE_Event       $event
965
-     * @param EE_Transaction $transaction
966
-     * @return void
967
-     * @throws EE_Error
968
-     * @throws InvalidArgumentException
969
-     * @throws InvalidDataTypeException
970
-     * @throws InvalidInterfaceException
971
-     * @throws ReflectionException
972
-     */
973
-    public static function set_event_subtotal_details(
974
-        EE_Line_Item $event_line_item,
975
-        EE_Event $event,
976
-        $transaction = null
977
-    ) {
978
-        if ($event instanceof EE_Event) {
979
-            $event_line_item->set_code(self::get_event_code($event));
980
-            $event_line_item->set_name(self::get_event_name($event));
981
-            $event_line_item->set_desc(self::get_event_desc($event));
982
-            $event_line_item->set_OBJ_ID($event->ID());
983
-        }
984
-        self::set_TXN_ID($event_line_item, $transaction);
985
-    }
986
-
987
-
988
-    /**
989
-     * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
990
-     * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
991
-     * any old taxes are removed
992
-     *
993
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
994
-     * @param bool         $update_txn_status
995
-     * @return bool
996
-     * @throws EE_Error
997
-     * @throws InvalidArgumentException
998
-     * @throws InvalidDataTypeException
999
-     * @throws InvalidInterfaceException
1000
-     * @throws ReflectionException
1001
-     * @throws RuntimeException
1002
-     */
1003
-    public static function apply_taxes(EE_Line_Item $total_line_item, $update_txn_status = false)
1004
-    {
1005
-        $total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($total_line_item);
1006
-        $taxes_line_item = self::get_taxes_subtotal($total_line_item);
1007
-        $existing_global_taxes = $taxes_line_item->tax_descendants();
1008
-        $updates = false;
1009
-        // loop thru taxes
1010
-        $global_taxes = EEH_Line_Item::getGlobalTaxes();
1011
-        foreach ($global_taxes as $order => $taxes) {
1012
-            foreach ($taxes as $tax) {
1013
-                if ($tax instanceof EE_Price) {
1014
-                    $found = false;
1015
-                    // check if this is already an existing tax
1016
-                    foreach ($existing_global_taxes as $existing_global_tax) {
1017
-                        if ($tax->ID() === $existing_global_tax->OBJ_ID()) {
1018
-                            // maybe update the tax rate in case it has changed
1019
-                            if ($existing_global_tax->percent() !== $tax->amount()) {
1020
-                                $existing_global_tax->set_percent($tax->amount());
1021
-                                $existing_global_tax->save();
1022
-                                $updates = true;
1023
-                            }
1024
-                            $found = true;
1025
-                            break;
1026
-                        }
1027
-                    }
1028
-                    if (! $found) {
1029
-                        // add a new line item for this global tax
1030
-                        $tax_line_item = apply_filters(
1031
-                            'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
1032
-                            EE_Line_Item::new_instance(
1033
-                                [
1034
-                                    'LIN_name'       => $tax->name(),
1035
-                                    'LIN_desc'       => $tax->desc(),
1036
-                                    'LIN_percent'    => $tax->amount(),
1037
-                                    'LIN_is_taxable' => false,
1038
-                                    'LIN_order'      => $order,
1039
-                                    'LIN_total'      => 0,
1040
-                                    'LIN_type'       => EEM_Line_Item::type_tax,
1041
-                                    'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
1042
-                                    'OBJ_ID'         => $tax->ID(),
1043
-                                ]
1044
-                            )
1045
-                        );
1046
-                        $updates = $taxes_line_item->add_child_line_item($tax_line_item) ? true : $updates;
1047
-                    }
1048
-                }
1049
-            }
1050
-        }
1051
-        // only recalculate totals if something changed
1052
-        if ($updates) {
1053
-            $total_line_item->recalculate_total_including_taxes($update_txn_status);
1054
-            return true;
1055
-        }
1056
-        return false;
1057
-    }
1058
-
1059
-
1060
-    /**
1061
-     * Ensures that taxes have been applied to the order, if not applies them.
1062
-     * Returns the total amount of tax
1063
-     *
1064
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
1065
-     * @return float
1066
-     * @throws EE_Error
1067
-     * @throws InvalidArgumentException
1068
-     * @throws InvalidDataTypeException
1069
-     * @throws InvalidInterfaceException
1070
-     * @throws ReflectionException
1071
-     */
1072
-    public static function ensure_taxes_applied($total_line_item)
1073
-    {
1074
-        $taxes_subtotal = self::get_taxes_subtotal($total_line_item);
1075
-        if (! $taxes_subtotal->children()) {
1076
-            self::apply_taxes($total_line_item);
1077
-        }
1078
-        return $taxes_subtotal->total();
1079
-    }
1080
-
1081
-
1082
-    /**
1083
-     * Deletes ALL children of the passed line item
1084
-     *
1085
-     * @param EE_Line_Item $parent_line_item
1086
-     * @return bool
1087
-     * @throws EE_Error
1088
-     * @throws InvalidArgumentException
1089
-     * @throws InvalidDataTypeException
1090
-     * @throws InvalidInterfaceException
1091
-     * @throws ReflectionException
1092
-     */
1093
-    public static function delete_all_child_items(EE_Line_Item $parent_line_item)
1094
-    {
1095
-        $deleted = 0;
1096
-        foreach ($parent_line_item->children() as $child_line_item) {
1097
-            if ($child_line_item instanceof EE_Line_Item) {
1098
-                $deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
1099
-                if ($child_line_item->ID()) {
1100
-                    $child_line_item->delete();
1101
-                    unset($child_line_item);
1102
-                } else {
1103
-                    $parent_line_item->delete_child_line_item($child_line_item->code());
1104
-                }
1105
-                $deleted++;
1106
-            }
1107
-        }
1108
-        return $deleted;
1109
-    }
1110
-
1111
-
1112
-    /**
1113
-     * Deletes the line items as indicated by the line item code(s) provided,
1114
-     * regardless of where they're found in the line item tree. Automatically
1115
-     * re-calculates the line item totals and updates the related transaction. But
1116
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
1117
-     * should probably change because of this).
1118
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
1119
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
1120
-     *
1121
-     * @param EE_Line_Item      $total_line_item of type EEM_Line_Item::type_total
1122
-     * @param array|bool|string $line_item_codes
1123
-     * @return int number of items successfully removed
1124
-     * @throws EE_Error
1125
-     */
1126
-    public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = false)
1127
-    {
1128
-
1129
-        if ($total_line_item->type() !== EEM_Line_Item::type_total) {
1130
-            EE_Error::doing_it_wrong(
1131
-                'EEH_Line_Item::delete_items',
1132
-                esc_html__(
1133
-                    'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
1134
-                    'event_espresso'
1135
-                ),
1136
-                '4.6.18'
1137
-            );
1138
-        }
1139
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1140
-
1141
-        // check if only a single line_item_id was passed
1142
-        if (! empty($line_item_codes) && ! is_array($line_item_codes)) {
1143
-            // place single line_item_id in an array to appear as multiple line_item_ids
1144
-            $line_item_codes = array($line_item_codes);
1145
-        }
1146
-        $removals = 0;
1147
-        // cycle thru line_item_ids
1148
-        foreach ($line_item_codes as $line_item_id) {
1149
-            $removals += $total_line_item->delete_child_line_item($line_item_id);
1150
-        }
1151
-
1152
-        if ($removals > 0) {
1153
-            $total_line_item->recalculate_taxes_and_tax_total();
1154
-            return $removals;
1155
-        } else {
1156
-            return false;
1157
-        }
1158
-    }
1159
-
1160
-
1161
-    /**
1162
-     * Overwrites the previous tax by clearing out the old taxes, and creates a new
1163
-     * tax and updates the total line item accordingly
1164
-     *
1165
-     * @param EE_Line_Item $total_line_item
1166
-     * @param float        $amount
1167
-     * @param string       $name
1168
-     * @param string       $description
1169
-     * @param string       $code
1170
-     * @param boolean      $add_to_existing_line_item
1171
-     *                          if true, and a duplicate line item with the same code is found,
1172
-     *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
1173
-     * @return EE_Line_Item the new tax line item created
1174
-     * @throws EE_Error
1175
-     * @throws InvalidArgumentException
1176
-     * @throws InvalidDataTypeException
1177
-     * @throws InvalidInterfaceException
1178
-     * @throws ReflectionException
1179
-     */
1180
-    public static function set_total_tax_to(
1181
-        EE_Line_Item $total_line_item,
1182
-        $amount,
1183
-        $name = null,
1184
-        $description = null,
1185
-        $code = null,
1186
-        $add_to_existing_line_item = false
1187
-    ) {
1188
-        $tax_subtotal = self::get_taxes_subtotal($total_line_item);
1189
-        $taxable_total = $total_line_item->taxable_total();
1190
-
1191
-        if ($add_to_existing_line_item) {
1192
-            $new_tax = $tax_subtotal->get_child_line_item($code);
1193
-            EEM_Line_Item::instance()->delete(
1194
-                array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
1195
-            );
1196
-        } else {
1197
-            $new_tax = null;
1198
-            $tax_subtotal->delete_children_line_items();
1199
-        }
1200
-        if ($new_tax) {
1201
-            $new_tax->set_total($new_tax->total() + $amount);
1202
-            $new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
1203
-        } else {
1204
-            // no existing tax item. Create it
1205
-            $new_tax = EE_Line_Item::new_instance(array(
1206
-                'TXN_ID'      => $total_line_item->TXN_ID(),
1207
-                'LIN_name'    => $name ?: esc_html__('Tax', 'event_espresso'),
1208
-                'LIN_desc'    => $description ?: '',
1209
-                'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
1210
-                'LIN_total'   => $amount,
1211
-                'LIN_parent'  => $tax_subtotal->ID(),
1212
-                'LIN_type'    => EEM_Line_Item::type_tax,
1213
-                'LIN_code'    => $code,
1214
-            ));
1215
-        }
1216
-
1217
-        $new_tax = apply_filters(
1218
-            'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
1219
-            $new_tax,
1220
-            $total_line_item
1221
-        );
1222
-        $new_tax->save();
1223
-        $tax_subtotal->set_total($new_tax->total());
1224
-        $tax_subtotal->save();
1225
-        $total_line_item->recalculate_total_including_taxes();
1226
-        return $new_tax;
1227
-    }
1228
-
1229
-
1230
-    /**
1231
-     * Makes all the line items which are children of $line_item taxable (or not).
1232
-     * Does NOT save the line items
1233
-     *
1234
-     * @param EE_Line_Item $line_item
1235
-     * @param boolean      $taxable
1236
-     * @param string       $code_substring_for_whitelist if this string is part of the line item's code
1237
-     *                                                   it will be whitelisted (ie, except from becoming taxable)
1238
-     * @throws EE_Error
1239
-     */
1240
-    public static function set_line_items_taxable(
1241
-        EE_Line_Item $line_item,
1242
-        $taxable = true,
1243
-        $code_substring_for_whitelist = null
1244
-    ) {
1245
-        $whitelisted = false;
1246
-        if ($code_substring_for_whitelist !== null) {
1247
-            $whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false;
1248
-        }
1249
-        if (! $whitelisted && $line_item->is_line_item()) {
1250
-            $line_item->set_is_taxable($taxable);
1251
-        }
1252
-        foreach ($line_item->children() as $child_line_item) {
1253
-            EEH_Line_Item::set_line_items_taxable(
1254
-                $child_line_item,
1255
-                $taxable,
1256
-                $code_substring_for_whitelist
1257
-            );
1258
-        }
1259
-    }
1260
-
1261
-
1262
-    /**
1263
-     * Gets all descendants that are event subtotals
1264
-     *
1265
-     * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1266
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1267
-     * @return EE_Line_Item[]
1268
-     * @throws EE_Error
1269
-     */
1270
-    public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1271
-    {
1272
-        return self::get_subtotals_of_object_type($parent_line_item, EEM_Line_Item::OBJ_TYPE_EVENT);
1273
-    }
1274
-
1275
-
1276
-    /**
1277
-     * Gets all descendants subtotals that match the supplied object type
1278
-     *
1279
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1280
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1281
-     * @param string       $obj_type
1282
-     * @return EE_Line_Item[]
1283
-     * @throws EE_Error
1284
-     */
1285
-    public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1286
-    {
1287
-        return self::_get_descendants_by_type_and_object_type(
1288
-            $parent_line_item,
1289
-            EEM_Line_Item::type_sub_total,
1290
-            $obj_type
1291
-        );
1292
-    }
1293
-
1294
-
1295
-    /**
1296
-     * Gets all descendants that are tickets
1297
-     *
1298
-     * @uses  EEH_Line_Item::get_line_items_of_object_type()
1299
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1300
-     * @return EE_Line_Item[]
1301
-     * @throws EE_Error
1302
-     */
1303
-    public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1304
-    {
1305
-        return self::get_line_items_of_object_type(
1306
-            $parent_line_item,
1307
-            EEM_Line_Item::OBJ_TYPE_TICKET
1308
-        );
1309
-    }
1310
-
1311
-
1312
-    /**
1313
-     * Gets all descendants subtotals that match the supplied object type
1314
-     *
1315
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1316
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1317
-     * @param string       $obj_type
1318
-     * @return EE_Line_Item[]
1319
-     * @throws EE_Error
1320
-     */
1321
-    public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1322
-    {
1323
-        return self::_get_descendants_by_type_and_object_type(
1324
-            $parent_line_item,
1325
-            EEM_Line_Item::type_line_item,
1326
-            $obj_type
1327
-        );
1328
-    }
1329
-
1330
-
1331
-    /**
1332
-     * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1333
-     *
1334
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1335
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1336
-     * @return EE_Line_Item[]
1337
-     * @throws EE_Error
1338
-     */
1339
-    public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1340
-    {
1341
-        return EEH_Line_Item::get_descendants_of_type(
1342
-            $parent_line_item,
1343
-            EEM_Line_Item::type_tax
1344
-        );
1345
-    }
1346
-
1347
-
1348
-    /**
1349
-     * Gets all the real items purchased which are children of this item
1350
-     *
1351
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1352
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1353
-     * @return EE_Line_Item[]
1354
-     * @throws EE_Error
1355
-     */
1356
-    public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1357
-    {
1358
-        return EEH_Line_Item::get_descendants_of_type(
1359
-            $parent_line_item,
1360
-            EEM_Line_Item::type_line_item
1361
-        );
1362
-    }
1363
-
1364
-
1365
-    /**
1366
-     * Gets all descendants of supplied line item that match the supplied line item type
1367
-     *
1368
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1369
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1370
-     * @param string       $line_item_type   one of the EEM_Line_Item constants
1371
-     * @return EE_Line_Item[]
1372
-     * @throws EE_Error
1373
-     */
1374
-    public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1375
-    {
1376
-        return self::_get_descendants_by_type_and_object_type(
1377
-            $parent_line_item,
1378
-            $line_item_type,
1379
-            null
1380
-        );
1381
-    }
1382
-
1383
-
1384
-    /**
1385
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1386
-     * as well
1387
-     *
1388
-     * @param EE_Line_Item  $parent_line_item - the line item to find descendants of
1389
-     * @param string        $line_item_type   one of the EEM_Line_Item constants
1390
-     * @param string | NULL $obj_type         object model class name (minus prefix) or NULL to ignore object type when
1391
-     *                                        searching
1392
-     * @return EE_Line_Item[]
1393
-     * @throws EE_Error
1394
-     */
1395
-    protected static function _get_descendants_by_type_and_object_type(
1396
-        EE_Line_Item $parent_line_item,
1397
-        $line_item_type,
1398
-        $obj_type = null
1399
-    ) {
1400
-        $objects = array();
1401
-        foreach ($parent_line_item->children() as $child_line_item) {
1402
-            if ($child_line_item instanceof EE_Line_Item) {
1403
-                if (
1404
-                    $child_line_item->type() === $line_item_type
1405
-                    && (
1406
-                        $child_line_item->OBJ_type() === $obj_type || $obj_type === null
1407
-                    )
1408
-                ) {
1409
-                    $objects[] = $child_line_item;
1410
-                } else {
1411
-                    // go-through-all-its children looking for more matches
1412
-                    $objects = array_merge(
1413
-                        $objects,
1414
-                        self::_get_descendants_by_type_and_object_type(
1415
-                            $child_line_item,
1416
-                            $line_item_type,
1417
-                            $obj_type
1418
-                        )
1419
-                    );
1420
-                }
1421
-            }
1422
-        }
1423
-        return $objects;
1424
-    }
1425
-
1426
-
1427
-    /**
1428
-     * Gets all descendants subtotals that match the supplied object type
1429
-     *
1430
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1431
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1432
-     * @param string       $OBJ_type         object type (like Event)
1433
-     * @param array        $OBJ_IDs          array of OBJ_IDs
1434
-     * @return EE_Line_Item[]
1435
-     * @throws EE_Error
1436
-     */
1437
-    public static function get_line_items_by_object_type_and_IDs(
1438
-        EE_Line_Item $parent_line_item,
1439
-        $OBJ_type = '',
1440
-        $OBJ_IDs = array()
1441
-    ) {
1442
-        return self::_get_descendants_by_object_type_and_object_ID(
1443
-            $parent_line_item,
1444
-            $OBJ_type,
1445
-            $OBJ_IDs
1446
-        );
1447
-    }
1448
-
1449
-
1450
-    /**
1451
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1452
-     * as well
1453
-     *
1454
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1455
-     * @param string       $OBJ_type         object type (like Event)
1456
-     * @param array        $OBJ_IDs          array of OBJ_IDs
1457
-     * @return EE_Line_Item[]
1458
-     * @throws EE_Error
1459
-     */
1460
-    protected static function _get_descendants_by_object_type_and_object_ID(
1461
-        EE_Line_Item $parent_line_item,
1462
-        $OBJ_type,
1463
-        $OBJ_IDs
1464
-    ) {
1465
-        $objects = array();
1466
-        foreach ($parent_line_item->children() as $child_line_item) {
1467
-            if ($child_line_item instanceof EE_Line_Item) {
1468
-                if (
1469
-                    $child_line_item->OBJ_type() === $OBJ_type
1470
-                    && is_array($OBJ_IDs)
1471
-                    && in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1472
-                ) {
1473
-                    $objects[] = $child_line_item;
1474
-                } else {
1475
-                    // go-through-all-its children looking for more matches
1476
-                    $objects = array_merge(
1477
-                        $objects,
1478
-                        self::_get_descendants_by_object_type_and_object_ID(
1479
-                            $child_line_item,
1480
-                            $OBJ_type,
1481
-                            $OBJ_IDs
1482
-                        )
1483
-                    );
1484
-                }
1485
-            }
1486
-        }
1487
-        return $objects;
1488
-    }
1489
-
1490
-
1491
-    /**
1492
-     * Uses a breadth-first-search in order to find the nearest descendant of
1493
-     * the specified type and returns it, else NULL
1494
-     *
1495
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1496
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1497
-     * @param string       $type             like one of the EEM_Line_Item::type_*
1498
-     * @return EE_Line_Item
1499
-     * @throws EE_Error
1500
-     * @throws InvalidArgumentException
1501
-     * @throws InvalidDataTypeException
1502
-     * @throws InvalidInterfaceException
1503
-     * @throws ReflectionException
1504
-     */
1505
-    public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1506
-    {
1507
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1508
-    }
1509
-
1510
-
1511
-    /**
1512
-     * Uses a breadth-first-search in order to find the nearest descendant
1513
-     * having the specified LIN_code and returns it, else NULL
1514
-     *
1515
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1516
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1517
-     * @param string       $code             any value used for LIN_code
1518
-     * @return EE_Line_Item
1519
-     * @throws EE_Error
1520
-     * @throws InvalidArgumentException
1521
-     * @throws InvalidDataTypeException
1522
-     * @throws InvalidInterfaceException
1523
-     * @throws ReflectionException
1524
-     */
1525
-    public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1526
-    {
1527
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1528
-    }
1529
-
1530
-
1531
-    /**
1532
-     * Uses a breadth-first-search in order to find the nearest descendant
1533
-     * having the specified LIN_code and returns it, else NULL
1534
-     *
1535
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1536
-     * @param string       $search_field     name of EE_Line_Item property
1537
-     * @param string       $value            any value stored in $search_field
1538
-     * @return EE_Line_Item
1539
-     * @throws EE_Error
1540
-     * @throws InvalidArgumentException
1541
-     * @throws InvalidDataTypeException
1542
-     * @throws InvalidInterfaceException
1543
-     * @throws ReflectionException
1544
-     */
1545
-    protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1546
-    {
1547
-        foreach ($parent_line_item->children() as $child) {
1548
-            if ($child->get($search_field) == $value) {
1549
-                return $child;
1550
-            }
1551
-        }
1552
-        foreach ($parent_line_item->children() as $child) {
1553
-            $descendant_found = self::_get_nearest_descendant(
1554
-                $child,
1555
-                $search_field,
1556
-                $value
1557
-            );
1558
-            if ($descendant_found) {
1559
-                return $descendant_found;
1560
-            }
1561
-        }
1562
-        return null;
1563
-    }
1564
-
1565
-
1566
-    /**
1567
-     * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1568
-     * else recursively walks up the line item tree until a parent of type total is found,
1569
-     *
1570
-     * @param EE_Line_Item $line_item
1571
-     * @return EE_Line_Item
1572
-     * @throws EE_Error
1573
-     * @throws ReflectionException
1574
-     */
1575
-    public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item): EE_Line_Item
1576
-    {
1577
-        if ($line_item->is_total()) {
1578
-            return $line_item;
1579
-        }
1580
-        if ($line_item->TXN_ID()) {
1581
-            $total_line_item = $line_item->transaction()->total_line_item(false);
1582
-            if ($total_line_item instanceof EE_Line_Item) {
1583
-                return $total_line_item;
1584
-            }
1585
-        } else {
1586
-            $line_item_parent = $line_item->parent();
1587
-            if ($line_item_parent instanceof EE_Line_Item) {
1588
-                if ($line_item_parent->is_total()) {
1589
-                    return $line_item_parent;
1590
-                }
1591
-                return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1592
-            }
1593
-        }
1594
-        throw new EE_Error(
1595
-            sprintf(
1596
-                esc_html__(
1597
-                    'A valid grand total for line item %1$d was not found.',
1598
-                    'event_espresso'
1599
-                ),
1600
-                $line_item->ID()
1601
-            )
1602
-        );
1603
-    }
1604
-
1605
-
1606
-    /**
1607
-     * Prints out a representation of the line item tree
1608
-     *
1609
-     * @param EE_Line_Item $line_item
1610
-     * @param int          $indentation
1611
-     * @return void
1612
-     * @throws EE_Error
1613
-     */
1614
-    public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1615
-    {
1616
-        $new_line = defined('EE_TESTS_DIR') ? "\n" : '<br />';
1617
-        echo $new_line;
1618
-        if (! $indentation) {
1619
-            echo $new_line;
1620
-        }
1621
-        echo str_repeat('. ', $indentation);
1622
-        $breakdown = '';
1623
-        if ($line_item->is_line_item() || $line_item->is_sub_line_item() || $line_item->isSubTax()) {
1624
-            if ($line_item->is_percent()) {
1625
-                $breakdown = "{$line_item->percent()}%";
1626
-            } else {
1627
-                $breakdown = "\${$line_item->unit_price()} x {$line_item->quantity()}";
1628
-            }
1629
-        }
1630
-        echo wp_kses($line_item->name(), AllowedTags::getAllowedTags());
1631
-        echo " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : ";
1632
-        echo "\${$line_item->total()}";
1633
-        if ($breakdown) {
1634
-            echo " ( {$breakdown} )";
1635
-        }
1636
-        if ($line_item->is_taxable()) {
1637
-            echo '  * taxable';
1638
-        }
1639
-        if ($line_item->children()) {
1640
-            foreach ($line_item->children() as $child) {
1641
-                self::visualize($child, $indentation + 1);
1642
-            }
1643
-        }
1644
-        if (! $indentation) {
1645
-            echo $new_line . $new_line;
1646
-        }
1647
-    }
1648
-
1649
-
1650
-    /**
1651
-     * Calculates the registration's final price, taking into account that they
1652
-     * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1653
-     * and receive a portion of any transaction-wide discounts.
1654
-     * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1655
-     * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1656
-     * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1657
-     * and brent's final price should be $5.50.
1658
-     * In order to do this, we basically need to traverse the line item tree calculating
1659
-     * the running totals (just as if we were recalculating the total), but when we identify
1660
-     * regular line items, we need to keep track of their share of the grand total.
1661
-     * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1662
-     * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1663
-     * when there are non-taxable items; otherwise they would be the same)
1664
-     *
1665
-     * @param EE_Line_Item $line_item
1666
-     * @param array        $billable_ticket_quantities  array of EE_Ticket IDs and their corresponding quantity that
1667
-     *                                                  can be included in price calculations at this moment
1668
-     * @return array        keys are line items for tickets IDs and values are their share of the running total,
1669
-     *                                                  plus the key 'total', and 'taxable' which also has keys of all
1670
-     *                                                  the ticket IDs.
1671
-     *                                                  Eg array(
1672
-     *                                                      12 => 4.3
1673
-     *                                                      23 => 8.0
1674
-     *                                                      'total' => 16.6,
1675
-     *                                                      'taxable' => array(
1676
-     *                                                          12 => 10,
1677
-     *                                                          23 => 4
1678
-     *                                                      ).
1679
-     *                                                  So to find which registrations have which final price, we need
1680
-     *                                                  to find which line item is theirs, which can be done with
1681
-     *                                                  `EEM_Line_Item::instance()->get_line_item_for_registration(
1682
-     *                                                  $registration );`
1683
-     * @throws EE_Error
1684
-     * @throws InvalidArgumentException
1685
-     * @throws InvalidDataTypeException
1686
-     * @throws InvalidInterfaceException
1687
-     * @throws ReflectionException
1688
-     */
1689
-    public static function calculate_reg_final_prices_per_line_item(
1690
-        EE_Line_Item $line_item,
1691
-        $billable_ticket_quantities = array()
1692
-    ) {
1693
-        $running_totals = [
1694
-            'total'   => 0,
1695
-            'taxable' => ['total' => 0]
1696
-        ];
1697
-        foreach ($line_item->children() as $child_line_item) {
1698
-            switch ($child_line_item->type()) {
1699
-                case EEM_Line_Item::type_sub_total:
1700
-                    $running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1701
-                        $child_line_item,
1702
-                        $billable_ticket_quantities
1703
-                    );
1704
-                    // combine arrays but preserve numeric keys
1705
-                    $running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1706
-                    $running_totals['total'] += $running_totals_from_subtotal['total'];
1707
-                    $running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1708
-                    break;
1709
-
1710
-                case EEM_Line_Item::type_tax_sub_total:
1711
-                    // find how much the taxes percentage is
1712
-                    if ($child_line_item->percent() !== 0) {
1713
-                        $tax_percent_decimal = $child_line_item->percent() / 100;
1714
-                    } else {
1715
-                        $tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1716
-                    }
1717
-                    // and apply to all the taxable totals, and add to the pretax totals
1718
-                    foreach ($running_totals as $line_item_id => $this_running_total) {
1719
-                        // "total" and "taxable" array key is an exception
1720
-                        if ($line_item_id === 'taxable') {
1721
-                            continue;
1722
-                        }
1723
-                        $taxable_total = $running_totals['taxable'][ $line_item_id ];
1724
-                        $running_totals[ $line_item_id ] += ($taxable_total * $tax_percent_decimal);
1725
-                    }
1726
-                    break;
1727
-
1728
-                case EEM_Line_Item::type_line_item:
1729
-                    // ticket line items or ????
1730
-                    if ($child_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
1731
-                        // kk it's a ticket
1732
-                        if (isset($running_totals[ $child_line_item->ID() ])) {
1733
-                            // huh? that shouldn't happen.
1734
-                            $running_totals['total'] += $child_line_item->total();
1735
-                        } else {
1736
-                            // its not in our running totals yet. great.
1737
-                            if ($child_line_item->is_taxable()) {
1738
-                                $taxable_amount = $child_line_item->unit_price();
1739
-                            } else {
1740
-                                $taxable_amount = 0;
1741
-                            }
1742
-                            // are we only calculating totals for some tickets?
1743
-                            if (isset($billable_ticket_quantities[ $child_line_item->OBJ_ID() ])) {
1744
-                                $quantity = $billable_ticket_quantities[ $child_line_item->OBJ_ID() ];
1745
-                                $running_totals[ $child_line_item->ID() ] = $quantity
1746
-                                    ? $child_line_item->unit_price()
1747
-                                    : 0;
1748
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $quantity
1749
-                                    ? $taxable_amount
1750
-                                    : 0;
1751
-                            } else {
1752
-                                $quantity = $child_line_item->quantity();
1753
-                                $running_totals[ $child_line_item->ID() ] = $child_line_item->unit_price();
1754
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $taxable_amount;
1755
-                            }
1756
-                            $running_totals['taxable']['total'] += $taxable_amount * $quantity;
1757
-                            $running_totals['total'] += $child_line_item->unit_price() * $quantity;
1758
-                        }
1759
-                    } else {
1760
-                        // it's some other type of item added to the cart
1761
-                        // it should affect the running totals
1762
-                        // basically we want to convert it into a PERCENT modifier. Because
1763
-                        // more clearly affect all registration's final price equally
1764
-                        $line_items_percent_of_running_total = $running_totals['total'] > 0
1765
-                            ? ($child_line_item->total() / $running_totals['total']) + 1
1766
-                            : 1;
1767
-                        foreach ($running_totals as $line_item_id => $this_running_total) {
1768
-                            // the "taxable" array key is an exception
1769
-                            if ($line_item_id === 'taxable') {
1770
-                                continue;
1771
-                            }
1772
-                            // update the running totals
1773
-                            // yes this actually even works for the running grand total!
1774
-                            $running_totals[ $line_item_id ] =
1775
-                                $line_items_percent_of_running_total * $this_running_total;
1776
-
1777
-                            if ($child_line_item->is_taxable()) {
1778
-                                $running_totals['taxable'][ $line_item_id ] =
1779
-                                    $line_items_percent_of_running_total * $running_totals['taxable'][ $line_item_id ];
1780
-                            }
1781
-                        }
1782
-                    }
1783
-                    break;
1784
-            }
1785
-        }
1786
-        return $running_totals;
1787
-    }
1788
-
1789
-
1790
-    /**
1791
-     * @param EE_Line_Item $total_line_item
1792
-     * @param EE_Line_Item $ticket_line_item
1793
-     * @return float | null
1794
-     * @throws EE_Error
1795
-     * @throws InvalidArgumentException
1796
-     * @throws InvalidDataTypeException
1797
-     * @throws InvalidInterfaceException
1798
-     * @throws OutOfRangeException
1799
-     * @throws ReflectionException
1800
-     */
1801
-    public static function calculate_final_price_for_ticket_line_item(
1802
-        EE_Line_Item $total_line_item,
1803
-        EE_Line_Item $ticket_line_item
1804
-    ) {
1805
-        static $final_prices_per_ticket_line_item = array();
1806
-        if (empty($final_prices_per_ticket_line_item) || empty($final_prices_per_ticket_line_item[ $total_line_item->ID() ])) {
1807
-            $final_prices_per_ticket_line_item[ $total_line_item->ID() ] = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1808
-                $total_line_item
1809
-            );
1810
-        }
1811
-        // ok now find this new registration's final price
1812
-        if (isset($final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ])) {
1813
-            return $final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ];
1814
-        }
1815
-        $message = sprintf(
1816
-            esc_html__(
1817
-                'The final price for the ticket line item (ID:%1$d) on the total line item (ID:%2$d) could not be calculated.',
1818
-                'event_espresso'
1819
-            ),
1820
-            $ticket_line_item->ID(),
1821
-            $total_line_item->ID()
1822
-        );
1823
-        if (WP_DEBUG) {
1824
-            $message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1825
-            throw new OutOfRangeException($message);
1826
-        }
1827
-        EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1828
-        return null;
1829
-    }
1830
-
1831
-
1832
-    /**
1833
-     * Creates a duplicate of the line item tree, except only includes billable items
1834
-     * and the portion of line items attributed to billable things
1835
-     *
1836
-     * @param EE_Line_Item      $line_item
1837
-     * @param EE_Registration[] $registrations
1838
-     * @return EE_Line_Item
1839
-     * @throws EE_Error
1840
-     * @throws InvalidArgumentException
1841
-     * @throws InvalidDataTypeException
1842
-     * @throws InvalidInterfaceException
1843
-     * @throws ReflectionException
1844
-     */
1845
-    public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1846
-    {
1847
-        $copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1848
-        foreach ($line_item->children() as $child_li) {
1849
-            $copy_li->add_child_line_item(
1850
-                EEH_Line_Item::billable_line_item_tree($child_li, $registrations)
1851
-            );
1852
-        }
1853
-        // if this is the grand total line item, make sure the totals all add up
1854
-        // (we could have duplicated this logic AS we copied the line items, but
1855
-        // it seems DRYer this way)
1856
-        if ($copy_li->type() === EEM_Line_Item::type_total) {
1857
-            $copy_li->recalculate_total_including_taxes();
1858
-        }
1859
-        return $copy_li;
1860
-    }
1861
-
1862
-
1863
-    /**
1864
-     * Creates a new, unsaved line item from $line_item that factors in the
1865
-     * number of billable registrations on $registrations.
1866
-     *
1867
-     * @param EE_Line_Item      $line_item
1868
-     * @param EE_Registration[] $registrations
1869
-     * @return EE_Line_Item
1870
-     * @throws EE_Error
1871
-     * @throws InvalidArgumentException
1872
-     * @throws InvalidDataTypeException
1873
-     * @throws InvalidInterfaceException
1874
-     * @throws ReflectionException
1875
-     */
1876
-    public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1877
-    {
1878
-        $new_li_fields = $line_item->model_field_array();
1879
-        if (
1880
-            $line_item->type() === EEM_Line_Item::type_line_item &&
1881
-            $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1882
-        ) {
1883
-            $count = 0;
1884
-            foreach ($registrations as $registration) {
1885
-                if (
1886
-                    $line_item->OBJ_ID() === $registration->ticket_ID() &&
1887
-                    in_array(
1888
-                        $registration->status_ID(),
1889
-                        EEM_Registration::reg_statuses_that_allow_payment(),
1890
-                        true
1891
-                    )
1892
-                ) {
1893
-                    $count++;
1894
-                }
1895
-            }
1896
-            $new_li_fields['LIN_quantity'] = $count;
1897
-        }
1898
-        // don't set the total. We'll leave that up to the code that calculates it
1899
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1900
-        return EE_Line_Item::new_instance($new_li_fields);
1901
-    }
1902
-
1903
-
1904
-    /**
1905
-     * Returns a modified line item tree where all the subtotals which have a total of 0
1906
-     * are removed, and line items with a quantity of 0
1907
-     *
1908
-     * @param EE_Line_Item $line_item |null
1909
-     * @return EE_Line_Item|null
1910
-     * @throws EE_Error
1911
-     * @throws InvalidArgumentException
1912
-     * @throws InvalidDataTypeException
1913
-     * @throws InvalidInterfaceException
1914
-     * @throws ReflectionException
1915
-     */
1916
-    public static function non_empty_line_items(EE_Line_Item $line_item)
1917
-    {
1918
-        $copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1919
-        if ($copied_li === null) {
1920
-            return null;
1921
-        }
1922
-        // if this is an event subtotal, we want to only include it if it
1923
-        // has a non-zero total and at least one ticket line item child
1924
-        $ticket_children = 0;
1925
-        foreach ($line_item->children() as $child_li) {
1926
-            $child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1927
-            if ($child_li_copy !== null) {
1928
-                $copied_li->add_child_line_item($child_li_copy);
1929
-                if (
1930
-                    $child_li_copy->type() === EEM_Line_Item::type_line_item &&
1931
-                    $child_li_copy->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1932
-                ) {
1933
-                    $ticket_children++;
1934
-                }
1935
-            }
1936
-        }
1937
-        // if this is an event subtotal with NO ticket children
1938
-        // we basically want to ignore it
1939
-        if (
1940
-            $ticket_children === 0
1941
-            && $line_item->type() === EEM_Line_Item::type_sub_total
1942
-            && $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
1943
-            && $line_item->total() === 0
1944
-        ) {
1945
-            return null;
1946
-        }
1947
-        return $copied_li;
1948
-    }
1949
-
1950
-
1951
-    /**
1952
-     * Creates a new, unsaved line item, but if it's a ticket line item
1953
-     * with a total of 0, or a subtotal of 0, returns null instead
1954
-     *
1955
-     * @param EE_Line_Item $line_item
1956
-     * @return EE_Line_Item
1957
-     * @throws EE_Error
1958
-     * @throws InvalidArgumentException
1959
-     * @throws InvalidDataTypeException
1960
-     * @throws InvalidInterfaceException
1961
-     * @throws ReflectionException
1962
-     */
1963
-    public static function non_empty_line_item(EE_Line_Item $line_item)
1964
-    {
1965
-        if (
1966
-            $line_item->type() === EEM_Line_Item::type_line_item
1967
-            && $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1968
-            && $line_item->quantity() === 0
1969
-        ) {
1970
-            return null;
1971
-        }
1972
-        $new_li_fields = $line_item->model_field_array();
1973
-        // don't set the total. We'll leave that up to the code that calculates it
1974
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1975
-        return EE_Line_Item::new_instance($new_li_fields);
1976
-    }
1977
-
1978
-
1979
-    /**
1980
-     * Cycles through all of the ticket line items for the supplied total line item
1981
-     * and ensures that the line item's "is_taxable" field matches that of its corresponding ticket
1982
-     *
1983
-     * @param EE_Line_Item $total_line_item
1984
-     * @since 4.9.79.p
1985
-     * @throws EE_Error
1986
-     * @throws InvalidArgumentException
1987
-     * @throws InvalidDataTypeException
1988
-     * @throws InvalidInterfaceException
1989
-     * @throws ReflectionException
1990
-     */
1991
-    public static function resetIsTaxableForTickets(EE_Line_Item $total_line_item)
1992
-    {
1993
-        $ticket_line_items = self::get_ticket_line_items($total_line_item);
1994
-        foreach ($ticket_line_items as $ticket_line_item) {
1995
-            if (
1996
-                $ticket_line_item instanceof EE_Line_Item
1997
-                && $ticket_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1998
-            ) {
1999
-                $ticket = $ticket_line_item->ticket();
2000
-                if ($ticket instanceof EE_Ticket && $ticket->taxable() !== $ticket_line_item->is_taxable()) {
2001
-                    $ticket_line_item->set_is_taxable($ticket->taxable());
2002
-                    $ticket_line_item->save();
2003
-                }
2004
-            }
2005
-        }
2006
-    }
2007
-
2008
-
2009
-    /**
2010
-     * @return EE_Line_Item[]
2011
-     * @throws EE_Error
2012
-     * @throws ReflectionException
2013
-     * @since   $VID:$
2014
-     */
2015
-    private static function getGlobalTaxes(): array
2016
-    {
2017
-        if (EEH_Line_Item::$global_taxes === null) {
2018
-
2019
-            /** @type EEM_Price $EEM_Price */
2020
-            $EEM_Price = EE_Registry::instance()->load_model('Price');
2021
-            // get array of taxes via Price Model
2022
-            EEH_Line_Item::$global_taxes = $EEM_Price->get_all_prices_that_are_taxes();
2023
-            ksort(EEH_Line_Item::$global_taxes);
2024
-        }
2025
-        return EEH_Line_Item::$global_taxes;
2026
-    }
2027
-
2028
-
2029
-
2030
-    /**************************************** @DEPRECATED METHODS *************************************** */
2031
-    /**
2032
-     * @deprecated
2033
-     * @param EE_Line_Item $total_line_item
2034
-     * @return EE_Line_Item
2035
-     * @throws EE_Error
2036
-     * @throws InvalidArgumentException
2037
-     * @throws InvalidDataTypeException
2038
-     * @throws InvalidInterfaceException
2039
-     * @throws ReflectionException
2040
-     */
2041
-    public static function get_items_subtotal(EE_Line_Item $total_line_item)
2042
-    {
2043
-        EE_Error::doing_it_wrong(
2044
-            'EEH_Line_Item::get_items_subtotal()',
2045
-            sprintf(
2046
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2047
-                'EEH_Line_Item::get_pre_tax_subtotal()'
2048
-            ),
2049
-            '4.6.0'
2050
-        );
2051
-        return self::get_pre_tax_subtotal($total_line_item);
2052
-    }
2053
-
2054
-
2055
-    /**
2056
-     * @deprecated
2057
-     * @param EE_Transaction $transaction
2058
-     * @return EE_Line_Item
2059
-     * @throws EE_Error
2060
-     * @throws InvalidArgumentException
2061
-     * @throws InvalidDataTypeException
2062
-     * @throws InvalidInterfaceException
2063
-     * @throws ReflectionException
2064
-     */
2065
-    public static function create_default_total_line_item($transaction = null)
2066
-    {
2067
-        EE_Error::doing_it_wrong(
2068
-            'EEH_Line_Item::create_default_total_line_item()',
2069
-            sprintf(
2070
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2071
-                'EEH_Line_Item::create_total_line_item()'
2072
-            ),
2073
-            '4.6.0'
2074
-        );
2075
-        return self::create_total_line_item($transaction);
2076
-    }
2077
-
2078
-
2079
-    /**
2080
-     * @deprecated
2081
-     * @param EE_Line_Item   $total_line_item
2082
-     * @param EE_Transaction $transaction
2083
-     * @return EE_Line_Item
2084
-     * @throws EE_Error
2085
-     * @throws InvalidArgumentException
2086
-     * @throws InvalidDataTypeException
2087
-     * @throws InvalidInterfaceException
2088
-     * @throws ReflectionException
2089
-     */
2090
-    public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2091
-    {
2092
-        EE_Error::doing_it_wrong(
2093
-            'EEH_Line_Item::create_default_tickets_subtotal()',
2094
-            sprintf(
2095
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2096
-                'EEH_Line_Item::create_pre_tax_subtotal()'
2097
-            ),
2098
-            '4.6.0'
2099
-        );
2100
-        return self::create_pre_tax_subtotal($total_line_item, $transaction);
2101
-    }
2102
-
2103
-
2104
-    /**
2105
-     * @deprecated
2106
-     * @param EE_Line_Item   $total_line_item
2107
-     * @param EE_Transaction $transaction
2108
-     * @return EE_Line_Item
2109
-     * @throws EE_Error
2110
-     * @throws InvalidArgumentException
2111
-     * @throws InvalidDataTypeException
2112
-     * @throws InvalidInterfaceException
2113
-     * @throws ReflectionException
2114
-     */
2115
-    public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2116
-    {
2117
-        EE_Error::doing_it_wrong(
2118
-            'EEH_Line_Item::create_default_taxes_subtotal()',
2119
-            sprintf(
2120
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2121
-                'EEH_Line_Item::create_taxes_subtotal()'
2122
-            ),
2123
-            '4.6.0'
2124
-        );
2125
-        return self::create_taxes_subtotal($total_line_item, $transaction);
2126
-    }
2127
-
2128
-
2129
-    /**
2130
-     * @deprecated
2131
-     * @param EE_Line_Item   $total_line_item
2132
-     * @param EE_Transaction $transaction
2133
-     * @return EE_Line_Item
2134
-     * @throws EE_Error
2135
-     * @throws InvalidArgumentException
2136
-     * @throws InvalidDataTypeException
2137
-     * @throws InvalidInterfaceException
2138
-     * @throws ReflectionException
2139
-     */
2140
-    public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2141
-    {
2142
-        EE_Error::doing_it_wrong(
2143
-            'EEH_Line_Item::create_default_event_subtotal()',
2144
-            sprintf(
2145
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2146
-                'EEH_Line_Item::create_event_subtotal()'
2147
-            ),
2148
-            '4.6.0'
2149
-        );
2150
-        return self::create_event_subtotal($total_line_item, $transaction);
2151
-    }
24
+	/**
25
+	 * @var EE_Line_Item[]
26
+	 */
27
+	private static $global_taxes;
28
+
29
+
30
+	/**
31
+	 * Adds a simple item (unrelated to any other model object) to the provided PARENT line item.
32
+	 * Does NOT automatically re-calculate the line item totals or update the related transaction.
33
+	 * You should call recalculate_total_including_taxes() on the grant total line item after this
34
+	 * to update the subtotals, and EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
35
+	 * to keep the registration final prices in-sync with the transaction's total.
36
+	 *
37
+	 * @param EE_Line_Item $parent_line_item
38
+	 * @param string       $name
39
+	 * @param float        $unit_price
40
+	 * @param string       $description
41
+	 * @param int          $quantity
42
+	 * @param boolean      $taxable
43
+	 * @param string|null  $code if set to a value, ensures there is only one line item with that code
44
+	 * @param bool         $return_item
45
+	 * @param bool         $recalculate_totals
46
+	 * @return boolean|EE_Line_Item success
47
+	 * @throws EE_Error
48
+	 * @throws ReflectionException
49
+	 */
50
+	public static function add_unrelated_item(
51
+		EE_Line_Item $parent_line_item,
52
+		string $name,
53
+		float $unit_price,
54
+		string $description = '',
55
+		int $quantity = 1,
56
+		bool $taxable = false,
57
+		?string $code = null,
58
+		bool $return_item = false,
59
+		bool $recalculate_totals = true
60
+	) {
61
+		$items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
62
+		$line_item      = EE_Line_Item::new_instance(
63
+			[
64
+				'LIN_name'       => $name,
65
+				'LIN_desc'       => $description,
66
+				'LIN_unit_price' => $unit_price,
67
+				'LIN_quantity'   => $quantity,
68
+				'LIN_percent'    => null,
69
+				'LIN_is_taxable' => $taxable,
70
+				'LIN_order'      => $items_subtotal instanceof EE_Line_Item
71
+					? count($items_subtotal->children())
72
+					: 0,
73
+				'LIN_total'      => (float) $unit_price * (int) $quantity,
74
+				'LIN_type'       => EEM_Line_Item::type_line_item,
75
+				'LIN_code'       => $code,
76
+			]
77
+		);
78
+		$line_item      = apply_filters(
79
+			'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
80
+			$line_item,
81
+			$parent_line_item
82
+		);
83
+		$added          = self::add_item($parent_line_item, $line_item, $recalculate_totals);
84
+		return $return_item ? $line_item : $added;
85
+	}
86
+
87
+
88
+	/**
89
+	 * Adds a simple item ( unrelated to any other model object) to the total line item,
90
+	 * in the correct spot in the line item tree. Does not automatically
91
+	 * re-calculate the line item totals, nor update the related transaction, nor upgrade the transaction's
92
+	 * registrations' final prices (which should probably change because of this).
93
+	 * You should call recalculate_total_including_taxes() on the grand total line item, then
94
+	 * update the transaction's total, and EE_Registration_Processor::update_registration_final_prices()
95
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
96
+	 *
97
+	 * @param EE_Line_Item $parent_line_item
98
+	 * @param string       $name
99
+	 * @param float        $percentage_amount
100
+	 * @param string       $description
101
+	 * @param boolean      $taxable
102
+	 * @param string|null  $code
103
+	 * @param bool         $return_item
104
+	 * @return boolean|EE_Line_Item success
105
+	 * @throws EE_Error
106
+	 * @throws ReflectionException
107
+	 */
108
+	public static function add_percentage_based_item(
109
+		EE_Line_Item $parent_line_item,
110
+		string $name,
111
+		float $percentage_amount,
112
+		string $description = '',
113
+		bool $taxable = false,
114
+		?string $code = null,
115
+		bool $return_item = false
116
+	) {
117
+		$total = $percentage_amount * $parent_line_item->total() / 100;
118
+		$line_item = EE_Line_Item::new_instance(
119
+			[
120
+				'LIN_name'       => $name,
121
+				'LIN_desc'       => $description,
122
+				'LIN_unit_price' => 0,
123
+				'LIN_percent'    => $percentage_amount,
124
+				'LIN_quantity'   => 1,
125
+				'LIN_is_taxable' => $taxable,
126
+				'LIN_total'      => (float) $total,
127
+				'LIN_type'       => EEM_Line_Item::type_line_item,
128
+				'LIN_parent'     => $parent_line_item->ID(),
129
+				'LIN_code'       => $code,
130
+			]
131
+		);
132
+		$line_item = apply_filters(
133
+			'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
134
+			$line_item
135
+		);
136
+		$added     = $parent_line_item->add_child_line_item($line_item, false);
137
+		return $return_item ? $line_item : $added;
138
+	}
139
+
140
+
141
+	/**
142
+	 * Returns the new line item created by adding a purchase of the ticket
143
+	 * ensures that ticket line item is saved, and that cart total has been recalculated.
144
+	 * If this ticket has already been purchased, just increments its count.
145
+	 * Automatically re-calculates the line item totals and updates the related transaction. But
146
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
147
+	 * should probably change because of this).
148
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
149
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
150
+	 *
151
+	 * @param EE_Line_Item|null $total_line_item grand total line item of type EEM_Line_Item::type_total
152
+	 * @param EE_Ticket         $ticket
153
+	 * @param int               $qty
154
+	 * @return EE_Line_Item
155
+	 * @throws EE_Error
156
+	 * @throws ReflectionException
157
+	 */
158
+	public static function add_ticket_purchase(
159
+		?EE_Line_Item $total_line_item,
160
+		EE_Ticket $ticket,
161
+		int $qty = 1
162
+	): ?EE_Line_Item {
163
+		if (! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
164
+			throw new EE_Error(
165
+				sprintf(
166
+					esc_html__(
167
+						'A valid line item total is required in order to add tickets. A line item of type "%s" was passed.',
168
+						'event_espresso'
169
+					),
170
+					$ticket->ID(),
171
+					$total_line_item->ID()
172
+				)
173
+			);
174
+		}
175
+		// either increment the qty for an existing ticket
176
+		$line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
177
+		// or add a new one
178
+		if (! $line_item instanceof EE_Line_Item) {
179
+			$line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
180
+		}
181
+		$total_line_item->recalculate_total_including_taxes();
182
+		return $line_item;
183
+	}
184
+
185
+
186
+	/**
187
+	 * Returns the new line item created by adding a purchase of the ticket
188
+	 *
189
+	 * @param EE_Line_Item $total_line_item
190
+	 * @param EE_Ticket    $ticket
191
+	 * @param int          $qty
192
+	 * @return EE_Line_Item
193
+	 * @throws EE_Error
194
+	 * @throws InvalidArgumentException
195
+	 * @throws InvalidDataTypeException
196
+	 * @throws InvalidInterfaceException
197
+	 * @throws ReflectionException
198
+	 */
199
+	public static function increment_ticket_qty_if_already_in_cart(
200
+		EE_Line_Item $total_line_item,
201
+		EE_Ticket $ticket,
202
+		$qty = 1
203
+	) {
204
+		$line_item = null;
205
+		if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
206
+			$ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
207
+			foreach ($ticket_line_items as $ticket_line_item) {
208
+				if (
209
+					$ticket_line_item instanceof EE_Line_Item
210
+					&& (int) $ticket_line_item->OBJ_ID() === (int) $ticket->ID()
211
+				) {
212
+					$line_item = $ticket_line_item;
213
+					break;
214
+				}
215
+			}
216
+		}
217
+		if ($line_item instanceof EE_Line_Item) {
218
+			EEH_Line_Item::increment_quantity($line_item, $qty);
219
+			return $line_item;
220
+		}
221
+		return null;
222
+	}
223
+
224
+
225
+	/**
226
+	 * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
227
+	 * Does NOT save or recalculate other line items totals
228
+	 *
229
+	 * @param EE_Line_Item $line_item
230
+	 * @param int          $qty
231
+	 * @return void
232
+	 * @throws EE_Error
233
+	 * @throws InvalidArgumentException
234
+	 * @throws InvalidDataTypeException
235
+	 * @throws InvalidInterfaceException
236
+	 * @throws ReflectionException
237
+	 */
238
+	public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
239
+	{
240
+		if (! $line_item->is_percent()) {
241
+			$qty += $line_item->quantity();
242
+			$line_item->set_quantity($qty);
243
+			$line_item->set_total($line_item->unit_price() * $qty);
244
+			$line_item->save();
245
+		}
246
+		foreach ($line_item->children() as $child) {
247
+			if ($child->is_sub_line_item()) {
248
+				EEH_Line_Item::update_quantity($child, $qty);
249
+			}
250
+		}
251
+	}
252
+
253
+
254
+	/**
255
+	 * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
256
+	 * Does NOT save or recalculate other line items totals
257
+	 *
258
+	 * @param EE_Line_Item $line_item
259
+	 * @param int          $qty
260
+	 * @return void
261
+	 * @throws EE_Error
262
+	 * @throws InvalidArgumentException
263
+	 * @throws InvalidDataTypeException
264
+	 * @throws InvalidInterfaceException
265
+	 * @throws ReflectionException
266
+	 */
267
+	public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
268
+	{
269
+		if (! $line_item->is_percent()) {
270
+			$qty = $line_item->quantity() - $qty;
271
+			$qty = max($qty, 0);
272
+			$line_item->set_quantity($qty);
273
+			$line_item->set_total($line_item->unit_price() * $qty);
274
+			$line_item->save();
275
+		}
276
+		foreach ($line_item->children() as $child) {
277
+			if ($child->is_sub_line_item()) {
278
+				EEH_Line_Item::update_quantity($child, $qty);
279
+			}
280
+		}
281
+	}
282
+
283
+
284
+	/**
285
+	 * Updates the line item and its children's quantities to the specified number.
286
+	 * Does NOT save them or recalculate totals.
287
+	 *
288
+	 * @param EE_Line_Item $line_item
289
+	 * @param int          $new_quantity
290
+	 * @throws EE_Error
291
+	 * @throws InvalidArgumentException
292
+	 * @throws InvalidDataTypeException
293
+	 * @throws InvalidInterfaceException
294
+	 * @throws ReflectionException
295
+	 */
296
+	public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
297
+	{
298
+		if (! $line_item->is_percent()) {
299
+			$line_item->set_quantity($new_quantity);
300
+			$line_item->set_total($line_item->unit_price() * $new_quantity);
301
+			$line_item->save();
302
+		}
303
+		foreach ($line_item->children() as $child) {
304
+			if ($child->is_sub_line_item()) {
305
+				EEH_Line_Item::update_quantity($child, $new_quantity);
306
+			}
307
+		}
308
+	}
309
+
310
+
311
+	/**
312
+	 * Returns the new line item created by adding a purchase of the ticket
313
+	 *
314
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
315
+	 * @param EE_Ticket    $ticket
316
+	 * @param int          $qty
317
+	 * @return EE_Line_Item
318
+	 * @throws EE_Error
319
+	 * @throws InvalidArgumentException
320
+	 * @throws InvalidDataTypeException
321
+	 * @throws InvalidInterfaceException
322
+	 * @throws ReflectionException
323
+	 */
324
+	public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
325
+	{
326
+		$datetimes = $ticket->datetimes();
327
+		$first_datetime = reset($datetimes);
328
+		$first_datetime_name = esc_html__('Event', 'event_espresso');
329
+		if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
330
+			$first_datetime_name = $first_datetime->event()->name();
331
+		}
332
+		$event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
333
+		// get event subtotal line
334
+		$events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
335
+		$taxes = $ticket->tax_price_modifiers();
336
+		// add $ticket to cart
337
+		$line_item = EE_Line_Item::new_instance(array(
338
+			'LIN_name'       => $ticket->name(),
339
+			'LIN_desc'       => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
340
+			'LIN_unit_price' => $ticket->price(),
341
+			'LIN_quantity'   => $qty,
342
+			'LIN_is_taxable' => empty($taxes) && $ticket->taxable(),
343
+			'LIN_order'      => count($events_sub_total->children()),
344
+			'LIN_total'      => $ticket->price() * $qty,
345
+			'LIN_type'       => EEM_Line_Item::type_line_item,
346
+			'OBJ_ID'         => $ticket->ID(),
347
+			'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_TICKET,
348
+		));
349
+		$line_item = apply_filters(
350
+			'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
351
+			$line_item
352
+		);
353
+		if (!$line_item instanceof EE_Line_Item) {
354
+			throw new DomainException(
355
+				esc_html__('Invalid EE_Line_Item received.', 'event_espresso')
356
+			);
357
+		}
358
+		$events_sub_total->add_child_line_item($line_item);
359
+		// now add the sub-line items
360
+		$running_total = 0;
361
+		$running_pre_tax_total = 0;
362
+		foreach ($ticket->prices() as $price) {
363
+			$sign = $price->is_discount() ? -1 : 1;
364
+			$price_total = $price->is_percent()
365
+				? $running_pre_tax_total * $price->amount() / 100
366
+				: $price->amount() * $qty;
367
+			if ($price->is_percent()) {
368
+				$percent = $sign * $price->amount();
369
+				$unit_price = 0;
370
+			} else {
371
+				$percent    = 0;
372
+				$unit_price = $sign * $price->amount();
373
+			}
374
+			$sub_line_item = EE_Line_Item::new_instance(array(
375
+				'LIN_name'       => $price->name(),
376
+				'LIN_desc'       => $price->desc(),
377
+				'LIN_quantity'   => $price->is_percent() ? null : $qty,
378
+				'LIN_is_taxable' => false,
379
+				'LIN_order'      => $price->order(),
380
+				'LIN_total'      => $price_total,
381
+				'LIN_pretax'     => 0,
382
+				'LIN_unit_price' => $unit_price,
383
+				'LIN_percent'    => $percent,
384
+				'LIN_type'       => $price->is_tax() ? EEM_Line_Item::type_sub_tax : EEM_Line_Item::type_sub_line_item,
385
+				'OBJ_ID'         => $price->ID(),
386
+				'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
387
+			));
388
+			$sub_line_item = apply_filters(
389
+				'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
390
+				$sub_line_item
391
+			);
392
+			$running_total += $sign * $price_total;
393
+			$running_pre_tax_total += ! $price->is_tax() ? $sign * $price_total : 0;
394
+			$line_item->add_child_line_item($sub_line_item);
395
+		}
396
+		$line_item->setPretaxTotal($running_pre_tax_total);
397
+		return $line_item;
398
+	}
399
+
400
+
401
+	/**
402
+	 * Adds the specified item under the pre-tax-sub-total line item. Automatically
403
+	 * re-calculates the line item totals and updates the related transaction. But
404
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
405
+	 * should probably change because of this).
406
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
407
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
408
+	 *
409
+	 * @param EE_Line_Item $total_line_item
410
+	 * @param EE_Line_Item $item to be added
411
+	 * @return boolean
412
+	 * @throws EE_Error
413
+	 * @throws InvalidArgumentException
414
+	 * @throws InvalidDataTypeException
415
+	 * @throws InvalidInterfaceException
416
+	 * @throws ReflectionException
417
+	 */
418
+	public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item, $recalculate_totals = true)
419
+	{
420
+		$pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
421
+		if ($pre_tax_subtotal instanceof EE_Line_Item) {
422
+			$success = $pre_tax_subtotal->add_child_line_item($item);
423
+		} else {
424
+			return false;
425
+		}
426
+		if ($recalculate_totals) {
427
+			$total_line_item->recalculate_total_including_taxes();
428
+		}
429
+		return $success;
430
+	}
431
+
432
+
433
+	/**
434
+	 * cancels an existing ticket line item,
435
+	 * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
436
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
437
+	 *
438
+	 * @param EE_Line_Item $ticket_line_item
439
+	 * @param int          $qty
440
+	 * @return bool success
441
+	 * @throws EE_Error
442
+	 * @throws InvalidArgumentException
443
+	 * @throws InvalidDataTypeException
444
+	 * @throws InvalidInterfaceException
445
+	 * @throws ReflectionException
446
+	 */
447
+	public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
448
+	{
449
+		// validate incoming line_item
450
+		if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
451
+			throw new EE_Error(
452
+				sprintf(
453
+					esc_html__(
454
+						'The supplied line item must have an Object Type of "Ticket", not %1$s.',
455
+						'event_espresso'
456
+					),
457
+					$ticket_line_item->type()
458
+				)
459
+			);
460
+		}
461
+		if ($ticket_line_item->quantity() < $qty) {
462
+			throw new EE_Error(
463
+				sprintf(
464
+					esc_html__(
465
+						'Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.',
466
+						'event_espresso'
467
+					),
468
+					$qty,
469
+					$ticket_line_item->quantity()
470
+				)
471
+			);
472
+		}
473
+		// decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
474
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
475
+		foreach ($ticket_line_item->children() as $child_line_item) {
476
+			if (
477
+				$child_line_item->is_sub_line_item()
478
+				&& ! $child_line_item->is_percent()
479
+				&& ! $child_line_item->is_cancellation()
480
+			) {
481
+				$child_line_item->set_quantity($child_line_item->quantity() - $qty);
482
+			}
483
+		}
484
+		// get cancellation sub line item
485
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
486
+			$ticket_line_item,
487
+			EEM_Line_Item::type_cancellation
488
+		);
489
+		$cancellation_line_item = reset($cancellation_line_item);
490
+		// verify that this ticket was indeed previously cancelled
491
+		if ($cancellation_line_item instanceof EE_Line_Item) {
492
+			// increment cancelled quantity
493
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
494
+		} else {
495
+			// create cancellation sub line item
496
+			$cancellation_line_item = EE_Line_Item::new_instance(array(
497
+				'LIN_name'       => esc_html__('Cancellation', 'event_espresso'),
498
+				'LIN_desc'       => sprintf(
499
+					esc_html_x(
500
+						'Cancelled %1$s : %2$s',
501
+						'Cancelled Ticket Name : 2015-01-01 11:11',
502
+						'event_espresso'
503
+					),
504
+					$ticket_line_item->name(),
505
+					current_time(get_option('date_format') . ' ' . get_option('time_format'))
506
+				),
507
+				'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
508
+				'LIN_quantity'   => $qty,
509
+				'LIN_is_taxable' => $ticket_line_item->is_taxable(),
510
+				'LIN_order'      => count($ticket_line_item->children()),
511
+				'LIN_total'      => 0, // $ticket_line_item->unit_price()
512
+				'LIN_type'       => EEM_Line_Item::type_cancellation,
513
+			));
514
+			$ticket_line_item->add_child_line_item($cancellation_line_item);
515
+		}
516
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
517
+			// decrement parent line item quantity
518
+			$event_line_item = $ticket_line_item->parent();
519
+			if (
520
+				$event_line_item instanceof EE_Line_Item
521
+				&& $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
522
+			) {
523
+				$event_line_item->set_quantity($event_line_item->quantity() - $qty);
524
+				$event_line_item->save();
525
+			}
526
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
527
+			return true;
528
+		}
529
+		return false;
530
+	}
531
+
532
+
533
+	/**
534
+	 * reinstates (un-cancels?) a previously canceled ticket line item,
535
+	 * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
536
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
537
+	 *
538
+	 * @param EE_Line_Item $ticket_line_item
539
+	 * @param int          $qty
540
+	 * @return bool success
541
+	 * @throws EE_Error
542
+	 * @throws InvalidArgumentException
543
+	 * @throws InvalidDataTypeException
544
+	 * @throws InvalidInterfaceException
545
+	 * @throws ReflectionException
546
+	 */
547
+	public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
548
+	{
549
+		// validate incoming line_item
550
+		if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
551
+			throw new EE_Error(
552
+				sprintf(
553
+					esc_html__(
554
+						'The supplied line item must have an Object Type of "Ticket", not %1$s.',
555
+						'event_espresso'
556
+					),
557
+					$ticket_line_item->type()
558
+				)
559
+			);
560
+		}
561
+		// get cancellation sub line item
562
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
563
+			$ticket_line_item,
564
+			EEM_Line_Item::type_cancellation
565
+		);
566
+		$cancellation_line_item = reset($cancellation_line_item);
567
+		// verify that this ticket was indeed previously cancelled
568
+		if (! $cancellation_line_item instanceof EE_Line_Item) {
569
+			return false;
570
+		}
571
+		if ($cancellation_line_item->quantity() > $qty) {
572
+			// decrement cancelled quantity
573
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
574
+		} elseif ($cancellation_line_item->quantity() === $qty) {
575
+			// decrement cancelled quantity in case anyone still has the object kicking around
576
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
577
+			// delete because quantity will end up as 0
578
+			$cancellation_line_item->delete();
579
+			// and attempt to destroy the object,
580
+			// even though PHP won't actually destroy it until it needs the memory
581
+			unset($cancellation_line_item);
582
+		} else {
583
+			// what ?!?! negative quantity ?!?!
584
+			throw new EE_Error(
585
+				sprintf(
586
+					esc_html__(
587
+						'Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
588
+						'event_espresso'
589
+					),
590
+					$qty,
591
+					$cancellation_line_item->quantity()
592
+				)
593
+			);
594
+		}
595
+		// increment ticket quantity
596
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
597
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
598
+			// increment parent line item quantity
599
+			$event_line_item = $ticket_line_item->parent();
600
+			if (
601
+				$event_line_item instanceof EE_Line_Item
602
+				&& $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
603
+			) {
604
+				$event_line_item->set_quantity($event_line_item->quantity() + $qty);
605
+			}
606
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
607
+			return true;
608
+		}
609
+		return false;
610
+	}
611
+
612
+
613
+	/**
614
+	 * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
615
+	 * then EE_Line_Item::recalculate_total_including_taxes() on the result
616
+	 *
617
+	 * @param EE_Line_Item $line_item
618
+	 * @return float
619
+	 * @throws EE_Error
620
+	 * @throws InvalidArgumentException
621
+	 * @throws InvalidDataTypeException
622
+	 * @throws InvalidInterfaceException
623
+	 * @throws ReflectionException
624
+	 */
625
+	public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
626
+	{
627
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
628
+		return $grand_total_line_item->recalculate_total_including_taxes();
629
+	}
630
+
631
+
632
+	/**
633
+	 * Gets the line item which contains the subtotal of all the items
634
+	 *
635
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
636
+	 * @return EE_Line_Item
637
+	 * @throws EE_Error
638
+	 * @throws InvalidArgumentException
639
+	 * @throws InvalidDataTypeException
640
+	 * @throws InvalidInterfaceException
641
+	 * @throws ReflectionException
642
+	 */
643
+	public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
644
+	{
645
+		$pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
646
+		return $pre_tax_subtotal instanceof EE_Line_Item
647
+			? $pre_tax_subtotal
648
+			: self::create_pre_tax_subtotal($total_line_item);
649
+	}
650
+
651
+
652
+	/**
653
+	 * Gets the line item for the taxes subtotal
654
+	 *
655
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
656
+	 * @return EE_Line_Item
657
+	 * @throws EE_Error
658
+	 * @throws InvalidArgumentException
659
+	 * @throws InvalidDataTypeException
660
+	 * @throws InvalidInterfaceException
661
+	 * @throws ReflectionException
662
+	 */
663
+	public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
664
+	{
665
+		$taxes = $total_line_item->get_child_line_item('taxes');
666
+		return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
667
+	}
668
+
669
+
670
+	/**
671
+	 * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
672
+	 *
673
+	 * @param EE_Line_Item   $line_item
674
+	 * @param EE_Transaction $transaction
675
+	 * @return void
676
+	 * @throws EE_Error
677
+	 * @throws InvalidArgumentException
678
+	 * @throws InvalidDataTypeException
679
+	 * @throws InvalidInterfaceException
680
+	 * @throws ReflectionException
681
+	 */
682
+	public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = null)
683
+	{
684
+		if ($transaction) {
685
+			/** @type EEM_Transaction $EEM_Transaction */
686
+			$EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
687
+			$TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
688
+			$line_item->set_TXN_ID($TXN_ID);
689
+		}
690
+	}
691
+
692
+
693
+	/**
694
+	 * Creates a new default total line item for the transaction,
695
+	 * and its tickets subtotal and taxes subtotal line items (and adds the
696
+	 * existing taxes as children of the taxes subtotal line item)
697
+	 *
698
+	 * @param EE_Transaction $transaction
699
+	 * @return EE_Line_Item of type total
700
+	 * @throws EE_Error
701
+	 * @throws InvalidArgumentException
702
+	 * @throws InvalidDataTypeException
703
+	 * @throws InvalidInterfaceException
704
+	 * @throws ReflectionException
705
+	 */
706
+	public static function create_total_line_item($transaction = null)
707
+	{
708
+		$total_line_item = EE_Line_Item::new_instance(array(
709
+			'LIN_code' => 'total',
710
+			'LIN_name' => esc_html__('Grand Total', 'event_espresso'),
711
+			'LIN_type' => EEM_Line_Item::type_total,
712
+			'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TRANSACTION,
713
+		));
714
+		$total_line_item = apply_filters(
715
+			'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
716
+			$total_line_item
717
+		);
718
+		self::set_TXN_ID($total_line_item, $transaction);
719
+		self::create_pre_tax_subtotal($total_line_item, $transaction);
720
+		self::create_taxes_subtotal($total_line_item, $transaction);
721
+		return $total_line_item;
722
+	}
723
+
724
+
725
+	/**
726
+	 * Creates a default items subtotal line item
727
+	 *
728
+	 * @param EE_Line_Item   $total_line_item
729
+	 * @param EE_Transaction $transaction
730
+	 * @return EE_Line_Item
731
+	 * @throws EE_Error
732
+	 * @throws InvalidArgumentException
733
+	 * @throws InvalidDataTypeException
734
+	 * @throws InvalidInterfaceException
735
+	 * @throws ReflectionException
736
+	 */
737
+	protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = null)
738
+	{
739
+		$pre_tax_line_item = EE_Line_Item::new_instance(array(
740
+			'LIN_code' => 'pre-tax-subtotal',
741
+			'LIN_name' => esc_html__('Pre-Tax Subtotal', 'event_espresso'),
742
+			'LIN_type' => EEM_Line_Item::type_sub_total,
743
+		));
744
+		$pre_tax_line_item = apply_filters(
745
+			'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
746
+			$pre_tax_line_item
747
+		);
748
+		self::set_TXN_ID($pre_tax_line_item, $transaction);
749
+		$total_line_item->add_child_line_item($pre_tax_line_item);
750
+		self::create_event_subtotal($pre_tax_line_item, $transaction);
751
+		return $pre_tax_line_item;
752
+	}
753
+
754
+
755
+	/**
756
+	 * Creates a line item for the taxes subtotal and finds all the tax prices
757
+	 * and applies taxes to it
758
+	 *
759
+	 * @param EE_Line_Item   $total_line_item of type EEM_Line_Item::type_total
760
+	 * @param EE_Transaction $transaction
761
+	 * @return EE_Line_Item
762
+	 * @throws EE_Error
763
+	 * @throws InvalidArgumentException
764
+	 * @throws InvalidDataTypeException
765
+	 * @throws InvalidInterfaceException
766
+	 * @throws ReflectionException
767
+	 */
768
+	protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
769
+	{
770
+		$tax_line_item = EE_Line_Item::new_instance(array(
771
+			'LIN_code'  => 'taxes',
772
+			'LIN_name'  => esc_html__('Taxes', 'event_espresso'),
773
+			'LIN_type'  => EEM_Line_Item::type_tax_sub_total,
774
+			'LIN_order' => 1000,// this should always come last
775
+		));
776
+		$tax_line_item = apply_filters(
777
+			'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
778
+			$tax_line_item
779
+		);
780
+		self::set_TXN_ID($tax_line_item, $transaction);
781
+		$total_line_item->add_child_line_item($tax_line_item);
782
+		// and lastly, add the actual taxes
783
+		self::apply_taxes($total_line_item);
784
+		return $tax_line_item;
785
+	}
786
+
787
+
788
+	/**
789
+	 * Creates a default items subtotal line item
790
+	 *
791
+	 * @param EE_Line_Item   $pre_tax_line_item
792
+	 * @param EE_Transaction $transaction
793
+	 * @param EE_Event       $event
794
+	 * @return EE_Line_Item
795
+	 * @throws EE_Error
796
+	 * @throws InvalidArgumentException
797
+	 * @throws InvalidDataTypeException
798
+	 * @throws InvalidInterfaceException
799
+	 * @throws ReflectionException
800
+	 */
801
+	public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = null, $event = null)
802
+	{
803
+		$event_line_item = EE_Line_Item::new_instance(array(
804
+			'LIN_code' => self::get_event_code($event),
805
+			'LIN_name' => self::get_event_name($event),
806
+			'LIN_desc' => self::get_event_desc($event),
807
+			'LIN_type' => EEM_Line_Item::type_sub_total,
808
+			'OBJ_type' => EEM_Line_Item::OBJ_TYPE_EVENT,
809
+			'OBJ_ID'   => $event instanceof EE_Event ? $event->ID() : 0,
810
+		));
811
+		$event_line_item = apply_filters(
812
+			'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
813
+			$event_line_item
814
+		);
815
+		self::set_TXN_ID($event_line_item, $transaction);
816
+		$pre_tax_line_item->add_child_line_item($event_line_item);
817
+		return $event_line_item;
818
+	}
819
+
820
+
821
+	/**
822
+	 * Gets what the event ticket's code SHOULD be
823
+	 *
824
+	 * @param EE_Event $event
825
+	 * @return string
826
+	 * @throws EE_Error
827
+	 */
828
+	public static function get_event_code($event)
829
+	{
830
+		return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
831
+	}
832
+
833
+
834
+	/**
835
+	 * Gets the event name
836
+	 *
837
+	 * @param EE_Event $event
838
+	 * @return string
839
+	 * @throws EE_Error
840
+	 */
841
+	public static function get_event_name($event)
842
+	{
843
+		return $event instanceof EE_Event
844
+			? mb_substr($event->name(), 0, 245)
845
+			: esc_html__('Event', 'event_espresso');
846
+	}
847
+
848
+
849
+	/**
850
+	 * Gets the event excerpt
851
+	 *
852
+	 * @param EE_Event $event
853
+	 * @return string
854
+	 * @throws EE_Error
855
+	 */
856
+	public static function get_event_desc($event)
857
+	{
858
+		return $event instanceof EE_Event ? $event->short_description() : '';
859
+	}
860
+
861
+
862
+	/**
863
+	 * Given the grand total line item and a ticket, finds the event sub-total
864
+	 * line item the ticket's purchase should be added onto
865
+	 *
866
+	 * @access public
867
+	 * @param EE_Line_Item $grand_total the grand total line item
868
+	 * @param EE_Ticket    $ticket
869
+	 * @return EE_Line_Item
870
+	 * @throws EE_Error
871
+	 * @throws InvalidArgumentException
872
+	 * @throws InvalidDataTypeException
873
+	 * @throws InvalidInterfaceException
874
+	 * @throws ReflectionException
875
+	 */
876
+	public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
877
+	{
878
+		$first_datetime = $ticket->first_datetime();
879
+		if (! $first_datetime instanceof EE_Datetime) {
880
+			throw new EE_Error(
881
+				sprintf(
882
+					esc_html__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'),
883
+					$ticket->ID()
884
+				)
885
+			);
886
+		}
887
+		$event = $first_datetime->event();
888
+		if (! $event instanceof EE_Event) {
889
+			throw new EE_Error(
890
+				sprintf(
891
+					esc_html__(
892
+						'The supplied ticket (ID %d) has no event data associated with it.',
893
+						'event_espresso'
894
+					),
895
+					$ticket->ID()
896
+				)
897
+			);
898
+		}
899
+		$events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
900
+		if (! $events_sub_total instanceof EE_Line_Item) {
901
+			throw new EE_Error(
902
+				sprintf(
903
+					esc_html__(
904
+						'There is no events sub-total for ticket %s on total line item %d',
905
+						'event_espresso'
906
+					),
907
+					$ticket->ID(),
908
+					$grand_total->ID()
909
+				)
910
+			);
911
+		}
912
+		return $events_sub_total;
913
+	}
914
+
915
+
916
+	/**
917
+	 * Gets the event line item
918
+	 *
919
+	 * @param EE_Line_Item $grand_total
920
+	 * @param EE_Event     $event
921
+	 * @return EE_Line_Item for the event subtotal which is a child of $grand_total
922
+	 * @throws EE_Error
923
+	 * @throws InvalidArgumentException
924
+	 * @throws InvalidDataTypeException
925
+	 * @throws InvalidInterfaceException
926
+	 * @throws ReflectionException
927
+	 */
928
+	public static function get_event_line_item(EE_Line_Item $grand_total, $event)
929
+	{
930
+		/** @type EE_Event $event */
931
+		$event = EEM_Event::instance()->ensure_is_obj($event, true);
932
+		$event_line_item = null;
933
+		$found = false;
934
+		foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
935
+			// default event subtotal, we should only ever find this the first time this method is called
936
+			if (! $event_line_item->OBJ_ID()) {
937
+				// let's use this! but first... set the event details
938
+				EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
939
+				$found = true;
940
+				break;
941
+			}
942
+			if ($event_line_item->OBJ_ID() === $event->ID()) {
943
+				// found existing line item for this event in the cart, so break out of loop and use this one
944
+				$found = true;
945
+				break;
946
+			}
947
+		}
948
+		if (! $found) {
949
+			// there is no event sub-total yet, so add it
950
+			$pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
951
+			// create a new "event" subtotal below that
952
+			$event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
953
+			// and set the event details
954
+			EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
955
+		}
956
+		return $event_line_item;
957
+	}
958
+
959
+
960
+	/**
961
+	 * Creates a default items subtotal line item
962
+	 *
963
+	 * @param EE_Line_Item   $event_line_item
964
+	 * @param EE_Event       $event
965
+	 * @param EE_Transaction $transaction
966
+	 * @return void
967
+	 * @throws EE_Error
968
+	 * @throws InvalidArgumentException
969
+	 * @throws InvalidDataTypeException
970
+	 * @throws InvalidInterfaceException
971
+	 * @throws ReflectionException
972
+	 */
973
+	public static function set_event_subtotal_details(
974
+		EE_Line_Item $event_line_item,
975
+		EE_Event $event,
976
+		$transaction = null
977
+	) {
978
+		if ($event instanceof EE_Event) {
979
+			$event_line_item->set_code(self::get_event_code($event));
980
+			$event_line_item->set_name(self::get_event_name($event));
981
+			$event_line_item->set_desc(self::get_event_desc($event));
982
+			$event_line_item->set_OBJ_ID($event->ID());
983
+		}
984
+		self::set_TXN_ID($event_line_item, $transaction);
985
+	}
986
+
987
+
988
+	/**
989
+	 * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
990
+	 * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
991
+	 * any old taxes are removed
992
+	 *
993
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
994
+	 * @param bool         $update_txn_status
995
+	 * @return bool
996
+	 * @throws EE_Error
997
+	 * @throws InvalidArgumentException
998
+	 * @throws InvalidDataTypeException
999
+	 * @throws InvalidInterfaceException
1000
+	 * @throws ReflectionException
1001
+	 * @throws RuntimeException
1002
+	 */
1003
+	public static function apply_taxes(EE_Line_Item $total_line_item, $update_txn_status = false)
1004
+	{
1005
+		$total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($total_line_item);
1006
+		$taxes_line_item = self::get_taxes_subtotal($total_line_item);
1007
+		$existing_global_taxes = $taxes_line_item->tax_descendants();
1008
+		$updates = false;
1009
+		// loop thru taxes
1010
+		$global_taxes = EEH_Line_Item::getGlobalTaxes();
1011
+		foreach ($global_taxes as $order => $taxes) {
1012
+			foreach ($taxes as $tax) {
1013
+				if ($tax instanceof EE_Price) {
1014
+					$found = false;
1015
+					// check if this is already an existing tax
1016
+					foreach ($existing_global_taxes as $existing_global_tax) {
1017
+						if ($tax->ID() === $existing_global_tax->OBJ_ID()) {
1018
+							// maybe update the tax rate in case it has changed
1019
+							if ($existing_global_tax->percent() !== $tax->amount()) {
1020
+								$existing_global_tax->set_percent($tax->amount());
1021
+								$existing_global_tax->save();
1022
+								$updates = true;
1023
+							}
1024
+							$found = true;
1025
+							break;
1026
+						}
1027
+					}
1028
+					if (! $found) {
1029
+						// add a new line item for this global tax
1030
+						$tax_line_item = apply_filters(
1031
+							'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
1032
+							EE_Line_Item::new_instance(
1033
+								[
1034
+									'LIN_name'       => $tax->name(),
1035
+									'LIN_desc'       => $tax->desc(),
1036
+									'LIN_percent'    => $tax->amount(),
1037
+									'LIN_is_taxable' => false,
1038
+									'LIN_order'      => $order,
1039
+									'LIN_total'      => 0,
1040
+									'LIN_type'       => EEM_Line_Item::type_tax,
1041
+									'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
1042
+									'OBJ_ID'         => $tax->ID(),
1043
+								]
1044
+							)
1045
+						);
1046
+						$updates = $taxes_line_item->add_child_line_item($tax_line_item) ? true : $updates;
1047
+					}
1048
+				}
1049
+			}
1050
+		}
1051
+		// only recalculate totals if something changed
1052
+		if ($updates) {
1053
+			$total_line_item->recalculate_total_including_taxes($update_txn_status);
1054
+			return true;
1055
+		}
1056
+		return false;
1057
+	}
1058
+
1059
+
1060
+	/**
1061
+	 * Ensures that taxes have been applied to the order, if not applies them.
1062
+	 * Returns the total amount of tax
1063
+	 *
1064
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
1065
+	 * @return float
1066
+	 * @throws EE_Error
1067
+	 * @throws InvalidArgumentException
1068
+	 * @throws InvalidDataTypeException
1069
+	 * @throws InvalidInterfaceException
1070
+	 * @throws ReflectionException
1071
+	 */
1072
+	public static function ensure_taxes_applied($total_line_item)
1073
+	{
1074
+		$taxes_subtotal = self::get_taxes_subtotal($total_line_item);
1075
+		if (! $taxes_subtotal->children()) {
1076
+			self::apply_taxes($total_line_item);
1077
+		}
1078
+		return $taxes_subtotal->total();
1079
+	}
1080
+
1081
+
1082
+	/**
1083
+	 * Deletes ALL children of the passed line item
1084
+	 *
1085
+	 * @param EE_Line_Item $parent_line_item
1086
+	 * @return bool
1087
+	 * @throws EE_Error
1088
+	 * @throws InvalidArgumentException
1089
+	 * @throws InvalidDataTypeException
1090
+	 * @throws InvalidInterfaceException
1091
+	 * @throws ReflectionException
1092
+	 */
1093
+	public static function delete_all_child_items(EE_Line_Item $parent_line_item)
1094
+	{
1095
+		$deleted = 0;
1096
+		foreach ($parent_line_item->children() as $child_line_item) {
1097
+			if ($child_line_item instanceof EE_Line_Item) {
1098
+				$deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
1099
+				if ($child_line_item->ID()) {
1100
+					$child_line_item->delete();
1101
+					unset($child_line_item);
1102
+				} else {
1103
+					$parent_line_item->delete_child_line_item($child_line_item->code());
1104
+				}
1105
+				$deleted++;
1106
+			}
1107
+		}
1108
+		return $deleted;
1109
+	}
1110
+
1111
+
1112
+	/**
1113
+	 * Deletes the line items as indicated by the line item code(s) provided,
1114
+	 * regardless of where they're found in the line item tree. Automatically
1115
+	 * re-calculates the line item totals and updates the related transaction. But
1116
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
1117
+	 * should probably change because of this).
1118
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
1119
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
1120
+	 *
1121
+	 * @param EE_Line_Item      $total_line_item of type EEM_Line_Item::type_total
1122
+	 * @param array|bool|string $line_item_codes
1123
+	 * @return int number of items successfully removed
1124
+	 * @throws EE_Error
1125
+	 */
1126
+	public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = false)
1127
+	{
1128
+
1129
+		if ($total_line_item->type() !== EEM_Line_Item::type_total) {
1130
+			EE_Error::doing_it_wrong(
1131
+				'EEH_Line_Item::delete_items',
1132
+				esc_html__(
1133
+					'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
1134
+					'event_espresso'
1135
+				),
1136
+				'4.6.18'
1137
+			);
1138
+		}
1139
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1140
+
1141
+		// check if only a single line_item_id was passed
1142
+		if (! empty($line_item_codes) && ! is_array($line_item_codes)) {
1143
+			// place single line_item_id in an array to appear as multiple line_item_ids
1144
+			$line_item_codes = array($line_item_codes);
1145
+		}
1146
+		$removals = 0;
1147
+		// cycle thru line_item_ids
1148
+		foreach ($line_item_codes as $line_item_id) {
1149
+			$removals += $total_line_item->delete_child_line_item($line_item_id);
1150
+		}
1151
+
1152
+		if ($removals > 0) {
1153
+			$total_line_item->recalculate_taxes_and_tax_total();
1154
+			return $removals;
1155
+		} else {
1156
+			return false;
1157
+		}
1158
+	}
1159
+
1160
+
1161
+	/**
1162
+	 * Overwrites the previous tax by clearing out the old taxes, and creates a new
1163
+	 * tax and updates the total line item accordingly
1164
+	 *
1165
+	 * @param EE_Line_Item $total_line_item
1166
+	 * @param float        $amount
1167
+	 * @param string       $name
1168
+	 * @param string       $description
1169
+	 * @param string       $code
1170
+	 * @param boolean      $add_to_existing_line_item
1171
+	 *                          if true, and a duplicate line item with the same code is found,
1172
+	 *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
1173
+	 * @return EE_Line_Item the new tax line item created
1174
+	 * @throws EE_Error
1175
+	 * @throws InvalidArgumentException
1176
+	 * @throws InvalidDataTypeException
1177
+	 * @throws InvalidInterfaceException
1178
+	 * @throws ReflectionException
1179
+	 */
1180
+	public static function set_total_tax_to(
1181
+		EE_Line_Item $total_line_item,
1182
+		$amount,
1183
+		$name = null,
1184
+		$description = null,
1185
+		$code = null,
1186
+		$add_to_existing_line_item = false
1187
+	) {
1188
+		$tax_subtotal = self::get_taxes_subtotal($total_line_item);
1189
+		$taxable_total = $total_line_item->taxable_total();
1190
+
1191
+		if ($add_to_existing_line_item) {
1192
+			$new_tax = $tax_subtotal->get_child_line_item($code);
1193
+			EEM_Line_Item::instance()->delete(
1194
+				array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
1195
+			);
1196
+		} else {
1197
+			$new_tax = null;
1198
+			$tax_subtotal->delete_children_line_items();
1199
+		}
1200
+		if ($new_tax) {
1201
+			$new_tax->set_total($new_tax->total() + $amount);
1202
+			$new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
1203
+		} else {
1204
+			// no existing tax item. Create it
1205
+			$new_tax = EE_Line_Item::new_instance(array(
1206
+				'TXN_ID'      => $total_line_item->TXN_ID(),
1207
+				'LIN_name'    => $name ?: esc_html__('Tax', 'event_espresso'),
1208
+				'LIN_desc'    => $description ?: '',
1209
+				'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
1210
+				'LIN_total'   => $amount,
1211
+				'LIN_parent'  => $tax_subtotal->ID(),
1212
+				'LIN_type'    => EEM_Line_Item::type_tax,
1213
+				'LIN_code'    => $code,
1214
+			));
1215
+		}
1216
+
1217
+		$new_tax = apply_filters(
1218
+			'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
1219
+			$new_tax,
1220
+			$total_line_item
1221
+		);
1222
+		$new_tax->save();
1223
+		$tax_subtotal->set_total($new_tax->total());
1224
+		$tax_subtotal->save();
1225
+		$total_line_item->recalculate_total_including_taxes();
1226
+		return $new_tax;
1227
+	}
1228
+
1229
+
1230
+	/**
1231
+	 * Makes all the line items which are children of $line_item taxable (or not).
1232
+	 * Does NOT save the line items
1233
+	 *
1234
+	 * @param EE_Line_Item $line_item
1235
+	 * @param boolean      $taxable
1236
+	 * @param string       $code_substring_for_whitelist if this string is part of the line item's code
1237
+	 *                                                   it will be whitelisted (ie, except from becoming taxable)
1238
+	 * @throws EE_Error
1239
+	 */
1240
+	public static function set_line_items_taxable(
1241
+		EE_Line_Item $line_item,
1242
+		$taxable = true,
1243
+		$code_substring_for_whitelist = null
1244
+	) {
1245
+		$whitelisted = false;
1246
+		if ($code_substring_for_whitelist !== null) {
1247
+			$whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false;
1248
+		}
1249
+		if (! $whitelisted && $line_item->is_line_item()) {
1250
+			$line_item->set_is_taxable($taxable);
1251
+		}
1252
+		foreach ($line_item->children() as $child_line_item) {
1253
+			EEH_Line_Item::set_line_items_taxable(
1254
+				$child_line_item,
1255
+				$taxable,
1256
+				$code_substring_for_whitelist
1257
+			);
1258
+		}
1259
+	}
1260
+
1261
+
1262
+	/**
1263
+	 * Gets all descendants that are event subtotals
1264
+	 *
1265
+	 * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1266
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1267
+	 * @return EE_Line_Item[]
1268
+	 * @throws EE_Error
1269
+	 */
1270
+	public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1271
+	{
1272
+		return self::get_subtotals_of_object_type($parent_line_item, EEM_Line_Item::OBJ_TYPE_EVENT);
1273
+	}
1274
+
1275
+
1276
+	/**
1277
+	 * Gets all descendants subtotals that match the supplied object type
1278
+	 *
1279
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1280
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1281
+	 * @param string       $obj_type
1282
+	 * @return EE_Line_Item[]
1283
+	 * @throws EE_Error
1284
+	 */
1285
+	public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1286
+	{
1287
+		return self::_get_descendants_by_type_and_object_type(
1288
+			$parent_line_item,
1289
+			EEM_Line_Item::type_sub_total,
1290
+			$obj_type
1291
+		);
1292
+	}
1293
+
1294
+
1295
+	/**
1296
+	 * Gets all descendants that are tickets
1297
+	 *
1298
+	 * @uses  EEH_Line_Item::get_line_items_of_object_type()
1299
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1300
+	 * @return EE_Line_Item[]
1301
+	 * @throws EE_Error
1302
+	 */
1303
+	public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1304
+	{
1305
+		return self::get_line_items_of_object_type(
1306
+			$parent_line_item,
1307
+			EEM_Line_Item::OBJ_TYPE_TICKET
1308
+		);
1309
+	}
1310
+
1311
+
1312
+	/**
1313
+	 * Gets all descendants subtotals that match the supplied object type
1314
+	 *
1315
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1316
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1317
+	 * @param string       $obj_type
1318
+	 * @return EE_Line_Item[]
1319
+	 * @throws EE_Error
1320
+	 */
1321
+	public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1322
+	{
1323
+		return self::_get_descendants_by_type_and_object_type(
1324
+			$parent_line_item,
1325
+			EEM_Line_Item::type_line_item,
1326
+			$obj_type
1327
+		);
1328
+	}
1329
+
1330
+
1331
+	/**
1332
+	 * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1333
+	 *
1334
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1335
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1336
+	 * @return EE_Line_Item[]
1337
+	 * @throws EE_Error
1338
+	 */
1339
+	public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1340
+	{
1341
+		return EEH_Line_Item::get_descendants_of_type(
1342
+			$parent_line_item,
1343
+			EEM_Line_Item::type_tax
1344
+		);
1345
+	}
1346
+
1347
+
1348
+	/**
1349
+	 * Gets all the real items purchased which are children of this item
1350
+	 *
1351
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1352
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1353
+	 * @return EE_Line_Item[]
1354
+	 * @throws EE_Error
1355
+	 */
1356
+	public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1357
+	{
1358
+		return EEH_Line_Item::get_descendants_of_type(
1359
+			$parent_line_item,
1360
+			EEM_Line_Item::type_line_item
1361
+		);
1362
+	}
1363
+
1364
+
1365
+	/**
1366
+	 * Gets all descendants of supplied line item that match the supplied line item type
1367
+	 *
1368
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1369
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1370
+	 * @param string       $line_item_type   one of the EEM_Line_Item constants
1371
+	 * @return EE_Line_Item[]
1372
+	 * @throws EE_Error
1373
+	 */
1374
+	public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1375
+	{
1376
+		return self::_get_descendants_by_type_and_object_type(
1377
+			$parent_line_item,
1378
+			$line_item_type,
1379
+			null
1380
+		);
1381
+	}
1382
+
1383
+
1384
+	/**
1385
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1386
+	 * as well
1387
+	 *
1388
+	 * @param EE_Line_Item  $parent_line_item - the line item to find descendants of
1389
+	 * @param string        $line_item_type   one of the EEM_Line_Item constants
1390
+	 * @param string | NULL $obj_type         object model class name (minus prefix) or NULL to ignore object type when
1391
+	 *                                        searching
1392
+	 * @return EE_Line_Item[]
1393
+	 * @throws EE_Error
1394
+	 */
1395
+	protected static function _get_descendants_by_type_and_object_type(
1396
+		EE_Line_Item $parent_line_item,
1397
+		$line_item_type,
1398
+		$obj_type = null
1399
+	) {
1400
+		$objects = array();
1401
+		foreach ($parent_line_item->children() as $child_line_item) {
1402
+			if ($child_line_item instanceof EE_Line_Item) {
1403
+				if (
1404
+					$child_line_item->type() === $line_item_type
1405
+					&& (
1406
+						$child_line_item->OBJ_type() === $obj_type || $obj_type === null
1407
+					)
1408
+				) {
1409
+					$objects[] = $child_line_item;
1410
+				} else {
1411
+					// go-through-all-its children looking for more matches
1412
+					$objects = array_merge(
1413
+						$objects,
1414
+						self::_get_descendants_by_type_and_object_type(
1415
+							$child_line_item,
1416
+							$line_item_type,
1417
+							$obj_type
1418
+						)
1419
+					);
1420
+				}
1421
+			}
1422
+		}
1423
+		return $objects;
1424
+	}
1425
+
1426
+
1427
+	/**
1428
+	 * Gets all descendants subtotals that match the supplied object type
1429
+	 *
1430
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1431
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1432
+	 * @param string       $OBJ_type         object type (like Event)
1433
+	 * @param array        $OBJ_IDs          array of OBJ_IDs
1434
+	 * @return EE_Line_Item[]
1435
+	 * @throws EE_Error
1436
+	 */
1437
+	public static function get_line_items_by_object_type_and_IDs(
1438
+		EE_Line_Item $parent_line_item,
1439
+		$OBJ_type = '',
1440
+		$OBJ_IDs = array()
1441
+	) {
1442
+		return self::_get_descendants_by_object_type_and_object_ID(
1443
+			$parent_line_item,
1444
+			$OBJ_type,
1445
+			$OBJ_IDs
1446
+		);
1447
+	}
1448
+
1449
+
1450
+	/**
1451
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1452
+	 * as well
1453
+	 *
1454
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1455
+	 * @param string       $OBJ_type         object type (like Event)
1456
+	 * @param array        $OBJ_IDs          array of OBJ_IDs
1457
+	 * @return EE_Line_Item[]
1458
+	 * @throws EE_Error
1459
+	 */
1460
+	protected static function _get_descendants_by_object_type_and_object_ID(
1461
+		EE_Line_Item $parent_line_item,
1462
+		$OBJ_type,
1463
+		$OBJ_IDs
1464
+	) {
1465
+		$objects = array();
1466
+		foreach ($parent_line_item->children() as $child_line_item) {
1467
+			if ($child_line_item instanceof EE_Line_Item) {
1468
+				if (
1469
+					$child_line_item->OBJ_type() === $OBJ_type
1470
+					&& is_array($OBJ_IDs)
1471
+					&& in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1472
+				) {
1473
+					$objects[] = $child_line_item;
1474
+				} else {
1475
+					// go-through-all-its children looking for more matches
1476
+					$objects = array_merge(
1477
+						$objects,
1478
+						self::_get_descendants_by_object_type_and_object_ID(
1479
+							$child_line_item,
1480
+							$OBJ_type,
1481
+							$OBJ_IDs
1482
+						)
1483
+					);
1484
+				}
1485
+			}
1486
+		}
1487
+		return $objects;
1488
+	}
1489
+
1490
+
1491
+	/**
1492
+	 * Uses a breadth-first-search in order to find the nearest descendant of
1493
+	 * the specified type and returns it, else NULL
1494
+	 *
1495
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1496
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1497
+	 * @param string       $type             like one of the EEM_Line_Item::type_*
1498
+	 * @return EE_Line_Item
1499
+	 * @throws EE_Error
1500
+	 * @throws InvalidArgumentException
1501
+	 * @throws InvalidDataTypeException
1502
+	 * @throws InvalidInterfaceException
1503
+	 * @throws ReflectionException
1504
+	 */
1505
+	public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1506
+	{
1507
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1508
+	}
1509
+
1510
+
1511
+	/**
1512
+	 * Uses a breadth-first-search in order to find the nearest descendant
1513
+	 * having the specified LIN_code and returns it, else NULL
1514
+	 *
1515
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1516
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1517
+	 * @param string       $code             any value used for LIN_code
1518
+	 * @return EE_Line_Item
1519
+	 * @throws EE_Error
1520
+	 * @throws InvalidArgumentException
1521
+	 * @throws InvalidDataTypeException
1522
+	 * @throws InvalidInterfaceException
1523
+	 * @throws ReflectionException
1524
+	 */
1525
+	public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1526
+	{
1527
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1528
+	}
1529
+
1530
+
1531
+	/**
1532
+	 * Uses a breadth-first-search in order to find the nearest descendant
1533
+	 * having the specified LIN_code and returns it, else NULL
1534
+	 *
1535
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1536
+	 * @param string       $search_field     name of EE_Line_Item property
1537
+	 * @param string       $value            any value stored in $search_field
1538
+	 * @return EE_Line_Item
1539
+	 * @throws EE_Error
1540
+	 * @throws InvalidArgumentException
1541
+	 * @throws InvalidDataTypeException
1542
+	 * @throws InvalidInterfaceException
1543
+	 * @throws ReflectionException
1544
+	 */
1545
+	protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1546
+	{
1547
+		foreach ($parent_line_item->children() as $child) {
1548
+			if ($child->get($search_field) == $value) {
1549
+				return $child;
1550
+			}
1551
+		}
1552
+		foreach ($parent_line_item->children() as $child) {
1553
+			$descendant_found = self::_get_nearest_descendant(
1554
+				$child,
1555
+				$search_field,
1556
+				$value
1557
+			);
1558
+			if ($descendant_found) {
1559
+				return $descendant_found;
1560
+			}
1561
+		}
1562
+		return null;
1563
+	}
1564
+
1565
+
1566
+	/**
1567
+	 * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1568
+	 * else recursively walks up the line item tree until a parent of type total is found,
1569
+	 *
1570
+	 * @param EE_Line_Item $line_item
1571
+	 * @return EE_Line_Item
1572
+	 * @throws EE_Error
1573
+	 * @throws ReflectionException
1574
+	 */
1575
+	public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item): EE_Line_Item
1576
+	{
1577
+		if ($line_item->is_total()) {
1578
+			return $line_item;
1579
+		}
1580
+		if ($line_item->TXN_ID()) {
1581
+			$total_line_item = $line_item->transaction()->total_line_item(false);
1582
+			if ($total_line_item instanceof EE_Line_Item) {
1583
+				return $total_line_item;
1584
+			}
1585
+		} else {
1586
+			$line_item_parent = $line_item->parent();
1587
+			if ($line_item_parent instanceof EE_Line_Item) {
1588
+				if ($line_item_parent->is_total()) {
1589
+					return $line_item_parent;
1590
+				}
1591
+				return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1592
+			}
1593
+		}
1594
+		throw new EE_Error(
1595
+			sprintf(
1596
+				esc_html__(
1597
+					'A valid grand total for line item %1$d was not found.',
1598
+					'event_espresso'
1599
+				),
1600
+				$line_item->ID()
1601
+			)
1602
+		);
1603
+	}
1604
+
1605
+
1606
+	/**
1607
+	 * Prints out a representation of the line item tree
1608
+	 *
1609
+	 * @param EE_Line_Item $line_item
1610
+	 * @param int          $indentation
1611
+	 * @return void
1612
+	 * @throws EE_Error
1613
+	 */
1614
+	public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1615
+	{
1616
+		$new_line = defined('EE_TESTS_DIR') ? "\n" : '<br />';
1617
+		echo $new_line;
1618
+		if (! $indentation) {
1619
+			echo $new_line;
1620
+		}
1621
+		echo str_repeat('. ', $indentation);
1622
+		$breakdown = '';
1623
+		if ($line_item->is_line_item() || $line_item->is_sub_line_item() || $line_item->isSubTax()) {
1624
+			if ($line_item->is_percent()) {
1625
+				$breakdown = "{$line_item->percent()}%";
1626
+			} else {
1627
+				$breakdown = "\${$line_item->unit_price()} x {$line_item->quantity()}";
1628
+			}
1629
+		}
1630
+		echo wp_kses($line_item->name(), AllowedTags::getAllowedTags());
1631
+		echo " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : ";
1632
+		echo "\${$line_item->total()}";
1633
+		if ($breakdown) {
1634
+			echo " ( {$breakdown} )";
1635
+		}
1636
+		if ($line_item->is_taxable()) {
1637
+			echo '  * taxable';
1638
+		}
1639
+		if ($line_item->children()) {
1640
+			foreach ($line_item->children() as $child) {
1641
+				self::visualize($child, $indentation + 1);
1642
+			}
1643
+		}
1644
+		if (! $indentation) {
1645
+			echo $new_line . $new_line;
1646
+		}
1647
+	}
1648
+
1649
+
1650
+	/**
1651
+	 * Calculates the registration's final price, taking into account that they
1652
+	 * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1653
+	 * and receive a portion of any transaction-wide discounts.
1654
+	 * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1655
+	 * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1656
+	 * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1657
+	 * and brent's final price should be $5.50.
1658
+	 * In order to do this, we basically need to traverse the line item tree calculating
1659
+	 * the running totals (just as if we were recalculating the total), but when we identify
1660
+	 * regular line items, we need to keep track of their share of the grand total.
1661
+	 * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1662
+	 * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1663
+	 * when there are non-taxable items; otherwise they would be the same)
1664
+	 *
1665
+	 * @param EE_Line_Item $line_item
1666
+	 * @param array        $billable_ticket_quantities  array of EE_Ticket IDs and their corresponding quantity that
1667
+	 *                                                  can be included in price calculations at this moment
1668
+	 * @return array        keys are line items for tickets IDs and values are their share of the running total,
1669
+	 *                                                  plus the key 'total', and 'taxable' which also has keys of all
1670
+	 *                                                  the ticket IDs.
1671
+	 *                                                  Eg array(
1672
+	 *                                                      12 => 4.3
1673
+	 *                                                      23 => 8.0
1674
+	 *                                                      'total' => 16.6,
1675
+	 *                                                      'taxable' => array(
1676
+	 *                                                          12 => 10,
1677
+	 *                                                          23 => 4
1678
+	 *                                                      ).
1679
+	 *                                                  So to find which registrations have which final price, we need
1680
+	 *                                                  to find which line item is theirs, which can be done with
1681
+	 *                                                  `EEM_Line_Item::instance()->get_line_item_for_registration(
1682
+	 *                                                  $registration );`
1683
+	 * @throws EE_Error
1684
+	 * @throws InvalidArgumentException
1685
+	 * @throws InvalidDataTypeException
1686
+	 * @throws InvalidInterfaceException
1687
+	 * @throws ReflectionException
1688
+	 */
1689
+	public static function calculate_reg_final_prices_per_line_item(
1690
+		EE_Line_Item $line_item,
1691
+		$billable_ticket_quantities = array()
1692
+	) {
1693
+		$running_totals = [
1694
+			'total'   => 0,
1695
+			'taxable' => ['total' => 0]
1696
+		];
1697
+		foreach ($line_item->children() as $child_line_item) {
1698
+			switch ($child_line_item->type()) {
1699
+				case EEM_Line_Item::type_sub_total:
1700
+					$running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1701
+						$child_line_item,
1702
+						$billable_ticket_quantities
1703
+					);
1704
+					// combine arrays but preserve numeric keys
1705
+					$running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1706
+					$running_totals['total'] += $running_totals_from_subtotal['total'];
1707
+					$running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1708
+					break;
1709
+
1710
+				case EEM_Line_Item::type_tax_sub_total:
1711
+					// find how much the taxes percentage is
1712
+					if ($child_line_item->percent() !== 0) {
1713
+						$tax_percent_decimal = $child_line_item->percent() / 100;
1714
+					} else {
1715
+						$tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1716
+					}
1717
+					// and apply to all the taxable totals, and add to the pretax totals
1718
+					foreach ($running_totals as $line_item_id => $this_running_total) {
1719
+						// "total" and "taxable" array key is an exception
1720
+						if ($line_item_id === 'taxable') {
1721
+							continue;
1722
+						}
1723
+						$taxable_total = $running_totals['taxable'][ $line_item_id ];
1724
+						$running_totals[ $line_item_id ] += ($taxable_total * $tax_percent_decimal);
1725
+					}
1726
+					break;
1727
+
1728
+				case EEM_Line_Item::type_line_item:
1729
+					// ticket line items or ????
1730
+					if ($child_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
1731
+						// kk it's a ticket
1732
+						if (isset($running_totals[ $child_line_item->ID() ])) {
1733
+							// huh? that shouldn't happen.
1734
+							$running_totals['total'] += $child_line_item->total();
1735
+						} else {
1736
+							// its not in our running totals yet. great.
1737
+							if ($child_line_item->is_taxable()) {
1738
+								$taxable_amount = $child_line_item->unit_price();
1739
+							} else {
1740
+								$taxable_amount = 0;
1741
+							}
1742
+							// are we only calculating totals for some tickets?
1743
+							if (isset($billable_ticket_quantities[ $child_line_item->OBJ_ID() ])) {
1744
+								$quantity = $billable_ticket_quantities[ $child_line_item->OBJ_ID() ];
1745
+								$running_totals[ $child_line_item->ID() ] = $quantity
1746
+									? $child_line_item->unit_price()
1747
+									: 0;
1748
+								$running_totals['taxable'][ $child_line_item->ID() ] = $quantity
1749
+									? $taxable_amount
1750
+									: 0;
1751
+							} else {
1752
+								$quantity = $child_line_item->quantity();
1753
+								$running_totals[ $child_line_item->ID() ] = $child_line_item->unit_price();
1754
+								$running_totals['taxable'][ $child_line_item->ID() ] = $taxable_amount;
1755
+							}
1756
+							$running_totals['taxable']['total'] += $taxable_amount * $quantity;
1757
+							$running_totals['total'] += $child_line_item->unit_price() * $quantity;
1758
+						}
1759
+					} else {
1760
+						// it's some other type of item added to the cart
1761
+						// it should affect the running totals
1762
+						// basically we want to convert it into a PERCENT modifier. Because
1763
+						// more clearly affect all registration's final price equally
1764
+						$line_items_percent_of_running_total = $running_totals['total'] > 0
1765
+							? ($child_line_item->total() / $running_totals['total']) + 1
1766
+							: 1;
1767
+						foreach ($running_totals as $line_item_id => $this_running_total) {
1768
+							// the "taxable" array key is an exception
1769
+							if ($line_item_id === 'taxable') {
1770
+								continue;
1771
+							}
1772
+							// update the running totals
1773
+							// yes this actually even works for the running grand total!
1774
+							$running_totals[ $line_item_id ] =
1775
+								$line_items_percent_of_running_total * $this_running_total;
1776
+
1777
+							if ($child_line_item->is_taxable()) {
1778
+								$running_totals['taxable'][ $line_item_id ] =
1779
+									$line_items_percent_of_running_total * $running_totals['taxable'][ $line_item_id ];
1780
+							}
1781
+						}
1782
+					}
1783
+					break;
1784
+			}
1785
+		}
1786
+		return $running_totals;
1787
+	}
1788
+
1789
+
1790
+	/**
1791
+	 * @param EE_Line_Item $total_line_item
1792
+	 * @param EE_Line_Item $ticket_line_item
1793
+	 * @return float | null
1794
+	 * @throws EE_Error
1795
+	 * @throws InvalidArgumentException
1796
+	 * @throws InvalidDataTypeException
1797
+	 * @throws InvalidInterfaceException
1798
+	 * @throws OutOfRangeException
1799
+	 * @throws ReflectionException
1800
+	 */
1801
+	public static function calculate_final_price_for_ticket_line_item(
1802
+		EE_Line_Item $total_line_item,
1803
+		EE_Line_Item $ticket_line_item
1804
+	) {
1805
+		static $final_prices_per_ticket_line_item = array();
1806
+		if (empty($final_prices_per_ticket_line_item) || empty($final_prices_per_ticket_line_item[ $total_line_item->ID() ])) {
1807
+			$final_prices_per_ticket_line_item[ $total_line_item->ID() ] = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1808
+				$total_line_item
1809
+			);
1810
+		}
1811
+		// ok now find this new registration's final price
1812
+		if (isset($final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ])) {
1813
+			return $final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ];
1814
+		}
1815
+		$message = sprintf(
1816
+			esc_html__(
1817
+				'The final price for the ticket line item (ID:%1$d) on the total line item (ID:%2$d) could not be calculated.',
1818
+				'event_espresso'
1819
+			),
1820
+			$ticket_line_item->ID(),
1821
+			$total_line_item->ID()
1822
+		);
1823
+		if (WP_DEBUG) {
1824
+			$message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1825
+			throw new OutOfRangeException($message);
1826
+		}
1827
+		EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1828
+		return null;
1829
+	}
1830
+
1831
+
1832
+	/**
1833
+	 * Creates a duplicate of the line item tree, except only includes billable items
1834
+	 * and the portion of line items attributed to billable things
1835
+	 *
1836
+	 * @param EE_Line_Item      $line_item
1837
+	 * @param EE_Registration[] $registrations
1838
+	 * @return EE_Line_Item
1839
+	 * @throws EE_Error
1840
+	 * @throws InvalidArgumentException
1841
+	 * @throws InvalidDataTypeException
1842
+	 * @throws InvalidInterfaceException
1843
+	 * @throws ReflectionException
1844
+	 */
1845
+	public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1846
+	{
1847
+		$copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1848
+		foreach ($line_item->children() as $child_li) {
1849
+			$copy_li->add_child_line_item(
1850
+				EEH_Line_Item::billable_line_item_tree($child_li, $registrations)
1851
+			);
1852
+		}
1853
+		// if this is the grand total line item, make sure the totals all add up
1854
+		// (we could have duplicated this logic AS we copied the line items, but
1855
+		// it seems DRYer this way)
1856
+		if ($copy_li->type() === EEM_Line_Item::type_total) {
1857
+			$copy_li->recalculate_total_including_taxes();
1858
+		}
1859
+		return $copy_li;
1860
+	}
1861
+
1862
+
1863
+	/**
1864
+	 * Creates a new, unsaved line item from $line_item that factors in the
1865
+	 * number of billable registrations on $registrations.
1866
+	 *
1867
+	 * @param EE_Line_Item      $line_item
1868
+	 * @param EE_Registration[] $registrations
1869
+	 * @return EE_Line_Item
1870
+	 * @throws EE_Error
1871
+	 * @throws InvalidArgumentException
1872
+	 * @throws InvalidDataTypeException
1873
+	 * @throws InvalidInterfaceException
1874
+	 * @throws ReflectionException
1875
+	 */
1876
+	public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1877
+	{
1878
+		$new_li_fields = $line_item->model_field_array();
1879
+		if (
1880
+			$line_item->type() === EEM_Line_Item::type_line_item &&
1881
+			$line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1882
+		) {
1883
+			$count = 0;
1884
+			foreach ($registrations as $registration) {
1885
+				if (
1886
+					$line_item->OBJ_ID() === $registration->ticket_ID() &&
1887
+					in_array(
1888
+						$registration->status_ID(),
1889
+						EEM_Registration::reg_statuses_that_allow_payment(),
1890
+						true
1891
+					)
1892
+				) {
1893
+					$count++;
1894
+				}
1895
+			}
1896
+			$new_li_fields['LIN_quantity'] = $count;
1897
+		}
1898
+		// don't set the total. We'll leave that up to the code that calculates it
1899
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1900
+		return EE_Line_Item::new_instance($new_li_fields);
1901
+	}
1902
+
1903
+
1904
+	/**
1905
+	 * Returns a modified line item tree where all the subtotals which have a total of 0
1906
+	 * are removed, and line items with a quantity of 0
1907
+	 *
1908
+	 * @param EE_Line_Item $line_item |null
1909
+	 * @return EE_Line_Item|null
1910
+	 * @throws EE_Error
1911
+	 * @throws InvalidArgumentException
1912
+	 * @throws InvalidDataTypeException
1913
+	 * @throws InvalidInterfaceException
1914
+	 * @throws ReflectionException
1915
+	 */
1916
+	public static function non_empty_line_items(EE_Line_Item $line_item)
1917
+	{
1918
+		$copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1919
+		if ($copied_li === null) {
1920
+			return null;
1921
+		}
1922
+		// if this is an event subtotal, we want to only include it if it
1923
+		// has a non-zero total and at least one ticket line item child
1924
+		$ticket_children = 0;
1925
+		foreach ($line_item->children() as $child_li) {
1926
+			$child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1927
+			if ($child_li_copy !== null) {
1928
+				$copied_li->add_child_line_item($child_li_copy);
1929
+				if (
1930
+					$child_li_copy->type() === EEM_Line_Item::type_line_item &&
1931
+					$child_li_copy->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1932
+				) {
1933
+					$ticket_children++;
1934
+				}
1935
+			}
1936
+		}
1937
+		// if this is an event subtotal with NO ticket children
1938
+		// we basically want to ignore it
1939
+		if (
1940
+			$ticket_children === 0
1941
+			&& $line_item->type() === EEM_Line_Item::type_sub_total
1942
+			&& $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
1943
+			&& $line_item->total() === 0
1944
+		) {
1945
+			return null;
1946
+		}
1947
+		return $copied_li;
1948
+	}
1949
+
1950
+
1951
+	/**
1952
+	 * Creates a new, unsaved line item, but if it's a ticket line item
1953
+	 * with a total of 0, or a subtotal of 0, returns null instead
1954
+	 *
1955
+	 * @param EE_Line_Item $line_item
1956
+	 * @return EE_Line_Item
1957
+	 * @throws EE_Error
1958
+	 * @throws InvalidArgumentException
1959
+	 * @throws InvalidDataTypeException
1960
+	 * @throws InvalidInterfaceException
1961
+	 * @throws ReflectionException
1962
+	 */
1963
+	public static function non_empty_line_item(EE_Line_Item $line_item)
1964
+	{
1965
+		if (
1966
+			$line_item->type() === EEM_Line_Item::type_line_item
1967
+			&& $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1968
+			&& $line_item->quantity() === 0
1969
+		) {
1970
+			return null;
1971
+		}
1972
+		$new_li_fields = $line_item->model_field_array();
1973
+		// don't set the total. We'll leave that up to the code that calculates it
1974
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1975
+		return EE_Line_Item::new_instance($new_li_fields);
1976
+	}
1977
+
1978
+
1979
+	/**
1980
+	 * Cycles through all of the ticket line items for the supplied total line item
1981
+	 * and ensures that the line item's "is_taxable" field matches that of its corresponding ticket
1982
+	 *
1983
+	 * @param EE_Line_Item $total_line_item
1984
+	 * @since 4.9.79.p
1985
+	 * @throws EE_Error
1986
+	 * @throws InvalidArgumentException
1987
+	 * @throws InvalidDataTypeException
1988
+	 * @throws InvalidInterfaceException
1989
+	 * @throws ReflectionException
1990
+	 */
1991
+	public static function resetIsTaxableForTickets(EE_Line_Item $total_line_item)
1992
+	{
1993
+		$ticket_line_items = self::get_ticket_line_items($total_line_item);
1994
+		foreach ($ticket_line_items as $ticket_line_item) {
1995
+			if (
1996
+				$ticket_line_item instanceof EE_Line_Item
1997
+				&& $ticket_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1998
+			) {
1999
+				$ticket = $ticket_line_item->ticket();
2000
+				if ($ticket instanceof EE_Ticket && $ticket->taxable() !== $ticket_line_item->is_taxable()) {
2001
+					$ticket_line_item->set_is_taxable($ticket->taxable());
2002
+					$ticket_line_item->save();
2003
+				}
2004
+			}
2005
+		}
2006
+	}
2007
+
2008
+
2009
+	/**
2010
+	 * @return EE_Line_Item[]
2011
+	 * @throws EE_Error
2012
+	 * @throws ReflectionException
2013
+	 * @since   $VID:$
2014
+	 */
2015
+	private static function getGlobalTaxes(): array
2016
+	{
2017
+		if (EEH_Line_Item::$global_taxes === null) {
2018
+
2019
+			/** @type EEM_Price $EEM_Price */
2020
+			$EEM_Price = EE_Registry::instance()->load_model('Price');
2021
+			// get array of taxes via Price Model
2022
+			EEH_Line_Item::$global_taxes = $EEM_Price->get_all_prices_that_are_taxes();
2023
+			ksort(EEH_Line_Item::$global_taxes);
2024
+		}
2025
+		return EEH_Line_Item::$global_taxes;
2026
+	}
2027
+
2028
+
2029
+
2030
+	/**************************************** @DEPRECATED METHODS *************************************** */
2031
+	/**
2032
+	 * @deprecated
2033
+	 * @param EE_Line_Item $total_line_item
2034
+	 * @return EE_Line_Item
2035
+	 * @throws EE_Error
2036
+	 * @throws InvalidArgumentException
2037
+	 * @throws InvalidDataTypeException
2038
+	 * @throws InvalidInterfaceException
2039
+	 * @throws ReflectionException
2040
+	 */
2041
+	public static function get_items_subtotal(EE_Line_Item $total_line_item)
2042
+	{
2043
+		EE_Error::doing_it_wrong(
2044
+			'EEH_Line_Item::get_items_subtotal()',
2045
+			sprintf(
2046
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2047
+				'EEH_Line_Item::get_pre_tax_subtotal()'
2048
+			),
2049
+			'4.6.0'
2050
+		);
2051
+		return self::get_pre_tax_subtotal($total_line_item);
2052
+	}
2053
+
2054
+
2055
+	/**
2056
+	 * @deprecated
2057
+	 * @param EE_Transaction $transaction
2058
+	 * @return EE_Line_Item
2059
+	 * @throws EE_Error
2060
+	 * @throws InvalidArgumentException
2061
+	 * @throws InvalidDataTypeException
2062
+	 * @throws InvalidInterfaceException
2063
+	 * @throws ReflectionException
2064
+	 */
2065
+	public static function create_default_total_line_item($transaction = null)
2066
+	{
2067
+		EE_Error::doing_it_wrong(
2068
+			'EEH_Line_Item::create_default_total_line_item()',
2069
+			sprintf(
2070
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2071
+				'EEH_Line_Item::create_total_line_item()'
2072
+			),
2073
+			'4.6.0'
2074
+		);
2075
+		return self::create_total_line_item($transaction);
2076
+	}
2077
+
2078
+
2079
+	/**
2080
+	 * @deprecated
2081
+	 * @param EE_Line_Item   $total_line_item
2082
+	 * @param EE_Transaction $transaction
2083
+	 * @return EE_Line_Item
2084
+	 * @throws EE_Error
2085
+	 * @throws InvalidArgumentException
2086
+	 * @throws InvalidDataTypeException
2087
+	 * @throws InvalidInterfaceException
2088
+	 * @throws ReflectionException
2089
+	 */
2090
+	public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2091
+	{
2092
+		EE_Error::doing_it_wrong(
2093
+			'EEH_Line_Item::create_default_tickets_subtotal()',
2094
+			sprintf(
2095
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2096
+				'EEH_Line_Item::create_pre_tax_subtotal()'
2097
+			),
2098
+			'4.6.0'
2099
+		);
2100
+		return self::create_pre_tax_subtotal($total_line_item, $transaction);
2101
+	}
2102
+
2103
+
2104
+	/**
2105
+	 * @deprecated
2106
+	 * @param EE_Line_Item   $total_line_item
2107
+	 * @param EE_Transaction $transaction
2108
+	 * @return EE_Line_Item
2109
+	 * @throws EE_Error
2110
+	 * @throws InvalidArgumentException
2111
+	 * @throws InvalidDataTypeException
2112
+	 * @throws InvalidInterfaceException
2113
+	 * @throws ReflectionException
2114
+	 */
2115
+	public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2116
+	{
2117
+		EE_Error::doing_it_wrong(
2118
+			'EEH_Line_Item::create_default_taxes_subtotal()',
2119
+			sprintf(
2120
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2121
+				'EEH_Line_Item::create_taxes_subtotal()'
2122
+			),
2123
+			'4.6.0'
2124
+		);
2125
+		return self::create_taxes_subtotal($total_line_item, $transaction);
2126
+	}
2127
+
2128
+
2129
+	/**
2130
+	 * @deprecated
2131
+	 * @param EE_Line_Item   $total_line_item
2132
+	 * @param EE_Transaction $transaction
2133
+	 * @return EE_Line_Item
2134
+	 * @throws EE_Error
2135
+	 * @throws InvalidArgumentException
2136
+	 * @throws InvalidDataTypeException
2137
+	 * @throws InvalidInterfaceException
2138
+	 * @throws ReflectionException
2139
+	 */
2140
+	public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2141
+	{
2142
+		EE_Error::doing_it_wrong(
2143
+			'EEH_Line_Item::create_default_event_subtotal()',
2144
+			sprintf(
2145
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2146
+				'EEH_Line_Item::create_event_subtotal()'
2147
+			),
2148
+			'4.6.0'
2149
+		);
2150
+		return self::create_event_subtotal($total_line_item, $transaction);
2151
+	}
2152 2152
 }
Please login to merge, or discard this patch.
core/admin/EE_Admin_Page_Menu_Map.core.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -12,49 +12,49 @@
 block discarded – undo
12 12
  */
13 13
 abstract class EE_Admin_Page_Menu_Map extends AdminMenuItem
14 14
 {
15
-    const NONE                   = 0;
16
-
17
-    const BLOG_ADMIN_ONLY        = 1;
18
-
19
-    const BLOG_AND_NETWORK_ADMIN = 2;
20
-
21
-    const NETWORK_ADMIN_ONLY     = 3;
22
-
23
-
24
-    /**
25
-     * @return string
26
-     * @deprecated $VID:$
27
-     */
28
-    protected function _add_menu_page(): string
29
-    {
30
-        return $this->registerMenuItem();
31
-    }
32
-
33
-
34
-    /**
35
-     * @param boolean $network_admin whether this is being added to the network admin page or not
36
-     * @deprecated $VID:$
37
-     * @since  4.4.0
38
-     */
39
-    public function add_menu_page(bool $network_admin = false)
40
-    {
41
-        $this->registerAdminMenuItem($network_admin);
42
-    }
43
-
44
-
45
-    public function __get(string $property)
46
-    {
47
-        // converts a property name like 'menu_slug' into 'menuSlug'
48
-        $getter = lcfirst(ucwords($property, '_'));
49
-        return method_exists($this, $getter) ? $this->{$getter}() : null;
50
-    }
51
-
52
-    public function __set(string $property, $value)
53
-    {
54
-        // converts a property name like 'menu_slug' into 'setMenuSlug'
55
-        $setter = 'set' . ucwords($property, '_');
56
-        if (method_exists($this, $setter)) {
57
-            $this->{$setter}($value);
58
-        }
59
-    }
15
+	const NONE                   = 0;
16
+
17
+	const BLOG_ADMIN_ONLY        = 1;
18
+
19
+	const BLOG_AND_NETWORK_ADMIN = 2;
20
+
21
+	const NETWORK_ADMIN_ONLY     = 3;
22
+
23
+
24
+	/**
25
+	 * @return string
26
+	 * @deprecated $VID:$
27
+	 */
28
+	protected function _add_menu_page(): string
29
+	{
30
+		return $this->registerMenuItem();
31
+	}
32
+
33
+
34
+	/**
35
+	 * @param boolean $network_admin whether this is being added to the network admin page or not
36
+	 * @deprecated $VID:$
37
+	 * @since  4.4.0
38
+	 */
39
+	public function add_menu_page(bool $network_admin = false)
40
+	{
41
+		$this->registerAdminMenuItem($network_admin);
42
+	}
43
+
44
+
45
+	public function __get(string $property)
46
+	{
47
+		// converts a property name like 'menu_slug' into 'menuSlug'
48
+		$getter = lcfirst(ucwords($property, '_'));
49
+		return method_exists($this, $getter) ? $this->{$getter}() : null;
50
+	}
51
+
52
+	public function __set(string $property, $value)
53
+	{
54
+		// converts a property name like 'menu_slug' into 'setMenuSlug'
55
+		$setter = 'set' . ucwords($property, '_');
56
+		if (method_exists($this, $setter)) {
57
+			$this->{$setter}($value);
58
+		}
59
+	}
60 60
 }
Please login to merge, or discard this patch.
core/services/request/Request.php 1 patch
Indentation   +549 added lines, -549 removed lines patch added patch discarded remove patch
@@ -16,553 +16,553 @@
 block discarded – undo
16 16
  */
17 17
 class Request implements InterminableInterface, RequestInterface, ReservedInstanceInterface
18 18
 {
19
-    /**
20
-     * $_COOKIE parameters
21
-     *
22
-     * @var array
23
-     */
24
-    protected $cookies;
25
-
26
-    /**
27
-     * $_FILES parameters
28
-     *
29
-     * @var array
30
-     */
31
-    protected $files;
32
-
33
-    /**
34
-     * true if current user appears to be some kind of bot
35
-     *
36
-     * @var bool
37
-     */
38
-    protected $is_bot;
39
-
40
-    /**
41
-     * @var RequestParams
42
-     */
43
-    protected $request_params;
44
-
45
-    /**
46
-     * @var RequestTypeContextCheckerInterface
47
-     */
48
-    protected $request_type;
49
-
50
-    /**
51
-     * @var ServerParams
52
-     */
53
-    protected $server_params;
54
-
55
-
56
-    public function __construct(
57
-        RequestParams $request_params,
58
-        ServerParams $server_params,
59
-        array $cookies = [],
60
-        array $files = []
61
-    ) {
62
-        $this->cookies        = ! empty($cookies)
63
-            ? $cookies
64
-            : filter_input_array(INPUT_COOKIE, FILTER_UNSAFE_RAW);
65
-        $this->files          = ! empty($files) ? $files : $_FILES;
66
-        $this->request_params = $request_params;
67
-        $this->server_params  = $server_params;
68
-    }
69
-
70
-
71
-    /**
72
-     * @param RequestTypeContextCheckerInterface $type
73
-     */
74
-    public function setRequestTypeContextChecker(RequestTypeContextCheckerInterface $type)
75
-    {
76
-        $this->request_type = $type;
77
-    }
78
-
79
-
80
-    /**
81
-     * @return array
82
-     */
83
-    public function getParams()
84
-    {
85
-        return $this->request_params->getParams();
86
-    }
87
-
88
-
89
-    /**
90
-     * @return array
91
-     */
92
-    public function postParams()
93
-    {
94
-        return $this->request_params->postParams();
95
-    }
96
-
97
-
98
-    /**
99
-     * @return array
100
-     */
101
-    public function cookieParams()
102
-    {
103
-        return $this->cookies;
104
-    }
105
-
106
-
107
-    /**
108
-     * @return array
109
-     */
110
-    public function serverParams()
111
-    {
112
-        return $this->server_params->getAllServerParams();
113
-    }
114
-
115
-
116
-    /**
117
-     * @param string     $key
118
-     * @param mixed|null $default
119
-     * @return array|int|float|string
120
-     */
121
-    public function getServerParam($key, $default = null)
122
-    {
123
-        return $this->server_params->getServerParam($key, $default);
124
-    }
125
-
126
-
127
-    /**
128
-     * @param string                 $key
129
-     * @param array|int|float|string $value
130
-     * @param bool                   $set_global_too
131
-     * @return void
132
-     */
133
-    public function setServerParam(string $key, $value, bool $set_global_too = false)
134
-    {
135
-        $this->server_params->setServerParam($key, $value, $set_global_too);
136
-    }
137
-
138
-
139
-    /**
140
-     * @param string $key
141
-     * @return bool
142
-     */
143
-    public function serverParamIsSet($key)
144
-    {
145
-        return $this->server_params->serverParamIsSet($key);
146
-    }
147
-
148
-
149
-    /**
150
-     * @return array
151
-     */
152
-    public function filesParams()
153
-    {
154
-        return $this->files;
155
-    }
156
-
157
-
158
-    /**
159
-     * returns sanitized contents of $_REQUEST
160
-     *
161
-     * @return array
162
-     */
163
-    public function requestParams()
164
-    {
165
-        return $this->request_params->requestParams();
166
-    }
167
-
168
-
169
-    /**
170
-     * @param string     $key
171
-     * @param mixed|null $value
172
-     * @param bool       $override_ee
173
-     * @return void
174
-     */
175
-    public function setRequestParam($key, $value, $override_ee = false)
176
-    {
177
-        $this->request_params->setRequestParam($key, $value, $override_ee);
178
-    }
179
-
180
-
181
-    /**
182
-     * merges the incoming array of parameters into the existing request parameters
183
-     *
184
-     * @param array $request_params
185
-     * @return void
186
-     * @since   4.10.24.p
187
-     */
188
-    public function mergeRequestParams(array $request_params)
189
-    {
190
-        $this->request_params->mergeRequestParams($request_params);
191
-    }
192
-
193
-
194
-    /**
195
-     * returns sanitized value for a request param if the given key exists
196
-     *
197
-     * @param string     $key
198
-     * @param mixed|null $default
199
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
200
-     * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
201
-     * @param string     $delimiter for CSV type strings that should be returned as an array
202
-     * @return array|bool|float|int|string
203
-     */
204
-    public function getRequestParam($key, $default = null, $type = DataType::STRING, $is_array = false, $delimiter = '')
205
-    {
206
-        return $this->request_params->getRequestParam($key, $default, $type, $is_array, $delimiter);
207
-    }
208
-
209
-
210
-    /**
211
-     * check if param exists
212
-     *
213
-     * @param string $key
214
-     * @return bool
215
-     */
216
-    public function requestParamIsSet($key)
217
-    {
218
-        return $this->request_params->requestParamIsSet($key);
219
-    }
220
-
221
-
222
-    /**
223
-     * check if a request parameter exists whose key that matches the supplied wildcard pattern
224
-     * and return the sanitized value for the first match found
225
-     * wildcards can be either of the following:
226
-     *      ? to represent a single character of any type
227
-     *      * to represent one or more characters of any type
228
-     *
229
-     * @param string     $pattern
230
-     * @param mixed|null $default
231
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
232
-     * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
233
-     * @param string     $delimiter for CSV type strings that should be returned as an array
234
-     * @return array|bool|float|int|string
235
-     */
236
-    public function getMatch($pattern, $default = null, $type = DataType::STRING, $is_array = false, $delimiter = '')
237
-    {
238
-        return $this->request_params->getMatch($pattern, $default, $type, $is_array, $delimiter);
239
-    }
240
-
241
-
242
-    /**
243
-     * check if a request parameter exists whose key matches the supplied wildcard pattern
244
-     * wildcards can be either of the following:
245
-     *      ? to represent a single character of any type
246
-     *      * to represent one or more characters of any type
247
-     * returns true if a match is found or false if not
248
-     *
249
-     * @param string $pattern
250
-     * @return bool
251
-     */
252
-    public function matches($pattern)
253
-    {
254
-        return $this->request_params->matches($pattern);
255
-    }
256
-
257
-
258
-    /**
259
-     * remove param
260
-     *
261
-     * @param      $key
262
-     * @param bool $unset_from_global_too
263
-     */
264
-    public function unSetRequestParam($key, $unset_from_global_too = false)
265
-    {
266
-        $this->request_params->unSetRequestParam($key, $unset_from_global_too);
267
-    }
268
-
269
-
270
-    /**
271
-     * remove params
272
-     *
273
-     * @param array $keys
274
-     * @param bool  $unset_from_global_too
275
-     */
276
-    public function unSetRequestParams(array $keys, $unset_from_global_too = false)
277
-    {
278
-        $this->request_params->unSetRequestParams($keys, $unset_from_global_too);
279
-    }
280
-
281
-
282
-    /**
283
-     * @param string $key
284
-     * @param bool   $unset_from_global_too
285
-     * @return void
286
-     */
287
-    public function unSetServerParam(string $key, bool $unset_from_global_too = false)
288
-    {
289
-        $this->server_params->unSetServerParam($key, $unset_from_global_too);
290
-    }
291
-
292
-
293
-    /**
294
-     * @return string
295
-     */
296
-    public function ipAddress()
297
-    {
298
-        return $this->server_params->ipAddress();
299
-    }
300
-
301
-
302
-    /**
303
-     * Gets the request's literal URI. Related to `requestUriAfterSiteHomeUri`, see its description for a comparison.
304
-     *
305
-     * @param boolean $relativeToWpRoot    If home_url() is "http://mysite.com/wp/", and a request comes to
306
-     *                                     "http://mysite.com/wp/wp-json", setting $relativeToWpRoot=true will return
307
-     *                                     "/wp-json", whereas $relativeToWpRoot=false will return "/wp/wp-json/".
308
-     * @param boolean $remove_query_params whether or not to return the uri with all query params removed.
309
-     * @return string
310
-     */
311
-    public function requestUri($relativeToWpRoot = false, $remove_query_params = false)
312
-    {
313
-        return $this->server_params->requestUri($relativeToWpRoot);
314
-    }
315
-
316
-
317
-    /**
318
-     * @return string
319
-     */
320
-    public function userAgent()
321
-    {
322
-        return $this->server_params->userAgent();
323
-    }
324
-
325
-
326
-    /**
327
-     * @param string $user_agent
328
-     */
329
-    public function setUserAgent($user_agent = '')
330
-    {
331
-        $this->server_params->setUserAgent($user_agent);
332
-    }
333
-
334
-
335
-    /**
336
-     * @return bool
337
-     */
338
-    public function isBot()
339
-    {
340
-        return $this->is_bot;
341
-    }
342
-
343
-
344
-    /**
345
-     * @param bool $is_bot
346
-     */
347
-    public function setIsBot($is_bot)
348
-    {
349
-        $this->is_bot = filter_var($is_bot, FILTER_VALIDATE_BOOLEAN);
350
-    }
351
-
352
-
353
-    /**
354
-     * @return bool
355
-     */
356
-    public function isActivation()
357
-    {
358
-        return $this->request_type->isActivation();
359
-    }
360
-
361
-
362
-    /**
363
-     * @param $is_activation
364
-     * @return bool
365
-     */
366
-    public function setIsActivation($is_activation)
367
-    {
368
-        return $this->request_type->setIsActivation($is_activation);
369
-    }
370
-
371
-
372
-    /**
373
-     * @return bool
374
-     */
375
-    public function isAdmin()
376
-    {
377
-        return $this->request_type->isAdmin();
378
-    }
379
-
380
-
381
-    /**
382
-     * @return bool
383
-     */
384
-    public function isAdminAjax()
385
-    {
386
-        return $this->request_type->isAdminAjax();
387
-    }
388
-
389
-
390
-    /**
391
-     * @return bool
392
-     */
393
-    public function isAjax()
394
-    {
395
-        return $this->request_type->isAjax();
396
-    }
397
-
398
-
399
-    /**
400
-     * @return bool
401
-     */
402
-    public function isEeAjax()
403
-    {
404
-        return $this->request_type->isEeAjax();
405
-    }
406
-
407
-
408
-    /**
409
-     * @return bool
410
-     */
411
-    public function isOtherAjax()
412
-    {
413
-        return $this->request_type->isOtherAjax();
414
-    }
415
-
416
-
417
-    /**
418
-     * @return bool
419
-     */
420
-    public function isApi()
421
-    {
422
-        return $this->request_type->isApi();
423
-    }
424
-
425
-
426
-    /**
427
-     * @return bool
428
-     */
429
-    public function isCli()
430
-    {
431
-        return $this->request_type->isCli();
432
-    }
433
-
434
-
435
-    /**
436
-     * @return bool
437
-     */
438
-    public function isCron()
439
-    {
440
-        return $this->request_type->isCron();
441
-    }
442
-
443
-
444
-    /**
445
-     * @return bool
446
-     */
447
-    public function isFeed()
448
-    {
449
-        return $this->request_type->isFeed();
450
-    }
451
-
452
-
453
-    /**
454
-     * @return bool
455
-     */
456
-    public function isFrontend()
457
-    {
458
-        return $this->request_type->isFrontend();
459
-    }
460
-
461
-
462
-    /**
463
-     * @return bool
464
-     */
465
-    public function isFrontAjax()
466
-    {
467
-        return $this->request_type->isFrontAjax();
468
-    }
469
-
470
-
471
-    /**
472
-     * @return bool
473
-     */
474
-    public function isGQL()
475
-    {
476
-        return $this->request_type->isGQL();
477
-    }
478
-
479
-
480
-    /**
481
-     * @return bool
482
-     */
483
-    public function isIframe()
484
-    {
485
-        return $this->request_type->isIframe();
486
-    }
487
-
488
-
489
-    /**
490
-     * @return bool
491
-     */
492
-    public function isUnitTesting()
493
-    {
494
-        return $this->request_type->isUnitTesting();
495
-    }
496
-
497
-
498
-    /**
499
-     * @return bool
500
-     */
501
-    public function isWordPressApi()
502
-    {
503
-        return $this->request_type->isWordPressApi();
504
-    }
505
-
506
-
507
-    /**
508
-     * @return bool
509
-     */
510
-    public function isWordPressHeartbeat()
511
-    {
512
-        return $this->request_type->isWordPressHeartbeat();
513
-    }
514
-
515
-
516
-    /**
517
-     * @return bool
518
-     */
519
-    public function isWordPressScrape()
520
-    {
521
-        return $this->request_type->isWordPressScrape();
522
-    }
523
-
524
-
525
-    /**
526
-     * @return string
527
-     */
528
-    public function slug()
529
-    {
530
-        return $this->request_type->slug();
531
-    }
532
-
533
-
534
-    /**
535
-     * returns the path portion of the current request URI with both the WP Root (home_url()) and query params removed
536
-     *
537
-     * @return string
538
-     * @since   $VID:$
539
-     */
540
-    public function requestPath()
541
-    {
542
-        return $this->requestUri(true, true);
543
-    }
544
-
545
-
546
-    /**
547
-     * returns true if the last segment of the current request path (without params) matches the provided string
548
-     *
549
-     * @param string $uri_segment
550
-     * @return bool
551
-     * @since   $VID:$
552
-     */
553
-    public function currentPageIs($uri_segment)
554
-    {
555
-        $request_path = $this->requestPath();
556
-        $current_page = explode('/', $request_path);
557
-        return end($current_page) === $uri_segment;
558
-    }
559
-
560
-
561
-    /**
562
-     * @return RequestTypeContextCheckerInterface
563
-     */
564
-    public function getRequestType(): RequestTypeContextCheckerInterface
565
-    {
566
-        return $this->request_type;
567
-    }
19
+	/**
20
+	 * $_COOKIE parameters
21
+	 *
22
+	 * @var array
23
+	 */
24
+	protected $cookies;
25
+
26
+	/**
27
+	 * $_FILES parameters
28
+	 *
29
+	 * @var array
30
+	 */
31
+	protected $files;
32
+
33
+	/**
34
+	 * true if current user appears to be some kind of bot
35
+	 *
36
+	 * @var bool
37
+	 */
38
+	protected $is_bot;
39
+
40
+	/**
41
+	 * @var RequestParams
42
+	 */
43
+	protected $request_params;
44
+
45
+	/**
46
+	 * @var RequestTypeContextCheckerInterface
47
+	 */
48
+	protected $request_type;
49
+
50
+	/**
51
+	 * @var ServerParams
52
+	 */
53
+	protected $server_params;
54
+
55
+
56
+	public function __construct(
57
+		RequestParams $request_params,
58
+		ServerParams $server_params,
59
+		array $cookies = [],
60
+		array $files = []
61
+	) {
62
+		$this->cookies        = ! empty($cookies)
63
+			? $cookies
64
+			: filter_input_array(INPUT_COOKIE, FILTER_UNSAFE_RAW);
65
+		$this->files          = ! empty($files) ? $files : $_FILES;
66
+		$this->request_params = $request_params;
67
+		$this->server_params  = $server_params;
68
+	}
69
+
70
+
71
+	/**
72
+	 * @param RequestTypeContextCheckerInterface $type
73
+	 */
74
+	public function setRequestTypeContextChecker(RequestTypeContextCheckerInterface $type)
75
+	{
76
+		$this->request_type = $type;
77
+	}
78
+
79
+
80
+	/**
81
+	 * @return array
82
+	 */
83
+	public function getParams()
84
+	{
85
+		return $this->request_params->getParams();
86
+	}
87
+
88
+
89
+	/**
90
+	 * @return array
91
+	 */
92
+	public function postParams()
93
+	{
94
+		return $this->request_params->postParams();
95
+	}
96
+
97
+
98
+	/**
99
+	 * @return array
100
+	 */
101
+	public function cookieParams()
102
+	{
103
+		return $this->cookies;
104
+	}
105
+
106
+
107
+	/**
108
+	 * @return array
109
+	 */
110
+	public function serverParams()
111
+	{
112
+		return $this->server_params->getAllServerParams();
113
+	}
114
+
115
+
116
+	/**
117
+	 * @param string     $key
118
+	 * @param mixed|null $default
119
+	 * @return array|int|float|string
120
+	 */
121
+	public function getServerParam($key, $default = null)
122
+	{
123
+		return $this->server_params->getServerParam($key, $default);
124
+	}
125
+
126
+
127
+	/**
128
+	 * @param string                 $key
129
+	 * @param array|int|float|string $value
130
+	 * @param bool                   $set_global_too
131
+	 * @return void
132
+	 */
133
+	public function setServerParam(string $key, $value, bool $set_global_too = false)
134
+	{
135
+		$this->server_params->setServerParam($key, $value, $set_global_too);
136
+	}
137
+
138
+
139
+	/**
140
+	 * @param string $key
141
+	 * @return bool
142
+	 */
143
+	public function serverParamIsSet($key)
144
+	{
145
+		return $this->server_params->serverParamIsSet($key);
146
+	}
147
+
148
+
149
+	/**
150
+	 * @return array
151
+	 */
152
+	public function filesParams()
153
+	{
154
+		return $this->files;
155
+	}
156
+
157
+
158
+	/**
159
+	 * returns sanitized contents of $_REQUEST
160
+	 *
161
+	 * @return array
162
+	 */
163
+	public function requestParams()
164
+	{
165
+		return $this->request_params->requestParams();
166
+	}
167
+
168
+
169
+	/**
170
+	 * @param string     $key
171
+	 * @param mixed|null $value
172
+	 * @param bool       $override_ee
173
+	 * @return void
174
+	 */
175
+	public function setRequestParam($key, $value, $override_ee = false)
176
+	{
177
+		$this->request_params->setRequestParam($key, $value, $override_ee);
178
+	}
179
+
180
+
181
+	/**
182
+	 * merges the incoming array of parameters into the existing request parameters
183
+	 *
184
+	 * @param array $request_params
185
+	 * @return void
186
+	 * @since   4.10.24.p
187
+	 */
188
+	public function mergeRequestParams(array $request_params)
189
+	{
190
+		$this->request_params->mergeRequestParams($request_params);
191
+	}
192
+
193
+
194
+	/**
195
+	 * returns sanitized value for a request param if the given key exists
196
+	 *
197
+	 * @param string     $key
198
+	 * @param mixed|null $default
199
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
200
+	 * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
201
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
202
+	 * @return array|bool|float|int|string
203
+	 */
204
+	public function getRequestParam($key, $default = null, $type = DataType::STRING, $is_array = false, $delimiter = '')
205
+	{
206
+		return $this->request_params->getRequestParam($key, $default, $type, $is_array, $delimiter);
207
+	}
208
+
209
+
210
+	/**
211
+	 * check if param exists
212
+	 *
213
+	 * @param string $key
214
+	 * @return bool
215
+	 */
216
+	public function requestParamIsSet($key)
217
+	{
218
+		return $this->request_params->requestParamIsSet($key);
219
+	}
220
+
221
+
222
+	/**
223
+	 * check if a request parameter exists whose key that matches the supplied wildcard pattern
224
+	 * and return the sanitized value for the first match found
225
+	 * wildcards can be either of the following:
226
+	 *      ? to represent a single character of any type
227
+	 *      * to represent one or more characters of any type
228
+	 *
229
+	 * @param string     $pattern
230
+	 * @param mixed|null $default
231
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
232
+	 * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
233
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
234
+	 * @return array|bool|float|int|string
235
+	 */
236
+	public function getMatch($pattern, $default = null, $type = DataType::STRING, $is_array = false, $delimiter = '')
237
+	{
238
+		return $this->request_params->getMatch($pattern, $default, $type, $is_array, $delimiter);
239
+	}
240
+
241
+
242
+	/**
243
+	 * check if a request parameter exists whose key matches the supplied wildcard pattern
244
+	 * wildcards can be either of the following:
245
+	 *      ? to represent a single character of any type
246
+	 *      * to represent one or more characters of any type
247
+	 * returns true if a match is found or false if not
248
+	 *
249
+	 * @param string $pattern
250
+	 * @return bool
251
+	 */
252
+	public function matches($pattern)
253
+	{
254
+		return $this->request_params->matches($pattern);
255
+	}
256
+
257
+
258
+	/**
259
+	 * remove param
260
+	 *
261
+	 * @param      $key
262
+	 * @param bool $unset_from_global_too
263
+	 */
264
+	public function unSetRequestParam($key, $unset_from_global_too = false)
265
+	{
266
+		$this->request_params->unSetRequestParam($key, $unset_from_global_too);
267
+	}
268
+
269
+
270
+	/**
271
+	 * remove params
272
+	 *
273
+	 * @param array $keys
274
+	 * @param bool  $unset_from_global_too
275
+	 */
276
+	public function unSetRequestParams(array $keys, $unset_from_global_too = false)
277
+	{
278
+		$this->request_params->unSetRequestParams($keys, $unset_from_global_too);
279
+	}
280
+
281
+
282
+	/**
283
+	 * @param string $key
284
+	 * @param bool   $unset_from_global_too
285
+	 * @return void
286
+	 */
287
+	public function unSetServerParam(string $key, bool $unset_from_global_too = false)
288
+	{
289
+		$this->server_params->unSetServerParam($key, $unset_from_global_too);
290
+	}
291
+
292
+
293
+	/**
294
+	 * @return string
295
+	 */
296
+	public function ipAddress()
297
+	{
298
+		return $this->server_params->ipAddress();
299
+	}
300
+
301
+
302
+	/**
303
+	 * Gets the request's literal URI. Related to `requestUriAfterSiteHomeUri`, see its description for a comparison.
304
+	 *
305
+	 * @param boolean $relativeToWpRoot    If home_url() is "http://mysite.com/wp/", and a request comes to
306
+	 *                                     "http://mysite.com/wp/wp-json", setting $relativeToWpRoot=true will return
307
+	 *                                     "/wp-json", whereas $relativeToWpRoot=false will return "/wp/wp-json/".
308
+	 * @param boolean $remove_query_params whether or not to return the uri with all query params removed.
309
+	 * @return string
310
+	 */
311
+	public function requestUri($relativeToWpRoot = false, $remove_query_params = false)
312
+	{
313
+		return $this->server_params->requestUri($relativeToWpRoot);
314
+	}
315
+
316
+
317
+	/**
318
+	 * @return string
319
+	 */
320
+	public function userAgent()
321
+	{
322
+		return $this->server_params->userAgent();
323
+	}
324
+
325
+
326
+	/**
327
+	 * @param string $user_agent
328
+	 */
329
+	public function setUserAgent($user_agent = '')
330
+	{
331
+		$this->server_params->setUserAgent($user_agent);
332
+	}
333
+
334
+
335
+	/**
336
+	 * @return bool
337
+	 */
338
+	public function isBot()
339
+	{
340
+		return $this->is_bot;
341
+	}
342
+
343
+
344
+	/**
345
+	 * @param bool $is_bot
346
+	 */
347
+	public function setIsBot($is_bot)
348
+	{
349
+		$this->is_bot = filter_var($is_bot, FILTER_VALIDATE_BOOLEAN);
350
+	}
351
+
352
+
353
+	/**
354
+	 * @return bool
355
+	 */
356
+	public function isActivation()
357
+	{
358
+		return $this->request_type->isActivation();
359
+	}
360
+
361
+
362
+	/**
363
+	 * @param $is_activation
364
+	 * @return bool
365
+	 */
366
+	public function setIsActivation($is_activation)
367
+	{
368
+		return $this->request_type->setIsActivation($is_activation);
369
+	}
370
+
371
+
372
+	/**
373
+	 * @return bool
374
+	 */
375
+	public function isAdmin()
376
+	{
377
+		return $this->request_type->isAdmin();
378
+	}
379
+
380
+
381
+	/**
382
+	 * @return bool
383
+	 */
384
+	public function isAdminAjax()
385
+	{
386
+		return $this->request_type->isAdminAjax();
387
+	}
388
+
389
+
390
+	/**
391
+	 * @return bool
392
+	 */
393
+	public function isAjax()
394
+	{
395
+		return $this->request_type->isAjax();
396
+	}
397
+
398
+
399
+	/**
400
+	 * @return bool
401
+	 */
402
+	public function isEeAjax()
403
+	{
404
+		return $this->request_type->isEeAjax();
405
+	}
406
+
407
+
408
+	/**
409
+	 * @return bool
410
+	 */
411
+	public function isOtherAjax()
412
+	{
413
+		return $this->request_type->isOtherAjax();
414
+	}
415
+
416
+
417
+	/**
418
+	 * @return bool
419
+	 */
420
+	public function isApi()
421
+	{
422
+		return $this->request_type->isApi();
423
+	}
424
+
425
+
426
+	/**
427
+	 * @return bool
428
+	 */
429
+	public function isCli()
430
+	{
431
+		return $this->request_type->isCli();
432
+	}
433
+
434
+
435
+	/**
436
+	 * @return bool
437
+	 */
438
+	public function isCron()
439
+	{
440
+		return $this->request_type->isCron();
441
+	}
442
+
443
+
444
+	/**
445
+	 * @return bool
446
+	 */
447
+	public function isFeed()
448
+	{
449
+		return $this->request_type->isFeed();
450
+	}
451
+
452
+
453
+	/**
454
+	 * @return bool
455
+	 */
456
+	public function isFrontend()
457
+	{
458
+		return $this->request_type->isFrontend();
459
+	}
460
+
461
+
462
+	/**
463
+	 * @return bool
464
+	 */
465
+	public function isFrontAjax()
466
+	{
467
+		return $this->request_type->isFrontAjax();
468
+	}
469
+
470
+
471
+	/**
472
+	 * @return bool
473
+	 */
474
+	public function isGQL()
475
+	{
476
+		return $this->request_type->isGQL();
477
+	}
478
+
479
+
480
+	/**
481
+	 * @return bool
482
+	 */
483
+	public function isIframe()
484
+	{
485
+		return $this->request_type->isIframe();
486
+	}
487
+
488
+
489
+	/**
490
+	 * @return bool
491
+	 */
492
+	public function isUnitTesting()
493
+	{
494
+		return $this->request_type->isUnitTesting();
495
+	}
496
+
497
+
498
+	/**
499
+	 * @return bool
500
+	 */
501
+	public function isWordPressApi()
502
+	{
503
+		return $this->request_type->isWordPressApi();
504
+	}
505
+
506
+
507
+	/**
508
+	 * @return bool
509
+	 */
510
+	public function isWordPressHeartbeat()
511
+	{
512
+		return $this->request_type->isWordPressHeartbeat();
513
+	}
514
+
515
+
516
+	/**
517
+	 * @return bool
518
+	 */
519
+	public function isWordPressScrape()
520
+	{
521
+		return $this->request_type->isWordPressScrape();
522
+	}
523
+
524
+
525
+	/**
526
+	 * @return string
527
+	 */
528
+	public function slug()
529
+	{
530
+		return $this->request_type->slug();
531
+	}
532
+
533
+
534
+	/**
535
+	 * returns the path portion of the current request URI with both the WP Root (home_url()) and query params removed
536
+	 *
537
+	 * @return string
538
+	 * @since   $VID:$
539
+	 */
540
+	public function requestPath()
541
+	{
542
+		return $this->requestUri(true, true);
543
+	}
544
+
545
+
546
+	/**
547
+	 * returns true if the last segment of the current request path (without params) matches the provided string
548
+	 *
549
+	 * @param string $uri_segment
550
+	 * @return bool
551
+	 * @since   $VID:$
552
+	 */
553
+	public function currentPageIs($uri_segment)
554
+	{
555
+		$request_path = $this->requestPath();
556
+		$current_page = explode('/', $request_path);
557
+		return end($current_page) === $uri_segment;
558
+	}
559
+
560
+
561
+	/**
562
+	 * @return RequestTypeContextCheckerInterface
563
+	 */
564
+	public function getRequestType(): RequestTypeContextCheckerInterface
565
+	{
566
+		return $this->request_type;
567
+	}
568 568
 }
Please login to merge, or discard this patch.
core/services/assets/I18nRegistry.php 1 patch
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -13,46 +13,46 @@
 block discarded – undo
13 13
  */
14 14
 class I18nRegistry
15 15
 {
16
-    /**
17
-     * @var DomainInterface
18
-     */
19
-    private $domain;
16
+	/**
17
+	 * @var DomainInterface
18
+	 */
19
+	private $domain;
20 20
 
21
-    /**
22
-     * @var JedLocaleData $jed_locale
23
-     */
24
-    private $jed_locale;
21
+	/**
22
+	 * @var JedLocaleData $jed_locale
23
+	 */
24
+	private $jed_locale;
25 25
 
26
-    /**
27
-     * I18nRegistry constructor.
28
-     *
29
-     * @param DomainInterface $domain
30
-     * @param JedLocaleData $jed_locale
31
-     * @param array() $i18n_map
32
-     * @deprecated $VID:$
33
-     */
34
-    public function __construct(DomainInterface $domain, JedLocaleData $jed_locale, array $i18n_map = [])
35
-    {
36
-        $this->domain = $domain;
37
-        $this->jed_locale = $jed_locale;
38
-    }
26
+	/**
27
+	 * I18nRegistry constructor.
28
+	 *
29
+	 * @param DomainInterface $domain
30
+	 * @param JedLocaleData $jed_locale
31
+	 * @param array() $i18n_map
32
+	 * @deprecated $VID:$
33
+	 */
34
+	public function __construct(DomainInterface $domain, JedLocaleData $jed_locale, array $i18n_map = [])
35
+	{
36
+		$this->domain = $domain;
37
+		$this->jed_locale = $jed_locale;
38
+	}
39 39
 
40
-    /**
41
-     * @param string $handle The script handle reference.
42
-     * @param string $domain The i18n domain for the strings.
43
-     * @deprecated $VID:$
44
-     */
45
-    public function registerScriptI18n(string $handle, string $domain = Domain::TEXT_DOMAIN)
46
-    {
47
-    }
40
+	/**
41
+	 * @param string $handle The script handle reference.
42
+	 * @param string $domain The i18n domain for the strings.
43
+	 * @deprecated $VID:$
44
+	 */
45
+	public function registerScriptI18n(string $handle, string $domain = Domain::TEXT_DOMAIN)
46
+	{
47
+	}
48 48
 
49
-    /**
50
-     * @param array $handles Array of registered script handles.
51
-     * @return array
52
-     * @deprecated $VID:$
53
-     */
54
-    public function queueI18n(array $handles): array
55
-    {
56
-        return $handles;
57
-    }
49
+	/**
50
+	 * @param array $handles Array of registered script handles.
51
+	 * @return array
52
+	 * @deprecated $VID:$
53
+	 */
54
+	public function queueI18n(array $handles): array
55
+	{
56
+		return $handles;
57
+	}
58 58
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 1 patch
Indentation   +6593 added lines, -6593 removed lines patch added patch discarded remove patch
@@ -37,6599 +37,6599 @@
 block discarded – undo
37 37
  */
38 38
 abstract class EEM_Base extends EE_Base implements ResettableInterface
39 39
 {
40
-    /**
41
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
42
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
43
-     * They almost always WILL NOT, but it's not necessarily a requirement.
44
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
45
-     *
46
-     * @var boolean
47
-     */
48
-    private $_values_already_prepared_by_model_object = 0;
49
-
50
-    /**
51
-     * when $_values_already_prepared_by_model_object equals this, we assume
52
-     * the data is just like form input that needs to have the model fields'
53
-     * prepare_for_set and prepare_for_use_in_db called on it
54
-     */
55
-    const not_prepared_by_model_object = 0;
56
-
57
-    /**
58
-     * when $_values_already_prepared_by_model_object equals this, we
59
-     * assume this value is coming from a model object and doesn't need to have
60
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
61
-     */
62
-    const prepared_by_model_object = 1;
63
-
64
-    /**
65
-     * when $_values_already_prepared_by_model_object equals this, we assume
66
-     * the values are already to be used in the database (ie no processing is done
67
-     * on them by the model's fields)
68
-     */
69
-    const prepared_for_use_in_db = 2;
70
-
71
-
72
-    protected $singular_item = 'Item';
73
-
74
-    protected $plural_item   = 'Items';
75
-
76
-    /**
77
-     * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
78
-     */
79
-    protected $_tables;
80
-
81
-    /**
82
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
83
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
84
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
85
-     *
86
-     * @var EE_Model_Field_Base[][] $_fields
87
-     */
88
-    protected $_fields;
89
-
90
-    /**
91
-     * array of different kinds of relations
92
-     *
93
-     * @var EE_Model_Relation_Base[] $_model_relations
94
-     */
95
-    protected $_model_relations = [];
96
-
97
-    /**
98
-     * @var EE_Index[] $_indexes
99
-     */
100
-    protected $_indexes = [];
101
-
102
-    /**
103
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
104
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
105
-     * by setting the same columns as used in these queries in the query yourself.
106
-     *
107
-     * @var EE_Default_Where_Conditions
108
-     */
109
-    protected $_default_where_conditions_strategy;
110
-
111
-    /**
112
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
113
-     * This is particularly useful when you want something between 'none' and 'default'
114
-     *
115
-     * @var EE_Default_Where_Conditions
116
-     */
117
-    protected $_minimum_where_conditions_strategy;
118
-
119
-    /**
120
-     * String describing how to find the "owner" of this model's objects.
121
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
122
-     * But when there isn't, this indicates which related model, or transiently-related model,
123
-     * has the foreign key to the wp_users table.
124
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
125
-     * related to events, and events have a foreign key to wp_users.
126
-     * On EEM_Transaction, this would be 'Transaction.Event'
127
-     *
128
-     * @var string
129
-     */
130
-    protected $_model_chain_to_wp_user = '';
131
-
132
-    /**
133
-     * String describing how to find the model with a password controlling access to this model. This property has the
134
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
135
-     * This value is the path of models to follow to arrive at the model with the password field.
136
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
137
-     * model with a password that should affect reading this on the front-end.
138
-     * Eg this is an empty string for the Event model because it has a password.
139
-     * This is null for the Registration model, because its event's password has no bearing on whether
140
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
141
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
142
-     * should hide tickets for datetimes for events that have a password set.
143
-     *
144
-     * @var string |null
145
-     */
146
-    protected $model_chain_to_password = null;
147
-
148
-    /**
149
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
150
-     * don't need it (particularly CPT models)
151
-     *
152
-     * @var bool
153
-     */
154
-    protected $_ignore_where_strategy = false;
155
-
156
-    /**
157
-     * String used in caps relating to this model. Eg, if the caps relating to this
158
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
159
-     *
160
-     * @var string. If null it hasn't been initialized yet. If false then we
161
-     * have indicated capabilities don't apply to this
162
-     */
163
-    protected $_caps_slug = null;
164
-
165
-    /**
166
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
167
-     * and next-level keys are capability names, and each's value is a
168
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
169
-     * they specify which context to use (ie, frontend, backend, edit or delete)
170
-     * and then each capability in the corresponding sub-array that they're missing
171
-     * adds the where conditions onto the query.
172
-     *
173
-     * @var array
174
-     */
175
-    protected $_cap_restrictions = [
176
-        self::caps_read       => [],
177
-        self::caps_read_admin => [],
178
-        self::caps_edit       => [],
179
-        self::caps_delete     => [],
180
-    ];
181
-
182
-    /**
183
-     * Array defining which cap restriction generators to use to create default
184
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
185
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
186
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
187
-     * automatically set this to false (not just null).
188
-     *
189
-     * @var EE_Restriction_Generator_Base[]
190
-     */
191
-    protected $_cap_restriction_generators = [];
192
-
193
-    /**
194
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
195
-     */
196
-    const caps_read       = 'read';
197
-
198
-    const caps_read_admin = 'read_admin';
199
-
200
-    const caps_edit       = 'edit';
201
-
202
-    const caps_delete     = 'delete';
203
-
204
-    /**
205
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
206
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
207
-     * maps to 'read' because when looking for relevant permissions we're going to use
208
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
209
-     *
210
-     * @var array
211
-     */
212
-    protected $_cap_contexts_to_cap_action_map = [
213
-        self::caps_read       => 'read',
214
-        self::caps_read_admin => 'read',
215
-        self::caps_edit       => 'edit',
216
-        self::caps_delete     => 'delete',
217
-    ];
218
-
219
-    /**
220
-     * Timezone
221
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
222
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
223
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
224
-     * EE_Datetime_Field data type will have access to it.
225
-     *
226
-     * @var string
227
-     */
228
-    protected $_timezone;
229
-
230
-
231
-    /**
232
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
233
-     * multisite.
234
-     *
235
-     * @var int
236
-     */
237
-    protected static $_model_query_blog_id;
238
-
239
-    /**
240
-     * A copy of _fields, except the array keys are the model names pointed to by
241
-     * the field
242
-     *
243
-     * @var EE_Model_Field_Base[]
244
-     */
245
-    private $_cache_foreign_key_to_fields = [];
246
-
247
-    /**
248
-     * Cached list of all the fields on the model, indexed by their name
249
-     *
250
-     * @var EE_Model_Field_Base[]
251
-     */
252
-    private $_cached_fields = null;
253
-
254
-    /**
255
-     * Cached list of all the fields on the model, except those that are
256
-     * marked as only pertinent to the database
257
-     *
258
-     * @var EE_Model_Field_Base[]
259
-     */
260
-    private $_cached_fields_non_db_only = null;
261
-
262
-    /**
263
-     * A cached reference to the primary key for quick lookup
264
-     *
265
-     * @var EE_Model_Field_Base
266
-     */
267
-    private $_primary_key_field = null;
268
-
269
-    /**
270
-     * Flag indicating whether this model has a primary key or not
271
-     *
272
-     * @var boolean
273
-     */
274
-    protected $_has_primary_key_field = null;
275
-
276
-    /**
277
-     * array in the format:  [ FK alias => full PK ]
278
-     * where keys are local column name aliases for foreign keys
279
-     * and values are the fully qualified column name for the primary key they represent
280
-     *  ex:
281
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
282
-     *
283
-     * @var array $foreign_key_aliases
284
-     */
285
-    protected $foreign_key_aliases = [];
286
-
287
-    /**
288
-     * Whether or not this model is based off a table in WP core only (CPTs should set
289
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
290
-     * This should be true for models that deal with data that should exist independent of EE.
291
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
292
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
293
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
294
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
295
-     *
296
-     * @var boolean
297
-     */
298
-    protected $_wp_core_model = false;
299
-
300
-    /**
301
-     * @var bool stores whether this model has a password field or not.
302
-     * null until initialized by hasPasswordField()
303
-     */
304
-    protected $has_password_field;
305
-
306
-    /**
307
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
308
-     */
309
-    protected $password_field;
310
-
311
-    /**
312
-     *    List of valid operators that can be used for querying.
313
-     * The keys are all operators we'll accept, the values are the real SQL
314
-     * operators used
315
-     *
316
-     * @var array
317
-     */
318
-    protected $_valid_operators = [
319
-        '='           => '=',
320
-        '<='          => '<=',
321
-        '<'           => '<',
322
-        '>='          => '>=',
323
-        '>'           => '>',
324
-        '!='          => '!=',
325
-        'LIKE'        => 'LIKE',
326
-        'like'        => 'LIKE',
327
-        'NOT_LIKE'    => 'NOT LIKE',
328
-        'not_like'    => 'NOT LIKE',
329
-        'NOT LIKE'    => 'NOT LIKE',
330
-        'not like'    => 'NOT LIKE',
331
-        'IN'          => 'IN',
332
-        'in'          => 'IN',
333
-        'NOT_IN'      => 'NOT IN',
334
-        'not_in'      => 'NOT IN',
335
-        'NOT IN'      => 'NOT IN',
336
-        'not in'      => 'NOT IN',
337
-        'between'     => 'BETWEEN',
338
-        'BETWEEN'     => 'BETWEEN',
339
-        'IS_NOT_NULL' => 'IS NOT NULL',
340
-        'is_not_null' => 'IS NOT NULL',
341
-        'IS NOT NULL' => 'IS NOT NULL',
342
-        'is not null' => 'IS NOT NULL',
343
-        'IS_NULL'     => 'IS NULL',
344
-        'is_null'     => 'IS NULL',
345
-        'IS NULL'     => 'IS NULL',
346
-        'is null'     => 'IS NULL',
347
-        'REGEXP'      => 'REGEXP',
348
-        'regexp'      => 'REGEXP',
349
-        'NOT_REGEXP'  => 'NOT REGEXP',
350
-        'not_regexp'  => 'NOT REGEXP',
351
-        'NOT REGEXP'  => 'NOT REGEXP',
352
-        'not regexp'  => 'NOT REGEXP',
353
-    ];
354
-
355
-    /**
356
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
357
-     *
358
-     * @var array
359
-     */
360
-    protected $_in_style_operators = ['IN', 'NOT IN'];
361
-
362
-    /**
363
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
364
-     * '12-31-2012'"
365
-     *
366
-     * @var array
367
-     */
368
-    protected $_between_style_operators = ['BETWEEN'];
369
-
370
-    /**
371
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
372
-     *
373
-     * @var array
374
-     */
375
-    protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
376
-
377
-    /**
378
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
379
-     * on a join table.
380
-     *
381
-     * @var array
382
-     */
383
-    protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
384
-
385
-    /**
386
-     * Allowed values for $query_params['order'] for ordering in queries
387
-     *
388
-     * @var array
389
-     */
390
-    protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
391
-
392
-    /**
393
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
394
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
395
-     *
396
-     * @var array
397
-     */
398
-    private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
399
-
400
-    /**
401
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
402
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
403
-     *
404
-     * @var array
405
-     */
406
-    private $_allowed_query_params = [
407
-        0,
408
-        'limit',
409
-        'order_by',
410
-        'group_by',
411
-        'having',
412
-        'force_join',
413
-        'order',
414
-        'on_join_limit',
415
-        'default_where_conditions',
416
-        'caps',
417
-        'extra_selects',
418
-        'exclude_protected',
419
-    ];
420
-
421
-    /**
422
-     * All the data types that can be used in $wpdb->prepare statements.
423
-     *
424
-     * @var array
425
-     */
426
-    private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
427
-
428
-    /**
429
-     * @var EE_Registry $EE
430
-     */
431
-    protected $EE = null;
432
-
433
-
434
-    /**
435
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
436
-     *
437
-     * @var int
438
-     */
439
-    protected $_show_next_x_db_queries = 0;
440
-
441
-    /**
442
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
443
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
444
-     * WHERE, GROUP_BY, etc.
445
-     *
446
-     * @var CustomSelects
447
-     */
448
-    protected $_custom_selections = [];
449
-
450
-    /**
451
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
452
-     * caches every model object we've fetched from the DB on this request
453
-     *
454
-     * @var array
455
-     */
456
-    protected $_entity_map;
457
-
458
-    /**
459
-     * @var LoaderInterface
460
-     */
461
-    protected static $loader;
462
-
463
-    /**
464
-     * @var Mirror
465
-     */
466
-    private static $mirror;
467
-
468
-
469
-    /**
470
-     * constant used to show EEM_Base has not yet verified the db on this http request
471
-     */
472
-    const db_verified_none = 0;
473
-
474
-    /**
475
-     * constant used to show EEM_Base has verified the EE core db on this http request,
476
-     * but not the addons' dbs
477
-     */
478
-    const db_verified_core = 1;
479
-
480
-    /**
481
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
482
-     * the EE core db too)
483
-     */
484
-    const db_verified_addons = 2;
485
-
486
-    /**
487
-     * indicates whether an EEM_Base child has already re-verified the DB
488
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
489
-     * looking like EEM_Base::db_verified_*
490
-     *
491
-     * @var int - 0 = none, 1 = core, 2 = addons
492
-     */
493
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
494
-
495
-    /**
496
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
497
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
498
-     *        registrations for non-trashed tickets for non-trashed datetimes)
499
-     */
500
-    const default_where_conditions_all = 'all';
501
-
502
-    /**
503
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
504
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
505
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
506
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
507
-     *        models which share tables with other models, this can return data for the wrong model.
508
-     */
509
-    const default_where_conditions_this_only = 'this_model_only';
510
-
511
-    /**
512
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
513
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
514
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
515
-     */
516
-    const default_where_conditions_others_only = 'other_models_only';
517
-
518
-    /**
519
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
520
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
521
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
522
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
523
-     *        (regardless of whether those events and venues are trashed)
524
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
525
-     *        events.
526
-     */
527
-    const default_where_conditions_minimum_all = 'minimum';
528
-
529
-    /**
530
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
531
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
532
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
533
-     *        not)
534
-     */
535
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
536
-
537
-    /**
538
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
539
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
540
-     *        it's possible it will return table entries for other models. You should use
541
-     *        EEM_Base::default_where_conditions_minimum_all instead.
542
-     */
543
-    const default_where_conditions_none = 'none';
544
-
545
-
546
-    /**
547
-     * About all child constructors:
548
-     * they should define the _tables, _fields and _model_relations arrays.
549
-     * Should ALWAYS be called after child constructor.
550
-     * In order to make the child constructors to be as simple as possible, this parent constructor
551
-     * finalizes constructing all the object's attributes.
552
-     * Generally, rather than requiring a child to code
553
-     * $this->_tables = array(
554
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
555
-     *        ...);
556
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
557
-     * each EE_Table has a function to set the table's alias after the constructor, using
558
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
559
-     * do something similar.
560
-     *
561
-     * @param null $timezone
562
-     * @throws EE_Error
563
-     */
564
-    protected function __construct($timezone = null)
565
-    {
566
-        // check that the model has not been loaded too soon
567
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
568
-            throw new EE_Error(
569
-                sprintf(
570
-                    esc_html__(
571
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
572
-                        'event_espresso'
573
-                    ),
574
-                    get_class($this)
575
-                )
576
-            );
577
-        }
578
-        /**
579
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
580
-         */
581
-        if (empty(EEM_Base::$_model_query_blog_id)) {
582
-            EEM_Base::set_model_query_blog_id();
583
-        }
584
-        /**
585
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
586
-         * just use EE_Register_Model_Extension
587
-         *
588
-         * @var EE_Table_Base[] $_tables
589
-         */
590
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
591
-        foreach ($this->_tables as $table_alias => $table_obj) {
592
-            /** @var $table_obj EE_Table_Base */
593
-            $table_obj->_construct_finalize_with_alias($table_alias);
594
-            if ($table_obj instanceof EE_Secondary_Table) {
595
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
596
-            }
597
-        }
598
-        /**
599
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
600
-         * EE_Register_Model_Extension
601
-         *
602
-         * @param EE_Model_Field_Base[] $_fields
603
-         */
604
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
605
-        $this->_invalidate_field_caches();
606
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
607
-            if (! array_key_exists($table_alias, $this->_tables)) {
608
-                throw new EE_Error(
609
-                    sprintf(
610
-                        esc_html__(
611
-                            "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
612
-                            'event_espresso'
613
-                        ),
614
-                        $table_alias,
615
-                        implode(",", $this->_fields)
616
-                    )
617
-                );
618
-            }
619
-            foreach ($fields_for_table as $field_name => $field_obj) {
620
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
621
-                // primary key field base has a slightly different _construct_finalize
622
-                /** @var $field_obj EE_Model_Field_Base */
623
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
624
-            }
625
-        }
626
-        // everything is related to Extra_Meta
627
-        if (get_class($this) !== 'EEM_Extra_Meta') {
628
-            // make extra meta related to everything, but don't block deleting things just
629
-            // because they have related extra meta info. For now just orphan those extra meta
630
-            // in the future we should automatically delete them
631
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
632
-        }
633
-        // and change logs
634
-        if (get_class($this) !== 'EEM_Change_Log') {
635
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
636
-        }
637
-        /**
638
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
639
-         * EE_Register_Model_Extension
640
-         *
641
-         * @param EE_Model_Relation_Base[] $_model_relations
642
-         */
643
-        $this->_model_relations = (array) apply_filters(
644
-            'FHEE__' . get_class($this) . '__construct__model_relations',
645
-            $this->_model_relations
646
-        );
647
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
648
-            /** @var $relation_obj EE_Model_Relation_Base */
649
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
650
-        }
651
-        foreach ($this->_indexes as $index_name => $index_obj) {
652
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
653
-        }
654
-        $this->set_timezone($timezone);
655
-        // finalize default where condition strategy, or set default
656
-        if (! $this->_default_where_conditions_strategy) {
657
-            // nothing was set during child constructor, so set default
658
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
659
-        }
660
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
661
-        if (! $this->_minimum_where_conditions_strategy) {
662
-            // nothing was set during child constructor, so set default
663
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
664
-        }
665
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
666
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
667
-        // to indicate to NOT set it, set it to the logical default
668
-        if ($this->_caps_slug === null) {
669
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
670
-        }
671
-        // initialize the standard cap restriction generators if none were specified by the child constructor
672
-        if (is_array($this->_cap_restriction_generators)) {
673
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
674
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
675
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
676
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
677
-                        new EE_Restriction_Generator_Protected(),
678
-                        $cap_context,
679
-                        $this
680
-                    );
681
-                }
682
-            }
683
-        }
684
-        // if there are cap restriction generators, use them to make the default cap restrictions
685
-        if (is_array($this->_cap_restriction_generators)) {
686
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
687
-                if (! $generator_object) {
688
-                    continue;
689
-                }
690
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
691
-                    throw new EE_Error(
692
-                        sprintf(
693
-                            esc_html__(
694
-                                '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.',
695
-                                'event_espresso'
696
-                            ),
697
-                            $context,
698
-                            $this->get_this_model_name()
699
-                        )
700
-                    );
701
-                }
702
-                $action = $this->cap_action_for_context($context);
703
-                if (! $generator_object->construction_finalized()) {
704
-                    $generator_object->_construct_finalize($this, $action);
705
-                }
706
-            }
707
-        }
708
-        do_action('AHEE__' . get_class($this) . '__construct__end');
709
-    }
710
-
711
-
712
-    /**
713
-     * @return LoaderInterface
714
-     * @throws InvalidArgumentException
715
-     * @throws InvalidDataTypeException
716
-     * @throws InvalidInterfaceException
717
-     */
718
-    protected static function getLoader(): LoaderInterface
719
-    {
720
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
721
-            EEM_Base::$loader = LoaderFactory::getLoader();
722
-        }
723
-        return EEM_Base::$loader;
724
-    }
725
-
726
-
727
-    /**
728
-     * @return Mirror
729
-     * @since   $VID:$
730
-     */
731
-    private static function getMirror(): Mirror
732
-    {
733
-        if (! EEM_Base::$mirror instanceof Mirror) {
734
-            EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
735
-        }
736
-        return EEM_Base::$mirror;
737
-    }
738
-
739
-
740
-    /**
741
-     * @param string $model_class_Name
742
-     * @param string $timezone
743
-     * @return array
744
-     * @throws ReflectionException
745
-     * @since   $VID:$
746
-     */
747
-    private static function getModelArguments(string $model_class_Name, string $timezone): array
748
-    {
749
-        $arguments = [$timezone];
750
-        $params    = EEM_Base::getMirror()->getParameters($model_class_Name);
751
-        if (count($params) > 1) {
752
-            if ($params[1]->getName() === 'model_field_factory') {
753
-                $arguments = [
754
-                    $timezone,
755
-                    EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
756
-                ];
757
-            } elseif ($model_class_Name === 'EEM_Form_Section') {
758
-                $arguments = [
759
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
760
-                    $timezone,
761
-                ];
762
-            } elseif ($model_class_Name === 'EEM_Form_Element') {
763
-                $arguments = [
764
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
765
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
766
-                    $timezone,
767
-                ];
768
-            }
769
-        }
770
-        return $arguments;
771
-    }
772
-
773
-
774
-    /**
775
-     * This function is a singleton method used to instantiate the Espresso_model object
776
-     *
777
-     * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
778
-     *                                (and any incoming timezone data that gets saved).
779
-     *                                Note this just sends the timezone info to the date time model field objects.
780
-     *                                Default is NULL
781
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
782
-     * @return static (as in the concrete child class)
783
-     * @throws EE_Error
784
-     * @throws ReflectionException
785
-     */
786
-    public static function instance($timezone = null)
787
-    {
788
-        // check if instance of Espresso_model already exists
789
-        if (! static::$_instance instanceof static) {
790
-            $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
791
-            $model     = new static(...$arguments);
792
-            EEM_Base::getLoader()->share(static::class, $model, $arguments);
793
-            static::$_instance = $model;
794
-        }
795
-        // we might have a timezone set, let set_timezone decide what to do with it
796
-        if ($timezone) {
797
-            static::$_instance->set_timezone($timezone);
798
-        }
799
-        // Espresso_model object
800
-        return static::$_instance;
801
-    }
802
-
803
-
804
-    /**
805
-     * resets the model and returns it
806
-     *
807
-     * @param string|null $timezone
808
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
809
-     * all its properties reset; if it wasn't instantiated, returns null)
810
-     * @throws EE_Error
811
-     * @throws ReflectionException
812
-     * @throws InvalidArgumentException
813
-     * @throws InvalidDataTypeException
814
-     * @throws InvalidInterfaceException
815
-     */
816
-    public static function reset($timezone = null)
817
-    {
818
-        if (! static::$_instance instanceof EEM_Base) {
819
-            return null;
820
-        }
821
-        // Let's NOT swap out the current instance for a new one
822
-        // because if someone has a reference to it, we can't remove their reference.
823
-        // It's best to keep using the same reference but change the original object instead,
824
-        // so reset all its properties to their original values as defined in the class.
825
-        $static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
826
-        foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
827
-            // don't set instance to null like it was originally,
828
-            // but it's static anyways, and we're ignoring static properties (for now at least)
829
-            if (! isset($static_properties[ $property ])) {
830
-                static::$_instance->{$property} = $value;
831
-            }
832
-        }
833
-        // and then directly call its constructor again, like we would if we were creating a new one
834
-        $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
835
-        static::$_instance->__construct(...$arguments);
836
-        return self::instance();
837
-    }
838
-
839
-
840
-    /**
841
-     * Used to set the $_model_query_blog_id static property.
842
-     *
843
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
844
-     *                      value for get_current_blog_id() will be used.
845
-     */
846
-    public static function set_model_query_blog_id($blog_id = 0)
847
-    {
848
-        EEM_Base::$_model_query_blog_id = $blog_id > 0
849
-            ? (int) $blog_id
850
-            : get_current_blog_id();
851
-    }
852
-
853
-
854
-    /**
855
-     * Returns whatever is set as the internal $model_query_blog_id.
856
-     *
857
-     * @return int
858
-     */
859
-    public static function get_model_query_blog_id()
860
-    {
861
-        return EEM_Base::$_model_query_blog_id;
862
-    }
863
-
864
-
865
-    /**
866
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
867
-     *
868
-     * @param boolean $translated return localized strings or JUST the array.
869
-     * @return array
870
-     * @throws EE_Error
871
-     * @throws InvalidArgumentException
872
-     * @throws InvalidDataTypeException
873
-     * @throws InvalidInterfaceException
874
-     * @throws ReflectionException
875
-     */
876
-    public function status_array($translated = false)
877
-    {
878
-        if (! array_key_exists('Status', $this->_model_relations)) {
879
-            return [];
880
-        }
881
-        $model_name   = $this->get_this_model_name();
882
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
883
-        $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
884
-        $status_array = [];
885
-        foreach ($stati as $status) {
886
-            $status_array[ $status->ID() ] = $status->get('STS_code');
887
-        }
888
-        return $translated
889
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
890
-            : $status_array;
891
-    }
892
-
893
-
894
-    /**
895
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
896
-     *
897
-     * @param array $query_params             @see
898
-     *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
899
-     *                                        or if you have the development copy of EE you can view this at the path:
900
-     *                                        /docs/G--Model-System/model-query-params.md
901
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
902
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
903
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
904
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
905
-     *                                        EEM_Transaction::instance()->get_all( array( array(
906
-     *                                        'OR'=>array(
907
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
908
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
909
-     *                                        )
910
-     *                                        ),
911
-     *                                        'limit'=>10,
912
-     *                                        'group_by'=>'TXN_ID'
913
-     *                                        ));
914
-     *                                        get all the answers to the question titled "shirt size" for event with id
915
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
916
-     *                                        'Question.QST_display_text'=>'shirt size',
917
-     *                                        'Registration.Event.EVT_ID'=>12
918
-     *                                        ),
919
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
920
-     *                                        ));
921
-     * @throws EE_Error
922
-     * @throws ReflectionException
923
-     */
924
-    public function get_all($query_params = [])
925
-    {
926
-        if (
927
-            isset($query_params['limit'])
928
-            && ! isset($query_params['group_by'])
929
-        ) {
930
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
931
-        }
932
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
933
-    }
934
-
935
-
936
-    /**
937
-     * Modifies the query parameters so we only get back model objects
938
-     * that "belong" to the current user
939
-     *
940
-     * @param array $query_params @see
941
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
942
-     * @return array @see
943
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
944
-     * @throws ReflectionException
945
-     * @throws ReflectionException
946
-     */
947
-    public function alter_query_params_to_only_include_mine($query_params = [])
948
-    {
949
-        $wp_user_field_name = $this->wp_user_field_name();
950
-        if ($wp_user_field_name) {
951
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
952
-        }
953
-        return $query_params;
954
-    }
955
-
956
-
957
-    /**
958
-     * Returns the name of the field's name that points to the WP_User table
959
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
960
-     * foreign key to the WP_User table)
961
-     *
962
-     * @return string|boolean string on success, boolean false when there is no
963
-     * foreign key to the WP_User table
964
-     * @throws ReflectionException
965
-     * @throws ReflectionException
966
-     */
967
-    public function wp_user_field_name()
968
-    {
969
-        try {
970
-            if (! empty($this->_model_chain_to_wp_user)) {
971
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
972
-                $last_model_name              = end($models_to_follow_to_wp_users);
973
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
974
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
975
-            } else {
976
-                $model_with_fk_to_wp_users = $this;
977
-                $model_chain_to_wp_user    = '';
978
-            }
979
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
980
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
981
-        } catch (EE_Error $e) {
982
-            return false;
983
-        }
984
-    }
985
-
986
-
987
-    /**
988
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
989
-     * (or transiently-related model) has a foreign key to the wp_users table;
990
-     * useful for finding if model objects of this type are 'owned' by the current user.
991
-     * This is an empty string when the foreign key is on this model and when it isn't,
992
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
993
-     * (or transiently-related model)
994
-     *
995
-     * @return string
996
-     */
997
-    public function model_chain_to_wp_user()
998
-    {
999
-        return $this->_model_chain_to_wp_user;
1000
-    }
1001
-
1002
-
1003
-    /**
1004
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1005
-     * like how registrations don't have a foreign key to wp_users, but the
1006
-     * events they are for are), or is unrelated to wp users.
1007
-     * generally available
1008
-     *
1009
-     * @return boolean
1010
-     */
1011
-    public function is_owned()
1012
-    {
1013
-        if ($this->model_chain_to_wp_user()) {
1014
-            return true;
1015
-        }
1016
-        try {
1017
-            $this->get_foreign_key_to('WP_User');
1018
-            return true;
1019
-        } catch (EE_Error $e) {
1020
-            return false;
1021
-        }
1022
-    }
1023
-
1024
-
1025
-    /**
1026
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1027
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1028
-     * the model)
1029
-     *
1030
-     * @param array  $query_params      @see
1031
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1032
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1033
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1034
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1035
-     *                                  override this and set the select to "*", or a specific column name, like
1036
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1037
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1038
-     *                                  the aliases used to refer to this selection, and values are to be
1039
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1040
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1041
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1042
-     * @throws EE_Error
1043
-     * @throws InvalidArgumentException
1044
-     */
1045
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1046
-    {
1047
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1048
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1049
-        $select_expressions       = $columns_to_select === null
1050
-            ? $this->_construct_default_select_sql($model_query_info)
1051
-            : '';
1052
-        if ($this->_custom_selections instanceof CustomSelects) {
1053
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1054
-            $select_expressions .= $select_expressions
1055
-                ? ', ' . $custom_expressions
1056
-                : $custom_expressions;
1057
-        }
1058
-
1059
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1060
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1061
-    }
1062
-
1063
-
1064
-    /**
1065
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1066
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1067
-     * method of including extra select information.
1068
-     *
1069
-     * @param array             $query_params
1070
-     * @param null|array|string $columns_to_select
1071
-     * @return null|CustomSelects
1072
-     * @throws InvalidArgumentException
1073
-     */
1074
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1075
-    {
1076
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1077
-            return null;
1078
-        }
1079
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1080
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1081
-        return new CustomSelects($selects);
1082
-    }
1083
-
1084
-
1085
-    /**
1086
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1087
-     * but you can use the model query params to more easily
1088
-     * take care of joins, field preparation etc.
1089
-     *
1090
-     * @param array  $query_params      @see
1091
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1092
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1093
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1094
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1095
-     *                                  override this and set the select to "*", or a specific column name, like
1096
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1097
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1098
-     *                                  the aliases used to refer to this selection, and values are to be
1099
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1100
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1101
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1102
-     * @throws EE_Error
1103
-     */
1104
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1105
-    {
1106
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1107
-    }
1108
-
1109
-
1110
-    /**
1111
-     * For creating a custom select statement
1112
-     *
1113
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1114
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1115
-     *                                 SQL, and 1=>is the datatype
1116
-     * @return string
1117
-     * @throws EE_Error
1118
-     */
1119
-    private function _construct_select_from_input($columns_to_select)
1120
-    {
1121
-        if (is_array($columns_to_select)) {
1122
-            $select_sql_array = [];
1123
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1124
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1125
-                    throw new EE_Error(
1126
-                        sprintf(
1127
-                            esc_html__(
1128
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1129
-                                'event_espresso'
1130
-                            ),
1131
-                            $selection_and_datatype,
1132
-                            $alias
1133
-                        )
1134
-                    );
1135
-                }
1136
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1137
-                    throw new EE_Error(
1138
-                        sprintf(
1139
-                            esc_html__(
1140
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1141
-                                'event_espresso'
1142
-                            ),
1143
-                            $selection_and_datatype[1],
1144
-                            $selection_and_datatype[0],
1145
-                            $alias,
1146
-                            implode(', ', $this->_valid_wpdb_data_types)
1147
-                        )
1148
-                    );
1149
-                }
1150
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1151
-            }
1152
-            $columns_to_select_string = implode(', ', $select_sql_array);
1153
-        } else {
1154
-            $columns_to_select_string = $columns_to_select;
1155
-        }
1156
-        return $columns_to_select_string;
1157
-    }
1158
-
1159
-
1160
-    /**
1161
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1162
-     *
1163
-     * @return string
1164
-     * @throws EE_Error
1165
-     */
1166
-    public function primary_key_name()
1167
-    {
1168
-        return $this->get_primary_key_field()->get_name();
1169
-    }
1170
-
1171
-
1172
-    /**
1173
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1174
-     * If there is no primary key on this model, $id is treated as primary key string
1175
-     *
1176
-     * @param mixed $id int or string, depending on the type of the model's primary key
1177
-     * @return EE_Base_Class|mixed|null
1178
-     * @throws EE_Error
1179
-     * @throws ReflectionException
1180
-     */
1181
-    public function get_one_by_ID($id)
1182
-    {
1183
-        if ($this->get_from_entity_map($id)) {
1184
-            return $this->get_from_entity_map($id);
1185
-        }
1186
-        $model_object = $this->get_one(
1187
-            $this->alter_query_params_to_restrict_by_ID(
1188
-                $id,
1189
-                ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1190
-            )
1191
-        );
1192
-        $className    = $this->_get_class_name();
1193
-        if ($model_object instanceof $className) {
1194
-            // make sure valid objects get added to the entity map
1195
-            // so that the next call to this method doesn't trigger another trip to the db
1196
-            $this->add_to_entity_map($model_object);
1197
-        }
1198
-        return $model_object;
1199
-    }
1200
-
1201
-
1202
-    /**
1203
-     * Alters query parameters to only get items with this ID are returned.
1204
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1205
-     * or could just be a simple primary key ID
1206
-     *
1207
-     * @param int   $id
1208
-     * @param array $query_params
1209
-     * @return array of normal query params, @see
1210
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1211
-     * @throws EE_Error
1212
-     */
1213
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1214
-    {
1215
-        if (! isset($query_params[0])) {
1216
-            $query_params[0] = [];
1217
-        }
1218
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1219
-        if ($conditions_from_id === null) {
1220
-            $query_params[0][ $this->primary_key_name() ] = $id;
1221
-        } else {
1222
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1223
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1224
-        }
1225
-        return $query_params;
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1231
-     * array. If no item is found, null is returned.
1232
-     *
1233
-     * @param array $query_params like EEM_Base's $query_params variable.
1234
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1235
-     * @throws EE_Error
1236
-     */
1237
-    public function get_one($query_params = [])
1238
-    {
1239
-        if (! is_array($query_params)) {
1240
-            EE_Error::doing_it_wrong(
1241
-                'EEM_Base::get_one',
1242
-                sprintf(
1243
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1244
-                    gettype($query_params)
1245
-                ),
1246
-                '4.6.0'
1247
-            );
1248
-            $query_params = [];
1249
-        }
1250
-        $query_params['limit'] = 1;
1251
-        $items                 = $this->get_all($query_params);
1252
-        if (empty($items)) {
1253
-            return null;
1254
-        }
1255
-        return array_shift($items);
1256
-    }
1257
-
1258
-
1259
-    /**
1260
-     * Returns the next x number of items in sequence from the given value as
1261
-     * found in the database matching the given query conditions.
1262
-     *
1263
-     * @param mixed $current_field_value    Value used for the reference point.
1264
-     * @param null  $field_to_order_by      What field is used for the
1265
-     *                                      reference point.
1266
-     * @param int   $limit                  How many to return.
1267
-     * @param array $query_params           Extra conditions on the query.
1268
-     * @param null  $columns_to_select      If left null, then an array of
1269
-     *                                      EE_Base_Class objects is returned,
1270
-     *                                      otherwise you can indicate just the
1271
-     *                                      columns you want returned.
1272
-     * @return EE_Base_Class[]|array
1273
-     * @throws EE_Error
1274
-     */
1275
-    public function next_x(
1276
-        $current_field_value,
1277
-        $field_to_order_by = null,
1278
-        $limit = 1,
1279
-        $query_params = [],
1280
-        $columns_to_select = null
1281
-    ) {
1282
-        return $this->_get_consecutive(
1283
-            $current_field_value,
1284
-            '>',
1285
-            $field_to_order_by,
1286
-            $limit,
1287
-            $query_params,
1288
-            $columns_to_select
1289
-        );
1290
-    }
1291
-
1292
-
1293
-    /**
1294
-     * Returns the previous x number of items in sequence from the given value
1295
-     * as found in the database matching the given query conditions.
1296
-     *
1297
-     * @param mixed $current_field_value    Value used for the reference point.
1298
-     * @param null  $field_to_order_by      What field is used for the
1299
-     *                                      reference point.
1300
-     * @param int   $limit                  How many to return.
1301
-     * @param array $query_params           Extra conditions on the query.
1302
-     * @param null  $columns_to_select      If left null, then an array of
1303
-     *                                      EE_Base_Class objects is returned,
1304
-     *                                      otherwise you can indicate just the
1305
-     *                                      columns you want returned.
1306
-     * @return EE_Base_Class[]|array
1307
-     * @throws EE_Error
1308
-     */
1309
-    public function previous_x(
1310
-        $current_field_value,
1311
-        $field_to_order_by = null,
1312
-        $limit = 1,
1313
-        $query_params = [],
1314
-        $columns_to_select = null
1315
-    ) {
1316
-        return $this->_get_consecutive(
1317
-            $current_field_value,
1318
-            '<',
1319
-            $field_to_order_by,
1320
-            $limit,
1321
-            $query_params,
1322
-            $columns_to_select
1323
-        );
1324
-    }
1325
-
1326
-
1327
-    /**
1328
-     * Returns the next item in sequence from the given value as found in the
1329
-     * database matching the given query conditions.
1330
-     *
1331
-     * @param mixed $current_field_value    Value used for the reference point.
1332
-     * @param null  $field_to_order_by      What field is used for the
1333
-     *                                      reference point.
1334
-     * @param array $query_params           Extra conditions on the query.
1335
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1336
-     *                                      object is returned, otherwise you
1337
-     *                                      can indicate just the columns you
1338
-     *                                      want and a single array indexed by
1339
-     *                                      the columns will be returned.
1340
-     * @return EE_Base_Class|null|array()
1341
-     * @throws EE_Error
1342
-     */
1343
-    public function next(
1344
-        $current_field_value,
1345
-        $field_to_order_by = null,
1346
-        $query_params = [],
1347
-        $columns_to_select = null
1348
-    ) {
1349
-        $results = $this->_get_consecutive(
1350
-            $current_field_value,
1351
-            '>',
1352
-            $field_to_order_by,
1353
-            1,
1354
-            $query_params,
1355
-            $columns_to_select
1356
-        );
1357
-        return empty($results) ? null : reset($results);
1358
-    }
1359
-
1360
-
1361
-    /**
1362
-     * Returns the previous item in sequence from the given value as found in
1363
-     * the database matching the given query conditions.
1364
-     *
1365
-     * @param mixed $current_field_value    Value used for the reference point.
1366
-     * @param null  $field_to_order_by      What field is used for the
1367
-     *                                      reference point.
1368
-     * @param array $query_params           Extra conditions on the query.
1369
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1370
-     *                                      object is returned, otherwise you
1371
-     *                                      can indicate just the columns you
1372
-     *                                      want and a single array indexed by
1373
-     *                                      the columns will be returned.
1374
-     * @return EE_Base_Class|null|array()
1375
-     * @throws EE_Error
1376
-     */
1377
-    public function previous(
1378
-        $current_field_value,
1379
-        $field_to_order_by = null,
1380
-        $query_params = [],
1381
-        $columns_to_select = null
1382
-    ) {
1383
-        $results = $this->_get_consecutive(
1384
-            $current_field_value,
1385
-            '<',
1386
-            $field_to_order_by,
1387
-            1,
1388
-            $query_params,
1389
-            $columns_to_select
1390
-        );
1391
-        return empty($results) ? null : reset($results);
1392
-    }
1393
-
1394
-
1395
-    /**
1396
-     * Returns the a consecutive number of items in sequence from the given
1397
-     * value as found in the database matching the given query conditions.
1398
-     *
1399
-     * @param mixed  $current_field_value   Value used for the reference point.
1400
-     * @param string $operand               What operand is used for the sequence.
1401
-     * @param string $field_to_order_by     What field is used for the reference point.
1402
-     * @param int    $limit                 How many to return.
1403
-     * @param array  $query_params          Extra conditions on the query.
1404
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1405
-     *                                      otherwise you can indicate just the columns you want returned.
1406
-     * @return EE_Base_Class[]|array
1407
-     * @throws EE_Error
1408
-     */
1409
-    protected function _get_consecutive(
1410
-        $current_field_value,
1411
-        $operand = '>',
1412
-        $field_to_order_by = null,
1413
-        $limit = 1,
1414
-        $query_params = [],
1415
-        $columns_to_select = null
1416
-    ) {
1417
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1418
-        if (empty($field_to_order_by)) {
1419
-            if ($this->has_primary_key_field()) {
1420
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1421
-            } else {
1422
-                if (WP_DEBUG) {
1423
-                    throw new EE_Error(
1424
-                        esc_html__(
1425
-                            'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1426
-                            'event_espresso'
1427
-                        )
1428
-                    );
1429
-                }
1430
-                EE_Error::add_error(
1431
-                    esc_html__('There was an error with the query.', 'event_espresso'),
1432
-                    __FILE__,
1433
-                    __FUNCTION__,
1434
-                    __LINE__
1435
-                );
1436
-                return [];
1437
-            }
1438
-        }
1439
-        if (! is_array($query_params)) {
1440
-            EE_Error::doing_it_wrong(
1441
-                'EEM_Base::_get_consecutive',
1442
-                sprintf(
1443
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1444
-                    gettype($query_params)
1445
-                ),
1446
-                '4.6.0'
1447
-            );
1448
-            $query_params = [];
1449
-        }
1450
-        // let's add the where query param for consecutive look up.
1451
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1452
-        $query_params['limit']                 = $limit;
1453
-        // set direction
1454
-        $incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1455
-        $query_params['order_by'] = $operand === '>'
1456
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1457
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1458
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1459
-        if (empty($columns_to_select)) {
1460
-            return $this->get_all($query_params);
1461
-        }
1462
-        // getting just the fields
1463
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1464
-    }
1465
-
1466
-
1467
-    /**
1468
-     * This sets the _timezone property after model object has been instantiated.
1469
-     *
1470
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1471
-     */
1472
-    public function set_timezone($timezone)
1473
-    {
1474
-        if ($timezone !== null) {
1475
-            $this->_timezone = $timezone;
1476
-        }
1477
-        // note we need to loop through relations and set the timezone on those objects as well.
1478
-        foreach ($this->_model_relations as $relation) {
1479
-            $relation->set_timezone($timezone);
1480
-        }
1481
-        // and finally we do the same for any datetime fields
1482
-        foreach ($this->_fields as $field) {
1483
-            if ($field instanceof EE_Datetime_Field) {
1484
-                $field->set_timezone($timezone);
1485
-            }
1486
-        }
1487
-    }
1488
-
1489
-
1490
-    /**
1491
-     * This just returns whatever is set for the current timezone.
1492
-     *
1493
-     * @access public
1494
-     * @return string
1495
-     */
1496
-    public function get_timezone()
1497
-    {
1498
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1499
-        if (empty($this->_timezone)) {
1500
-            foreach ($this->_fields as $field) {
1501
-                if ($field instanceof EE_Datetime_Field) {
1502
-                    $this->set_timezone($field->get_timezone());
1503
-                    break;
1504
-                }
1505
-            }
1506
-        }
1507
-        // if timezone STILL empty then return the default timezone for the site.
1508
-        if (empty($this->_timezone)) {
1509
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1510
-        }
1511
-        return $this->_timezone;
1512
-    }
1513
-
1514
-
1515
-    /**
1516
-     * This returns the date formats set for the given field name and also ensures that
1517
-     * $this->_timezone property is set correctly.
1518
-     *
1519
-     * @param string $field_name The name of the field the formats are being retrieved for.
1520
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1521
-     * @return array formats in an array with the date format first, and the time format last.
1522
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1523
-     * @since 4.6.x
1524
-     */
1525
-    public function get_formats_for($field_name, $pretty = false)
1526
-    {
1527
-        $field_settings = $this->field_settings_for($field_name);
1528
-        // if not a valid EE_Datetime_Field then throw error
1529
-        if (! $field_settings instanceof EE_Datetime_Field) {
1530
-            throw new EE_Error(
1531
-                sprintf(
1532
-                    esc_html__(
1533
-                        '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.',
1534
-                        'event_espresso'
1535
-                    ),
1536
-                    $field_name
1537
-                )
1538
-            );
1539
-        }
1540
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1541
-        // the field.
1542
-        $this->_timezone = $field_settings->get_timezone();
1543
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1544
-    }
1545
-
1546
-
1547
-    /**
1548
-     * This returns the current time in a format setup for a query on this model.
1549
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1550
-     * it will return:
1551
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1552
-     *  NOW
1553
-     *  - or a unix timestamp (equivalent to time())
1554
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1555
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1556
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1557
-     *
1558
-     * @param string $field_name       The field the current time is needed for.
1559
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1560
-     *                                 formatted string matching the set format for the field in the set timezone will
1561
-     *                                 be returned.
1562
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1563
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1564
-     *                                 exception is triggered.
1565
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1566
-     * @throws Exception
1567
-     * @since 4.6.x
1568
-     */
1569
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1570
-    {
1571
-        $formats  = $this->get_formats_for($field_name);
1572
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1573
-        if ($timestamp) {
1574
-            return $DateTime->format('U');
1575
-        }
1576
-        // not returning timestamp, so return formatted string in timezone.
1577
-        switch ($what) {
1578
-            case 'time':
1579
-                return $DateTime->format($formats[1]);
1580
-            case 'date':
1581
-                return $DateTime->format($formats[0]);
1582
-            default:
1583
-                return $DateTime->format(implode(' ', $formats));
1584
-        }
1585
-    }
1586
-
1587
-
1588
-    /**
1589
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1590
-     * for the model are.  Returns a DateTime object.
1591
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1592
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1593
-     * ignored.
1594
-     *
1595
-     * @param string $field_name      The field being setup.
1596
-     * @param string $timestring      The date time string being used.
1597
-     * @param string $incoming_format The format for the time string.
1598
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1599
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1600
-     *                                format is
1601
-     *                                'U', this is ignored.
1602
-     * @return DateTime
1603
-     * @throws EE_Error
1604
-     */
1605
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1606
-    {
1607
-        // just using this to ensure the timezone is set correctly internally
1608
-        $this->get_formats_for($field_name);
1609
-        // load EEH_DTT_Helper
1610
-        $set_timezone     = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1611
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1612
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1613
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1614
-    }
1615
-
1616
-
1617
-    /**
1618
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1619
-     *
1620
-     * @return EE_Table_Base[]
1621
-     */
1622
-    public function get_tables()
1623
-    {
1624
-        return $this->_tables;
1625
-    }
1626
-
1627
-
1628
-    /**
1629
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1630
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1631
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1632
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1633
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1634
-     * model object with EVT_ID = 1
1635
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1636
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1637
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1638
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1639
-     * are not specified)
1640
-     *
1641
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1642
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1643
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1644
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1645
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1646
-     *                                         ID=34, we'd use this method as follows:
1647
-     *                                         EEM_Transaction::instance()->update(
1648
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1649
-     *                                         array(array('TXN_ID'=>34)));
1650
-     * @param array   $query_params            @see
1651
-     *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1652
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1653
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1654
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1655
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1656
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1657
-     *                                         TRUE, it is assumed that you've already called
1658
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1659
-     *                                         malicious javascript. However, if
1660
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1661
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1662
-     *                                         and every other field, before insertion. We provide this parameter
1663
-     *                                         because model objects perform their prepare_for_set function on all
1664
-     *                                         their values, and so don't need to be called again (and in many cases,
1665
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1666
-     *                                         prepare_for_set method...)
1667
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1668
-     *                                         in this model's entity map according to $fields_n_values that match
1669
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1670
-     *                                         by setting this to FALSE, but be aware that model objects being used
1671
-     *                                         could get out-of-sync with the database
1672
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1673
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1674
-     *                                         bad)
1675
-     * @throws EE_Error
1676
-     * @throws ReflectionException
1677
-     */
1678
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1679
-    {
1680
-        if (! is_array($query_params)) {
1681
-            EE_Error::doing_it_wrong(
1682
-                'EEM_Base::update',
1683
-                sprintf(
1684
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1685
-                    gettype($query_params)
1686
-                ),
1687
-                '4.6.0'
1688
-            );
1689
-            $query_params = [];
1690
-        }
1691
-        /**
1692
-         * Action called before a model update call has been made.
1693
-         *
1694
-         * @param EEM_Base $model
1695
-         * @param array    $fields_n_values the updated fields and their new values
1696
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1697
-         */
1698
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1699
-        /**
1700
-         * Filters the fields about to be updated given the query parameters. You can provide the
1701
-         * $query_params to $this->get_all() to find exactly which records will be updated
1702
-         *
1703
-         * @param array    $fields_n_values fields and their new values
1704
-         * @param EEM_Base $model           the model being queried
1705
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1706
-         */
1707
-        $fields_n_values = (array) apply_filters(
1708
-            'FHEE__EEM_Base__update__fields_n_values',
1709
-            $fields_n_values,
1710
-            $this,
1711
-            $query_params
1712
-        );
1713
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1714
-        // to do that, for each table, verify that it's PK isn't null.
1715
-        $tables = $this->get_tables();
1716
-        // 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
1717
-        // NOTE: we should make this code more efficient by NOT querying twice
1718
-        // before the real update, but that needs to first go through ALPHA testing
1719
-        // as it's dangerous. says Mike August 8 2014
1720
-        // we want to make sure the default_where strategy is ignored
1721
-        $this->_ignore_where_strategy = true;
1722
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1723
-        foreach ($wpdb_select_results as $wpdb_result) {
1724
-            // type cast stdClass as array
1725
-            $wpdb_result = (array) $wpdb_result;
1726
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1727
-            if ($this->has_primary_key_field()) {
1728
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1729
-            } else {
1730
-                // 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)
1731
-                $main_table_pk_value = null;
1732
-            }
1733
-            // 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
1734
-            // 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
1735
-            if (count($tables) > 1) {
1736
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1737
-                // in that table, and so we'll want to insert one
1738
-                foreach ($tables as $table_obj) {
1739
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1740
-                    // if there is no private key for this table on the results, it means there's no entry
1741
-                    // in this table, right? so insert a row in the current table, using any fields available
1742
-                    if (
1743
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1744
-                           && $wpdb_result[ $this_table_pk_column ])
1745
-                    ) {
1746
-                        $success = $this->_insert_into_specific_table(
1747
-                            $table_obj,
1748
-                            $fields_n_values,
1749
-                            $main_table_pk_value
1750
-                        );
1751
-                        // if we died here, report the error
1752
-                        if (! $success) {
1753
-                            return false;
1754
-                        }
1755
-                    }
1756
-                }
1757
-            }
1758
-            //              //and now check that if we have cached any models by that ID on the model, that
1759
-            //              //they also get updated properly
1760
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1761
-            //              if( $model_object ){
1762
-            //                  foreach( $fields_n_values as $field => $value ){
1763
-            //                      $model_object->set($field, $value);
1764
-            // let's make sure default_where strategy is followed now
1765
-            $this->_ignore_where_strategy = false;
1766
-        }
1767
-        // if we want to keep model objects in sync, AND
1768
-        // if this wasn't called from a model object (to update itself)
1769
-        // then we want to make sure we keep all the existing
1770
-        // model objects in sync with the db
1771
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1772
-            if ($this->has_primary_key_field()) {
1773
-                $model_objs_affected_ids = $this->get_col($query_params);
1774
-            } else {
1775
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1776
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1777
-                $model_objs_affected_ids     = [];
1778
-                foreach ($models_affected_key_columns as $row) {
1779
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1780
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1781
-                }
1782
-            }
1783
-            if (! $model_objs_affected_ids) {
1784
-                // wait wait wait- if nothing was affected let's stop here
1785
-                return 0;
1786
-            }
1787
-            foreach ($model_objs_affected_ids as $id) {
1788
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1789
-                if ($model_obj_in_entity_map) {
1790
-                    foreach ($fields_n_values as $field => $new_value) {
1791
-                        $model_obj_in_entity_map->set($field, $new_value);
1792
-                    }
1793
-                }
1794
-            }
1795
-            // if there is a primary key on this model, we can now do a slight optimization
1796
-            if ($this->has_primary_key_field()) {
1797
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1798
-                $query_params = [
1799
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1800
-                    'limit'                    => count($model_objs_affected_ids),
1801
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1802
-                ];
1803
-            }
1804
-        }
1805
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1806
-        $SQL              = "UPDATE "
1807
-                            . $model_query_info->get_full_join_sql()
1808
-                            . " SET "
1809
-                            . $this->_construct_update_sql($fields_n_values)
1810
-                            . $model_query_info->get_where_sql(
1811
-                            );// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1812
-        $rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1813
-        /**
1814
-         * Action called after a model update call has been made.
1815
-         *
1816
-         * @param EEM_Base $model
1817
-         * @param array    $fields_n_values the updated fields and their new values
1818
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1819
-         * @param int      $rows_affected
1820
-         */
1821
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1822
-        return $rows_affected;// how many supposedly got updated
1823
-    }
1824
-
1825
-
1826
-    /**
1827
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1828
-     * are teh values of the field specified (or by default the primary key field)
1829
-     * that matched the query params. Note that you should pass the name of the
1830
-     * model FIELD, not the database table's column name.
1831
-     *
1832
-     * @param array  $query_params @see
1833
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1834
-     * @param string $field_to_select
1835
-     * @return array just like $wpdb->get_col()
1836
-     * @throws EE_Error
1837
-     */
1838
-    public function get_col($query_params = [], $field_to_select = null)
1839
-    {
1840
-        if ($field_to_select) {
1841
-            $field = $this->field_settings_for($field_to_select);
1842
-        } elseif ($this->has_primary_key_field()) {
1843
-            $field = $this->get_primary_key_field();
1844
-        } else {
1845
-            $field_settings = $this->field_settings();
1846
-            // no primary key, just grab the first column
1847
-            $field = reset($field_settings);
1848
-            // don't need this array now
1849
-            unset($field_settings);
1850
-        }
1851
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1852
-        $select_expressions = $field->get_qualified_column();
1853
-        $SQL                =
1854
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1855
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1856
-    }
1857
-
1858
-
1859
-    /**
1860
-     * Returns a single column value for a single row from the database
1861
-     *
1862
-     * @param array  $query_params    @see
1863
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1864
-     * @param string $field_to_select @see EEM_Base::get_col()
1865
-     * @return string
1866
-     * @throws EE_Error
1867
-     */
1868
-    public function get_var($query_params = [], $field_to_select = null)
1869
-    {
1870
-        $query_params['limit'] = 1;
1871
-        $col                   = $this->get_col($query_params, $field_to_select);
1872
-        if (! empty($col)) {
1873
-            return reset($col);
1874
-        }
1875
-        return null;
1876
-    }
1877
-
1878
-
1879
-    /**
1880
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1881
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1882
-     * injection, but currently no further filtering is done
1883
-     *
1884
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1885
-     *                               be updated to in the DB
1886
-     * @return string of SQL
1887
-     * @throws EE_Error
1888
-     * @global      $wpdb
1889
-     */
1890
-    public function _construct_update_sql($fields_n_values)
1891
-    {
1892
-        /** @type WPDB $wpdb */
1893
-        global $wpdb;
1894
-        $cols_n_values = [];
1895
-        foreach ($fields_n_values as $field_name => $value) {
1896
-            $field_obj = $this->field_settings_for($field_name);
1897
-            // if the value is NULL, we want to assign the value to that.
1898
-            // wpdb->prepare doesn't really handle that properly
1899
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1900
-            $value_sql       = $prepared_value === null ? 'NULL'
1901
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1902
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1903
-        }
1904
-        return implode(",", $cols_n_values);
1905
-    }
1906
-
1907
-
1908
-    /**
1909
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1910
-     * Performs a HARD delete, meaning the database row should always be removed,
1911
-     * not just have a flag field on it switched
1912
-     * Wrapper for EEM_Base::delete_permanently()
1913
-     *
1914
-     * @param mixed   $id
1915
-     * @param boolean $allow_blocking
1916
-     * @return int the number of rows deleted
1917
-     * @throws EE_Error
1918
-     * @throws ReflectionException
1919
-     */
1920
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1921
-    {
1922
-        return $this->delete_permanently(
1923
-            [
1924
-                [$this->get_primary_key_field()->get_name() => $id],
1925
-                'limit' => 1,
1926
-            ],
1927
-            $allow_blocking
1928
-        );
1929
-    }
1930
-
1931
-
1932
-    /**
1933
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1934
-     * Wrapper for EEM_Base::delete()
1935
-     *
1936
-     * @param mixed   $id
1937
-     * @param boolean $allow_blocking
1938
-     * @return int the number of rows deleted
1939
-     * @throws EE_Error
1940
-     */
1941
-    public function delete_by_ID($id, $allow_blocking = true)
1942
-    {
1943
-        return $this->delete(
1944
-            [
1945
-                [$this->get_primary_key_field()->get_name() => $id],
1946
-                'limit' => 1,
1947
-            ],
1948
-            $allow_blocking
1949
-        );
1950
-    }
1951
-
1952
-
1953
-    /**
1954
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1955
-     * meaning if the model has a field that indicates its been "trashed" or
1956
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1957
-     *
1958
-     * @param array   $query_params
1959
-     * @param boolean $allow_blocking
1960
-     * @return int how many rows got deleted
1961
-     * @throws EE_Error
1962
-     * @throws ReflectionException
1963
-     * @see EEM_Base::delete_permanently
1964
-     */
1965
-    public function delete($query_params, $allow_blocking = true)
1966
-    {
1967
-        return $this->delete_permanently($query_params, $allow_blocking);
1968
-    }
1969
-
1970
-
1971
-    /**
1972
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1973
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1974
-     * as archived, not actually deleted
1975
-     *
1976
-     * @param array   $query_params   @see
1977
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1978
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1979
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1980
-     *                                deletes regardless of other objects which may depend on it. Its generally
1981
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1982
-     *                                DB
1983
-     * @return int how many rows got deleted
1984
-     * @throws EE_Error
1985
-     * @throws ReflectionException
1986
-     */
1987
-    public function delete_permanently($query_params, $allow_blocking = true)
1988
-    {
1989
-        /**
1990
-         * Action called just before performing a real deletion query. You can use the
1991
-         * model and its $query_params to find exactly which items will be deleted
1992
-         *
1993
-         * @param EEM_Base $model
1994
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1995
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1996
-         *                                 to block (prevent) this deletion
1997
-         */
1998
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1999
-        // some MySQL databases may be running safe mode, which may restrict
2000
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
2001
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
2002
-        // to delete them
2003
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2004
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2005
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2006
-            $columns_and_ids_for_deleting
2007
-        );
2008
-        /**
2009
-         * Allows client code to act on the items being deleted before the query is actually executed.
2010
-         *
2011
-         * @param EEM_Base $this                            The model instance being acted on.
2012
-         * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
2013
-         * @param bool     $allow_blocking                  @see param description in method phpdoc block.
2014
-         * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
2015
-         *                                                  derived from the incoming query parameters.
2016
-         * @see details on the structure of this array in the phpdocs
2017
-         *                                                  for the `_get_ids_for_delete_method`
2018
-         *
2019
-         */
2020
-        do_action(
2021
-            'AHEE__EEM_Base__delete__before_query',
2022
-            $this,
2023
-            $query_params,
2024
-            $allow_blocking,
2025
-            $columns_and_ids_for_deleting
2026
-        );
2027
-        if ($deletion_where_query_part) {
2028
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2029
-            $table_aliases    = array_keys($this->_tables);
2030
-            $SQL              = "DELETE "
2031
-                                . implode(", ", $table_aliases)
2032
-                                . " FROM "
2033
-                                . $model_query_info->get_full_join_sql()
2034
-                                . " WHERE "
2035
-                                . $deletion_where_query_part;
2036
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2037
-        } else {
2038
-            $rows_deleted = 0;
2039
-        }
2040
-
2041
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2042
-        // there was no error with the delete query.
2043
-        if (
2044
-            $this->has_primary_key_field()
2045
-            && $rows_deleted !== false
2046
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2047
-        ) {
2048
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2049
-            foreach ($ids_for_removal as $id) {
2050
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2051
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2052
-                }
2053
-            }
2054
-
2055
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2056
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2057
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2058
-            // (although it is possible).
2059
-            // Note this can be skipped by using the provided filter and returning false.
2060
-            if (
2061
-                apply_filters(
2062
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2063
-                    ! $this instanceof EEM_Extra_Meta,
2064
-                    $this
2065
-                )
2066
-            ) {
2067
-                EEM_Extra_Meta::instance()->delete_permanently([
2068
-                                                                   0 => [
2069
-                                                                       'EXM_type' => $this->get_this_model_name(),
2070
-                                                                       'OBJ_ID'   => [
2071
-                                                                           'IN',
2072
-                                                                           $ids_for_removal,
2073
-                                                                       ],
2074
-                                                                   ],
2075
-                                                               ]);
2076
-            }
2077
-        }
2078
-
2079
-        /**
2080
-         * Action called just after performing a real deletion query. Although at this point the
2081
-         * items should have been deleted
2082
-         *
2083
-         * @param EEM_Base $model
2084
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2085
-         * @param int      $rows_deleted
2086
-         */
2087
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2088
-        return $rows_deleted;// how many supposedly got deleted
2089
-    }
2090
-
2091
-
2092
-    /**
2093
-     * Checks all the relations that throw error messages when there are blocking related objects
2094
-     * for related model objects. If there are any related model objects on those relations,
2095
-     * adds an EE_Error, and return true
2096
-     *
2097
-     * @param EE_Base_Class|int $this_model_obj_or_id
2098
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2099
-     *                                                 should be ignored when determining whether there are related
2100
-     *                                                 model objects which block this model object's deletion. Useful
2101
-     *                                                 if you know A is related to B and are considering deleting A,
2102
-     *                                                 but want to see if A has any other objects blocking its deletion
2103
-     *                                                 before removing the relation between A and B
2104
-     * @return boolean
2105
-     * @throws EE_Error
2106
-     * @throws ReflectionException
2107
-     */
2108
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2109
-    {
2110
-        // first, if $ignore_this_model_obj was supplied, get its model
2111
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2112
-            $ignored_model = $ignore_this_model_obj->get_model();
2113
-        } else {
2114
-            $ignored_model = null;
2115
-        }
2116
-        // now check all the relations of $this_model_obj_or_id and see if there
2117
-        // are any related model objects blocking it?
2118
-        $is_blocked = false;
2119
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2120
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2121
-                // if $ignore_this_model_obj was supplied, then for the query
2122
-                // on that model needs to be told to ignore $ignore_this_model_obj
2123
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2124
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, [
2125
-                        [
2126
-                            $ignored_model->get_primary_key_field()->get_name() => [
2127
-                                '!=',
2128
-                                $ignore_this_model_obj->ID(),
2129
-                            ],
2130
-                        ],
2131
-                    ]);
2132
-                } else {
2133
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2134
-                }
2135
-                if ($related_model_objects) {
2136
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2137
-                    $is_blocked = true;
2138
-                }
2139
-            }
2140
-        }
2141
-        return $is_blocked;
2142
-    }
2143
-
2144
-
2145
-    /**
2146
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2147
-     *
2148
-     * @param array $row_results_for_deleting
2149
-     * @param bool  $allow_blocking
2150
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2151
-     *                              model DOES have a primary_key_field, then the array will be a simple single
2152
-     *                              dimension array where the key is the fully qualified primary key column and the
2153
-     *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2154
-     *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2155
-     *                              be a two dimensional array where each element is a group of columns and values that
2156
-     *                              get deleted. Example: array(
2157
-     *                              0 => array(
2158
-     *                              'Term_Relationship.object_id' => 1
2159
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2160
-     *                              ),
2161
-     *                              1 => array(
2162
-     *                              'Term_Relationship.object_id' => 1
2163
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2164
-     *                              )
2165
-     *                              )
2166
-     * @throws EE_Error
2167
-     * @throws ReflectionException
2168
-     */
2169
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2170
-    {
2171
-        $ids_to_delete_indexed_by_column = [];
2172
-        if ($this->has_primary_key_field()) {
2173
-            $primary_table                   = $this->_get_main_table();
2174
-            $primary_table_pk_field          =
2175
-                $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2176
-            $other_tables                    = $this->_get_other_tables();
2177
-            $ids_to_delete_indexed_by_column = $query = [];
2178
-            foreach ($row_results_for_deleting as $item_to_delete) {
2179
-                // before we mark this item for deletion,
2180
-                // make sure there's no related entities blocking its deletion (if we're checking)
2181
-                if (
2182
-                    $allow_blocking
2183
-                    && $this->delete_is_blocked_by_related_models(
2184
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2185
-                    )
2186
-                ) {
2187
-                    continue;
2188
-                }
2189
-                // primary table deletes
2190
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2191
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2192
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2193
-                }
2194
-            }
2195
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2196
-            $fields = $this->get_combined_primary_key_fields();
2197
-            foreach ($row_results_for_deleting as $item_to_delete) {
2198
-                $ids_to_delete_indexed_by_column_for_row = [];
2199
-                foreach ($fields as $cpk_field) {
2200
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2201
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2202
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2203
-                    }
2204
-                }
2205
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2206
-            }
2207
-        } else {
2208
-            // so there's no primary key and no combined key...
2209
-            // sorry, can't help you
2210
-            throw new EE_Error(
2211
-                sprintf(
2212
-                    esc_html__(
2213
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2214
-                        "event_espresso"
2215
-                    ),
2216
-                    get_class($this)
2217
-                )
2218
-            );
2219
-        }
2220
-        return $ids_to_delete_indexed_by_column;
2221
-    }
2222
-
2223
-
2224
-    /**
2225
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2226
-     * the corresponding query_part for the query performing the delete.
2227
-     *
2228
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2229
-     * @return string
2230
-     * @throws EE_Error
2231
-     */
2232
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2233
-    {
2234
-        $query_part = '';
2235
-        if (empty($ids_to_delete_indexed_by_column)) {
2236
-            return $query_part;
2237
-        } elseif ($this->has_primary_key_field()) {
2238
-            $query = [];
2239
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2240
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2241
-            }
2242
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2243
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2244
-            $ways_to_identify_a_row = [];
2245
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2246
-                $values_for_each_combined_primary_key_for_a_row = [];
2247
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2248
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2249
-                }
2250
-                $ways_to_identify_a_row[] = '('
2251
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2252
-                                            . ')';
2253
-            }
2254
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2255
-        }
2256
-        return $query_part;
2257
-    }
2258
-
2259
-
2260
-    /**
2261
-     * Gets the model field by the fully qualified name
2262
-     *
2263
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2264
-     * @return EE_Model_Field_Base
2265
-     * @throws EE_Error
2266
-     * @throws EE_Error
2267
-     */
2268
-    public function get_field_by_column($qualified_column_name)
2269
-    {
2270
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2271
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2272
-                return $field_obj;
2273
-            }
2274
-        }
2275
-        throw new EE_Error(
2276
-            sprintf(
2277
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2278
-                $this->get_this_model_name(),
2279
-                $qualified_column_name
2280
-            )
2281
-        );
2282
-    }
2283
-
2284
-
2285
-    /**
2286
-     * Count all the rows that match criteria the model query params.
2287
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2288
-     * column
2289
-     *
2290
-     * @param array  $query_params   @see
2291
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2292
-     * @param string $field_to_count field on model to count by (not column name)
2293
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2294
-     *                               that by the setting $distinct to TRUE;
2295
-     * @return int
2296
-     * @throws EE_Error
2297
-     */
2298
-    public function count($query_params = [], $field_to_count = null, $distinct = false)
2299
-    {
2300
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2301
-        if ($field_to_count) {
2302
-            $field_obj       = $this->field_settings_for($field_to_count);
2303
-            $column_to_count = $field_obj->get_qualified_column();
2304
-        } elseif ($this->has_primary_key_field()) {
2305
-            $pk_field_obj    = $this->get_primary_key_field();
2306
-            $column_to_count = $pk_field_obj->get_qualified_column();
2307
-        } else {
2308
-            // there's no primary key
2309
-            // if we're counting distinct items, and there's no primary key,
2310
-            // we need to list out the columns for distinction;
2311
-            // otherwise we can just use star
2312
-            if ($distinct) {
2313
-                $columns_to_use = [];
2314
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2315
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2316
-                }
2317
-                $column_to_count = implode(',', $columns_to_use);
2318
-            } else {
2319
-                $column_to_count = '*';
2320
-            }
2321
-        }
2322
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2323
-        $SQL             =
2324
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2325
-        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2326
-    }
2327
-
2328
-
2329
-    /**
2330
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2331
-     *
2332
-     * @param array  $query_params @see
2333
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2334
-     * @param string $field_to_sum name of field (array key in $_fields array)
2335
-     * @return float
2336
-     * @throws EE_Error
2337
-     */
2338
-    public function sum($query_params, $field_to_sum = null)
2339
-    {
2340
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2341
-        if ($field_to_sum) {
2342
-            $field_obj = $this->field_settings_for($field_to_sum);
2343
-        } else {
2344
-            $field_obj = $this->get_primary_key_field();
2345
-        }
2346
-        $column_to_count = $field_obj->get_qualified_column();
2347
-        $SQL             =
2348
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2349
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2350
-        $data_type       = $field_obj->get_wpdb_data_type();
2351
-        if ($data_type === '%d' || $data_type === '%s') {
2352
-            return (float) $return_value;
2353
-        }
2354
-        // must be %f
2355
-        return (float) $return_value;
2356
-    }
2357
-
2358
-
2359
-    /**
2360
-     * Just calls the specified method on $wpdb with the given arguments
2361
-     * Consolidates a little extra error handling code
2362
-     *
2363
-     * @param string $wpdb_method
2364
-     * @param array  $arguments_to_provide
2365
-     * @return mixed
2366
-     * @throws EE_Error
2367
-     * @global wpdb  $wpdb
2368
-     */
2369
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2370
-    {
2371
-        // if we're in maintenance mode level 2, DON'T run any queries
2372
-        // because level 2 indicates the database needs updating and
2373
-        // is probably out of sync with the code
2374
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2375
-            throw new EE_Error(
2376
-                sprintf(
2377
-                    esc_html__(
2378
-                        "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.",
2379
-                        "event_espresso"
2380
-                    )
2381
-                )
2382
-            );
2383
-        }
2384
-        /** @type WPDB $wpdb */
2385
-        global $wpdb;
2386
-        if (! method_exists($wpdb, $wpdb_method)) {
2387
-            throw new EE_Error(
2388
-                sprintf(
2389
-                    esc_html__(
2390
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2391
-                        'event_espresso'
2392
-                    ),
2393
-                    $wpdb_method
2394
-                )
2395
-            );
2396
-        }
2397
-        if (WP_DEBUG) {
2398
-            $old_show_errors_value = $wpdb->show_errors;
2399
-            $wpdb->show_errors(false);
2400
-        }
2401
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2402
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2403
-        if (WP_DEBUG) {
2404
-            $wpdb->show_errors($old_show_errors_value);
2405
-            if (! empty($wpdb->last_error)) {
2406
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2407
-            }
2408
-            if ($result === false) {
2409
-                throw new EE_Error(
2410
-                    sprintf(
2411
-                        esc_html__(
2412
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2413
-                            'event_espresso'
2414
-                        ),
2415
-                        $wpdb_method,
2416
-                        var_export($arguments_to_provide, true)
2417
-                    )
2418
-                );
2419
-            }
2420
-        } elseif ($result === false) {
2421
-            EE_Error::add_error(
2422
-                sprintf(
2423
-                    esc_html__(
2424
-                        '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"',
2425
-                        'event_espresso'
2426
-                    ),
2427
-                    $wpdb_method,
2428
-                    var_export($arguments_to_provide, true),
2429
-                    $wpdb->last_error
2430
-                ),
2431
-                __FILE__,
2432
-                __FUNCTION__,
2433
-                __LINE__
2434
-            );
2435
-        }
2436
-        return $result;
2437
-    }
2438
-
2439
-
2440
-    /**
2441
-     * Attempts to run the indicated WPDB method with the provided arguments,
2442
-     * and if there's an error tries to verify the DB is correct. Uses
2443
-     * the static property EEM_Base::$_db_verification_level to determine whether
2444
-     * we should try to fix the EE core db, the addons, or just give up
2445
-     *
2446
-     * @param string $wpdb_method
2447
-     * @param array  $arguments_to_provide
2448
-     * @return mixed
2449
-     */
2450
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2451
-    {
2452
-        /** @type WPDB $wpdb */
2453
-        global $wpdb;
2454
-        $wpdb->last_error = null;
2455
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2456
-        // was there an error running the query? but we don't care on new activations
2457
-        // (we're going to setup the DB anyway on new activations)
2458
-        if (
2459
-            ($result === false || ! empty($wpdb->last_error))
2460
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2461
-        ) {
2462
-            switch (EEM_Base::$_db_verification_level) {
2463
-                case EEM_Base::db_verified_none:
2464
-                    // let's double-check core's DB
2465
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2466
-                    break;
2467
-                case EEM_Base::db_verified_core:
2468
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2469
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2470
-                    break;
2471
-                case EEM_Base::db_verified_addons:
2472
-                    // ummmm... you in trouble
2473
-                    return $result;
2474
-            }
2475
-            if (! empty($error_message)) {
2476
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2477
-                trigger_error($error_message);
2478
-            }
2479
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2480
-        }
2481
-        return $result;
2482
-    }
2483
-
2484
-
2485
-    /**
2486
-     * Verifies the EE core database is up-to-date and records that we've done it on
2487
-     * EEM_Base::$_db_verification_level
2488
-     *
2489
-     * @param string $wpdb_method
2490
-     * @param array  $arguments_to_provide
2491
-     * @return string
2492
-     */
2493
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2494
-    {
2495
-        /** @type WPDB $wpdb */
2496
-        global $wpdb;
2497
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2498
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2499
-        $error_message                    = sprintf(
2500
-            esc_html__(
2501
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2502
-                'event_espresso'
2503
-            ),
2504
-            $wpdb->last_error,
2505
-            $wpdb_method,
2506
-            wp_json_encode($arguments_to_provide)
2507
-        );
2508
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2509
-        return $error_message;
2510
-    }
2511
-
2512
-
2513
-    /**
2514
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2515
-     * EEM_Base::$_db_verification_level
2516
-     *
2517
-     * @param $wpdb_method
2518
-     * @param $arguments_to_provide
2519
-     * @return string
2520
-     */
2521
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2522
-    {
2523
-        /** @type WPDB $wpdb */
2524
-        global $wpdb;
2525
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2526
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2527
-        $error_message                    = sprintf(
2528
-            esc_html__(
2529
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2530
-                'event_espresso'
2531
-            ),
2532
-            $wpdb->last_error,
2533
-            $wpdb_method,
2534
-            wp_json_encode($arguments_to_provide)
2535
-        );
2536
-        EE_System::instance()->initialize_addons();
2537
-        return $error_message;
2538
-    }
2539
-
2540
-
2541
-    /**
2542
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2543
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2544
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2545
-     * ..."
2546
-     *
2547
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2548
-     * @return string
2549
-     */
2550
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2551
-    {
2552
-        return " FROM " . $model_query_info->get_full_join_sql() .
2553
-               $model_query_info->get_where_sql() .
2554
-               $model_query_info->get_group_by_sql() .
2555
-               $model_query_info->get_having_sql() .
2556
-               $model_query_info->get_order_by_sql() .
2557
-               $model_query_info->get_limit_sql();
2558
-    }
2559
-
2560
-
2561
-    /**
2562
-     * Set to easily debug the next X queries ran from this model.
2563
-     *
2564
-     * @param int $count
2565
-     */
2566
-    public function show_next_x_db_queries($count = 1)
2567
-    {
2568
-        $this->_show_next_x_db_queries = $count;
2569
-    }
2570
-
2571
-
2572
-    /**
2573
-     * @param $sql_query
2574
-     */
2575
-    public function show_db_query_if_previously_requested($sql_query)
2576
-    {
2577
-        if ($this->_show_next_x_db_queries > 0) {
2578
-            echo esc_html($sql_query);
2579
-            $this->_show_next_x_db_queries--;
2580
-        }
2581
-    }
2582
-
2583
-
2584
-    /**
2585
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2586
-     * There are the 3 cases:
2587
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2588
-     * $otherModelObject has no ID, it is first saved.
2589
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2590
-     * has no ID, it is first saved.
2591
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2592
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2593
-     * join table
2594
-     *
2595
-     * @param EE_Base_Class                     /int $thisModelObject
2596
-     * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2597
-     * @param string $relationName                     , key in EEM_Base::_relations
2598
-     *                                                 an attendee to a group, you also want to specify which role they
2599
-     *                                                 will have in that group. So you would use this parameter to
2600
-     *                                                 specify array('role-column-name'=>'role-id')
2601
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2602
-     *                                                 to for relation to methods that allow you to further specify
2603
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2604
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2605
-     *                                                 because these will be inserted in any new rows created as well.
2606
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2607
-     * @throws EE_Error
2608
-     */
2609
-    public function add_relationship_to(
2610
-        $id_or_obj,
2611
-        $other_model_id_or_obj,
2612
-        $relationName,
2613
-        $extra_join_model_fields_n_values = []
2614
-    ) {
2615
-        $relation_obj = $this->related_settings_for($relationName);
2616
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2617
-    }
2618
-
2619
-
2620
-    /**
2621
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2622
-     * There are the 3 cases:
2623
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2624
-     * error
2625
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2626
-     * an error
2627
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2628
-     *
2629
-     * @param EE_Base_Class /int $id_or_obj
2630
-     * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2631
-     * @param string $relationName key in EEM_Base::_relations
2632
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2633
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2634
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2635
-     *                             because these will be inserted in any new rows created as well.
2636
-     * @return boolean of success
2637
-     * @throws EE_Error
2638
-     */
2639
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2640
-    {
2641
-        $relation_obj = $this->related_settings_for($relationName);
2642
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2643
-    }
2644
-
2645
-
2646
-    /**
2647
-     * @param mixed  $id_or_obj
2648
-     * @param string $relationName
2649
-     * @param array  $where_query_params
2650
-     * @param EE_Base_Class[] objects to which relations were removed
2651
-     * @return EE_Base_Class[]
2652
-     * @throws EE_Error
2653
-     */
2654
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2655
-    {
2656
-        $relation_obj = $this->related_settings_for($relationName);
2657
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2658
-    }
2659
-
2660
-
2661
-    /**
2662
-     * Gets all the related items of the specified $model_name, using $query_params.
2663
-     * Note: by default, we remove the "default query params"
2664
-     * because we want to get even deleted items etc.
2665
-     *
2666
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2667
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2668
-     * @param array  $query_params @see
2669
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2670
-     * @return EE_Base_Class[]
2671
-     * @throws EE_Error
2672
-     * @throws ReflectionException
2673
-     */
2674
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2675
-    {
2676
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2677
-        $relation_settings = $this->related_settings_for($model_name);
2678
-        return $relation_settings->get_all_related($model_obj, $query_params);
2679
-    }
2680
-
2681
-
2682
-    /**
2683
-     * Deletes all the model objects across the relation indicated by $model_name
2684
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2685
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2686
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2687
-     *
2688
-     * @param EE_Base_Class|int|string $id_or_obj
2689
-     * @param string                   $model_name
2690
-     * @param array                    $query_params
2691
-     * @return int how many deleted
2692
-     * @throws EE_Error
2693
-     * @throws ReflectionException
2694
-     */
2695
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2696
-    {
2697
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2698
-        $relation_settings = $this->related_settings_for($model_name);
2699
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2700
-    }
2701
-
2702
-
2703
-    /**
2704
-     * Hard deletes all the model objects across the relation indicated by $model_name
2705
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2706
-     * the model objects can't be hard deleted because of blocking related model objects,
2707
-     * just does a soft-delete on them instead.
2708
-     *
2709
-     * @param EE_Base_Class|int|string $id_or_obj
2710
-     * @param string                   $model_name
2711
-     * @param array                    $query_params
2712
-     * @return int how many deleted
2713
-     * @throws EE_Error
2714
-     * @throws ReflectionException
2715
-     */
2716
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2717
-    {
2718
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2719
-        $relation_settings = $this->related_settings_for($model_name);
2720
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2721
-    }
2722
-
2723
-
2724
-    /**
2725
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2726
-     * unless otherwise specified in the $query_params
2727
-     *
2728
-     * @param int             /EE_Base_Class $id_or_obj
2729
-     * @param string $model_name     like 'Event', or 'Registration'
2730
-     * @param array  $query_params   @see
2731
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2732
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2733
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2734
-     *                               that by the setting $distinct to TRUE;
2735
-     * @return int
2736
-     * @throws EE_Error
2737
-     */
2738
-    public function count_related(
2739
-        $id_or_obj,
2740
-        $model_name,
2741
-        $query_params = [],
2742
-        $field_to_count = null,
2743
-        $distinct = false
2744
-    ) {
2745
-        $related_model = $this->get_related_model_obj($model_name);
2746
-        // we're just going to use the query params on the related model's normal get_all query,
2747
-        // except add a condition to say to match the current mod
2748
-        if (! isset($query_params['default_where_conditions'])) {
2749
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2750
-        }
2751
-        $this_model_name                                                 = $this->get_this_model_name();
2752
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2753
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2754
-        return $related_model->count($query_params, $field_to_count, $distinct);
2755
-    }
2756
-
2757
-
2758
-    /**
2759
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2760
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2761
-     *
2762
-     * @param int           /EE_Base_Class $id_or_obj
2763
-     * @param string $model_name   like 'Event', or 'Registration'
2764
-     * @param array  $query_params @see
2765
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2766
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2767
-     * @return float
2768
-     * @throws EE_Error
2769
-     */
2770
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2771
-    {
2772
-        $related_model = $this->get_related_model_obj($model_name);
2773
-        if (! is_array($query_params)) {
2774
-            EE_Error::doing_it_wrong(
2775
-                'EEM_Base::sum_related',
2776
-                sprintf(
2777
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2778
-                    gettype($query_params)
2779
-                ),
2780
-                '4.6.0'
2781
-            );
2782
-            $query_params = [];
2783
-        }
2784
-        // we're just going to use the query params on the related model's normal get_all query,
2785
-        // except add a condition to say to match the current mod
2786
-        if (! isset($query_params['default_where_conditions'])) {
2787
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2788
-        }
2789
-        $this_model_name                                                 = $this->get_this_model_name();
2790
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2791
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2792
-        return $related_model->sum($query_params, $field_to_sum);
2793
-    }
2794
-
2795
-
2796
-    /**
2797
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2798
-     * $modelObject
2799
-     *
2800
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2801
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2802
-     * @param array               $query_params     @see
2803
-     *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2804
-     * @return EE_Base_Class
2805
-     * @throws EE_Error
2806
-     */
2807
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2808
-    {
2809
-        $query_params['limit'] = 1;
2810
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2811
-        if ($results) {
2812
-            return array_shift($results);
2813
-        }
2814
-        return null;
2815
-    }
2816
-
2817
-
2818
-    /**
2819
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2820
-     *
2821
-     * @return string
2822
-     */
2823
-    public function get_this_model_name()
2824
-    {
2825
-        return str_replace("EEM_", "", get_class($this));
2826
-    }
2827
-
2828
-
2829
-    /**
2830
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2831
-     *
2832
-     * @return EE_Any_Foreign_Model_Name_Field
2833
-     * @throws EE_Error
2834
-     */
2835
-    public function get_field_containing_related_model_name()
2836
-    {
2837
-        foreach ($this->field_settings(true) as $field) {
2838
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2839
-                $field_with_model_name = $field;
2840
-            }
2841
-        }
2842
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2843
-            throw new EE_Error(
2844
-                sprintf(
2845
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2846
-                    $this->get_this_model_name()
2847
-                )
2848
-            );
2849
-        }
2850
-        return $field_with_model_name;
2851
-    }
2852
-
2853
-
2854
-    /**
2855
-     * Inserts a new entry into the database, for each table.
2856
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2857
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2858
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2859
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2860
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2861
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2862
-     *
2863
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2864
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2865
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2866
-     *                              of EEM_Base)
2867
-     * @return int|string new primary key on main table that got inserted
2868
-     * @throws EE_Error
2869
-     */
2870
-    public function insert($field_n_values)
2871
-    {
2872
-        /**
2873
-         * Filters the fields and their values before inserting an item using the models
2874
-         *
2875
-         * @param array    $fields_n_values keys are the fields and values are their new values
2876
-         * @param EEM_Base $model           the model used
2877
-         */
2878
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2879
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2880
-            $main_table = $this->_get_main_table();
2881
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2882
-            if ($new_id !== false) {
2883
-                foreach ($this->_get_other_tables() as $other_table) {
2884
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2885
-                }
2886
-            }
2887
-            /**
2888
-             * Done just after attempting to insert a new model object
2889
-             *
2890
-             * @param EEM_Base $model           used
2891
-             * @param array    $fields_n_values fields and their values
2892
-             * @param int|string the              ID of the newly-inserted model object
2893
-             */
2894
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2895
-            return $new_id;
2896
-        }
2897
-        return false;
2898
-    }
2899
-
2900
-
2901
-    /**
2902
-     * Checks that the result would satisfy the unique indexes on this model
2903
-     *
2904
-     * @param array  $field_n_values
2905
-     * @param string $action
2906
-     * @return boolean
2907
-     * @throws EE_Error
2908
-     */
2909
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2910
-    {
2911
-        foreach ($this->unique_indexes() as $index_name => $index) {
2912
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2913
-            if ($this->exists([$uniqueness_where_params])) {
2914
-                EE_Error::add_error(
2915
-                    sprintf(
2916
-                        esc_html__(
2917
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2918
-                            "event_espresso"
2919
-                        ),
2920
-                        $action,
2921
-                        $this->_get_class_name(),
2922
-                        $index_name,
2923
-                        implode(",", $index->field_names()),
2924
-                        http_build_query($uniqueness_where_params)
2925
-                    ),
2926
-                    __FILE__,
2927
-                    __FUNCTION__,
2928
-                    __LINE__
2929
-                );
2930
-                return false;
2931
-            }
2932
-        }
2933
-        return true;
2934
-    }
2935
-
2936
-
2937
-    /**
2938
-     * Checks the database for an item that conflicts (ie, if this item were
2939
-     * saved to the DB would break some uniqueness requirement, like a primary key
2940
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2941
-     * can be either an EE_Base_Class or an array of fields n values
2942
-     *
2943
-     * @param EE_Base_Class|array $obj_or_fields_array
2944
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2945
-     *                                                 when looking for conflicts
2946
-     *                                                 (ie, if false, we ignore the model object's primary key
2947
-     *                                                 when finding "conflicts". If true, it's also considered).
2948
-     *                                                 Only works for INT primary key,
2949
-     *                                                 STRING primary keys cannot be ignored
2950
-     * @return EE_Base_Class|array
2951
-     * @throws EE_Error
2952
-     * @throws ReflectionException
2953
-     */
2954
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2955
-    {
2956
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2957
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2958
-        } elseif (is_array($obj_or_fields_array)) {
2959
-            $fields_n_values = $obj_or_fields_array;
2960
-        } else {
2961
-            throw new EE_Error(
2962
-                sprintf(
2963
-                    esc_html__(
2964
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2965
-                        "event_espresso"
2966
-                    ),
2967
-                    get_class($this),
2968
-                    $obj_or_fields_array
2969
-                )
2970
-            );
2971
-        }
2972
-        $query_params = [];
2973
-        if (
2974
-            $this->has_primary_key_field()
2975
-            && ($include_primary_key
2976
-                || $this->get_primary_key_field()
2977
-                   instanceof
2978
-                   EE_Primary_Key_String_Field)
2979
-            && isset($fields_n_values[ $this->primary_key_name() ])
2980
-        ) {
2981
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2982
-        }
2983
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2984
-            $uniqueness_where_params                              =
2985
-                array_intersect_key($fields_n_values, $unique_index->fields());
2986
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2987
-        }
2988
-        // if there is nothing to base this search on, then we shouldn't find anything
2989
-        if (empty($query_params)) {
2990
-            return [];
2991
-        }
2992
-        return $this->get_one($query_params);
2993
-    }
2994
-
2995
-
2996
-    /**
2997
-     * Like count, but is optimized and returns a boolean instead of an int
2998
-     *
2999
-     * @param array $query_params
3000
-     * @return boolean
3001
-     * @throws EE_Error
3002
-     */
3003
-    public function exists($query_params)
3004
-    {
3005
-        $query_params['limit'] = 1;
3006
-        return $this->count($query_params) > 0;
3007
-    }
3008
-
3009
-
3010
-    /**
3011
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
3012
-     *
3013
-     * @param int|string $id
3014
-     * @return boolean
3015
-     * @throws EE_Error
3016
-     */
3017
-    public function exists_by_ID($id)
3018
-    {
3019
-        return $this->exists(
3020
-            [
3021
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3022
-                [
3023
-                    $this->primary_key_name() => $id,
3024
-                ],
3025
-            ]
3026
-        );
3027
-    }
3028
-
3029
-
3030
-    /**
3031
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3032
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3033
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3034
-     * on the main table)
3035
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3036
-     * cases where we want to call it directly rather than via insert().
3037
-     *
3038
-     * @access   protected
3039
-     * @param EE_Table_Base $table
3040
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3041
-     *                                       float
3042
-     * @param int           $new_id          for now we assume only int keys
3043
-     * @return int ID of new row inserted, or FALSE on failure
3044
-     * @throws EE_Error
3045
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3046
-     */
3047
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3048
-    {
3049
-        global $wpdb;
3050
-        $insertion_col_n_values = [];
3051
-        $format_for_insertion   = [];
3052
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3053
-        foreach ($fields_on_table as $field_name => $field_obj) {
3054
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3055
-            if ($field_obj->is_auto_increment()) {
3056
-                continue;
3057
-            }
3058
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3059
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3060
-            if ($prepared_value !== null) {
3061
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3062
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3063
-            }
3064
-        }
3065
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3066
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3067
-            // so add the fk to the main table as a column
3068
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3069
-            $format_for_insertion[]                              =
3070
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3071
-        }
3072
-
3073
-        // insert the new entry
3074
-        $result = $this->_do_wpdb_query(
3075
-            'insert',
3076
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3077
-        );
3078
-        if ($result === false) {
3079
-            return false;
3080
-        }
3081
-        // ok, now what do we return for the ID of the newly-inserted thing?
3082
-        if ($this->has_primary_key_field()) {
3083
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3084
-                return $wpdb->insert_id;
3085
-            }
3086
-            // it's not an auto-increment primary key, so
3087
-            // it must have been supplied
3088
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3089
-        }
3090
-        // we can't return a  primary key because there is none. instead return
3091
-        // a unique string indicating this model
3092
-        return $this->get_index_primary_key_string($fields_n_values);
3093
-    }
3094
-
3095
-
3096
-    /**
3097
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3098
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3099
-     * and there is no default, we pass it along. WPDB will take care of it)
3100
-     *
3101
-     * @param EE_Model_Field_Base $field_obj
3102
-     * @param array               $fields_n_values
3103
-     * @return mixed string|int|float depending on what the table column will be expecting
3104
-     * @throws EE_Error
3105
-     */
3106
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3107
-    {
3108
-        $field_name = $field_obj->get_name();
3109
-        // if this field doesn't allow nullable, don't allow it
3110
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3111
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3112
-        }
3113
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3114
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3115
-    }
3116
-
3117
-
3118
-    /**
3119
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3120
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3121
-     * the field's prepare_for_set() method.
3122
-     *
3123
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3124
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3125
-     *                                   top of file)
3126
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3127
-     *                                   $value is a custom selection
3128
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3129
-     */
3130
-    private function _prepare_value_for_use_in_db($value, $field)
3131
-    {
3132
-        if ($field instanceof EE_Model_Field_Base) {
3133
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3134
-            switch ($this->_values_already_prepared_by_model_object) {
3135
-                /** @noinspection PhpMissingBreakStatementInspection */
3136
-                case self::not_prepared_by_model_object:
3137
-                    $value = $field->prepare_for_set($value);
3138
-                // purposefully left out "return"
3139
-                // no break
3140
-                case self::prepared_by_model_object:
3141
-                    /** @noinspection SuspiciousAssignmentsInspection */
3142
-                    $value = $field->prepare_for_use_in_db($value);
3143
-                // no break
3144
-                case self::prepared_for_use_in_db:
3145
-                    // leave the value alone
3146
-            }
3147
-            // phpcs:enable
3148
-        }
3149
-        return $value;
3150
-    }
3151
-
3152
-
3153
-    /**
3154
-     * Returns the main table on this model
3155
-     *
3156
-     * @return EE_Primary_Table
3157
-     * @throws EE_Error
3158
-     */
3159
-    protected function _get_main_table()
3160
-    {
3161
-        foreach ($this->_tables as $table) {
3162
-            if ($table instanceof EE_Primary_Table) {
3163
-                return $table;
3164
-            }
3165
-        }
3166
-        throw new EE_Error(
3167
-            sprintf(
3168
-                esc_html__(
3169
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3170
-                    'event_espresso'
3171
-                ),
3172
-                get_class($this)
3173
-            )
3174
-        );
3175
-    }
3176
-
3177
-
3178
-    /**
3179
-     * table
3180
-     * returns EE_Primary_Table table name
3181
-     *
3182
-     * @return string
3183
-     * @throws EE_Error
3184
-     */
3185
-    public function table()
3186
-    {
3187
-        return $this->_get_main_table()->get_table_name();
3188
-    }
3189
-
3190
-
3191
-    /**
3192
-     * table
3193
-     * returns first EE_Secondary_Table table name
3194
-     *
3195
-     * @return string
3196
-     */
3197
-    public function second_table()
3198
-    {
3199
-        // grab second table from tables array
3200
-        $second_table = end($this->_tables);
3201
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3202
-    }
3203
-
3204
-
3205
-    /**
3206
-     * get_table_obj_by_alias
3207
-     * returns table name given it's alias
3208
-     *
3209
-     * @param string $table_alias
3210
-     * @return EE_Primary_Table | EE_Secondary_Table
3211
-     */
3212
-    public function get_table_obj_by_alias($table_alias = '')
3213
-    {
3214
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3215
-    }
3216
-
3217
-
3218
-    /**
3219
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3220
-     *
3221
-     * @return EE_Secondary_Table[]
3222
-     */
3223
-    protected function _get_other_tables()
3224
-    {
3225
-        $other_tables = [];
3226
-        foreach ($this->_tables as $table_alias => $table) {
3227
-            if ($table instanceof EE_Secondary_Table) {
3228
-                $other_tables[ $table_alias ] = $table;
3229
-            }
3230
-        }
3231
-        return $other_tables;
3232
-    }
3233
-
3234
-
3235
-    /**
3236
-     * Finds all the fields that correspond to the given table
3237
-     *
3238
-     * @param string $table_alias , array key in EEM_Base::_tables
3239
-     * @return EE_Model_Field_Base[]
3240
-     */
3241
-    public function _get_fields_for_table($table_alias)
3242
-    {
3243
-        return $this->_fields[ $table_alias ];
3244
-    }
3245
-
3246
-
3247
-    /**
3248
-     * Recurses through all the where parameters, and finds all the related models we'll need
3249
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3250
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3251
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3252
-     * related Registration, Transaction, and Payment models.
3253
-     *
3254
-     * @param array $query_params @see
3255
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3256
-     * @return EE_Model_Query_Info_Carrier
3257
-     * @throws EE_Error
3258
-     */
3259
-    public function _extract_related_models_from_query($query_params)
3260
-    {
3261
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3262
-        if (array_key_exists(0, $query_params)) {
3263
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3264
-        }
3265
-        if (array_key_exists('group_by', $query_params)) {
3266
-            if (is_array($query_params['group_by'])) {
3267
-                $this->_extract_related_models_from_sub_params_array_values(
3268
-                    $query_params['group_by'],
3269
-                    $query_info_carrier,
3270
-                    'group_by'
3271
-                );
3272
-            } elseif (! empty($query_params['group_by'])) {
3273
-                $this->_extract_related_model_info_from_query_param(
3274
-                    $query_params['group_by'],
3275
-                    $query_info_carrier,
3276
-                    'group_by'
3277
-                );
3278
-            }
3279
-        }
3280
-        if (array_key_exists('having', $query_params)) {
3281
-            $this->_extract_related_models_from_sub_params_array_keys(
3282
-                $query_params[0],
3283
-                $query_info_carrier,
3284
-                'having'
3285
-            );
3286
-        }
3287
-        if (array_key_exists('order_by', $query_params)) {
3288
-            if (is_array($query_params['order_by'])) {
3289
-                $this->_extract_related_models_from_sub_params_array_keys(
3290
-                    $query_params['order_by'],
3291
-                    $query_info_carrier,
3292
-                    'order_by'
3293
-                );
3294
-            } elseif (! empty($query_params['order_by'])) {
3295
-                $this->_extract_related_model_info_from_query_param(
3296
-                    $query_params['order_by'],
3297
-                    $query_info_carrier,
3298
-                    'order_by'
3299
-                );
3300
-            }
3301
-        }
3302
-        if (array_key_exists('force_join', $query_params)) {
3303
-            $this->_extract_related_models_from_sub_params_array_values(
3304
-                $query_params['force_join'],
3305
-                $query_info_carrier,
3306
-                'force_join'
3307
-            );
3308
-        }
3309
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3310
-        return $query_info_carrier;
3311
-    }
3312
-
3313
-
3314
-    /**
3315
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3316
-     *
3317
-     * @param array                       $sub_query_params @see
3318
-     *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3319
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3320
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3321
-     * @return EE_Model_Query_Info_Carrier
3322
-     * @throws EE_Error
3323
-     */
3324
-    private function _extract_related_models_from_sub_params_array_keys(
3325
-        $sub_query_params,
3326
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3327
-        $query_param_type
3328
-    ) {
3329
-        if (! empty($sub_query_params)) {
3330
-            $sub_query_params = (array) $sub_query_params;
3331
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3332
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3333
-                $this->_extract_related_model_info_from_query_param(
3334
-                    $param,
3335
-                    $model_query_info_carrier,
3336
-                    $query_param_type
3337
-                );
3338
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3339
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3340
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3341
-                // of array('Registration.TXN_ID'=>23)
3342
-                $query_param_sans_stars =
3343
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3344
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3345
-                    if (! is_array($possibly_array_of_params)) {
3346
-                        throw new EE_Error(
3347
-                            sprintf(
3348
-                                esc_html__(
3349
-                                    "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'))",
3350
-                                    "event_espresso"
3351
-                                ),
3352
-                                $param,
3353
-                                $possibly_array_of_params
3354
-                            )
3355
-                        );
3356
-                    }
3357
-                    $this->_extract_related_models_from_sub_params_array_keys(
3358
-                        $possibly_array_of_params,
3359
-                        $model_query_info_carrier,
3360
-                        $query_param_type
3361
-                    );
3362
-                } elseif (
3363
-                    $query_param_type === 0 // ie WHERE
3364
-                    && is_array($possibly_array_of_params)
3365
-                    && isset($possibly_array_of_params[2])
3366
-                    && $possibly_array_of_params[2] == true
3367
-                ) {
3368
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3369
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3370
-                    // from which we should extract query parameters!
3371
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3372
-                        throw new EE_Error(
3373
-                            sprintf(
3374
-                                esc_html__(
3375
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3376
-                                    "event_espresso"
3377
-                                ),
3378
-                                $query_param_type,
3379
-                                implode(",", $possibly_array_of_params)
3380
-                            )
3381
-                        );
3382
-                    }
3383
-                    $this->_extract_related_model_info_from_query_param(
3384
-                        $possibly_array_of_params[1],
3385
-                        $model_query_info_carrier,
3386
-                        $query_param_type
3387
-                    );
3388
-                }
3389
-            }
3390
-        }
3391
-        return $model_query_info_carrier;
3392
-    }
3393
-
3394
-
3395
-    /**
3396
-     * For extracting related models from forced_joins, where the array values contain the info about what
3397
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3398
-     *
3399
-     * @param array                       $sub_query_params @see
3400
-     *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3401
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3402
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3403
-     * @return EE_Model_Query_Info_Carrier
3404
-     * @throws EE_Error
3405
-     */
3406
-    private function _extract_related_models_from_sub_params_array_values(
3407
-        $sub_query_params,
3408
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3409
-        $query_param_type
3410
-    ) {
3411
-        if (! empty($sub_query_params)) {
3412
-            if (! is_array($sub_query_params)) {
3413
-                throw new EE_Error(
3414
-                    sprintf(
3415
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3416
-                        $sub_query_params
3417
-                    )
3418
-                );
3419
-            }
3420
-            foreach ($sub_query_params as $param) {
3421
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3422
-                $this->_extract_related_model_info_from_query_param(
3423
-                    $param,
3424
-                    $model_query_info_carrier,
3425
-                    $query_param_type
3426
-                );
3427
-            }
3428
-        }
3429
-        return $model_query_info_carrier;
3430
-    }
3431
-
3432
-
3433
-    /**
3434
-     * Extract all the query parts from  model query params
3435
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3436
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3437
-     * but use them in a different order. Eg, we need to know what models we are querying
3438
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3439
-     * other models before we can finalize the where clause SQL.
3440
-     *
3441
-     * @param array $query_params @see
3442
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3443
-     * @return EE_Model_Query_Info_Carrier
3444
-     * @throws EE_Error
3445
-     * @throws ModelConfigurationException*@throws ReflectionException
3446
-     * @throws ReflectionException
3447
-     */
3448
-    public function _create_model_query_info_carrier($query_params)
3449
-    {
3450
-        if (! is_array($query_params)) {
3451
-            EE_Error::doing_it_wrong(
3452
-                'EEM_Base::_create_model_query_info_carrier',
3453
-                sprintf(
3454
-                    esc_html__(
3455
-                        '$query_params should be an array, you passed a variable of type %s',
3456
-                        'event_espresso'
3457
-                    ),
3458
-                    gettype($query_params)
3459
-                ),
3460
-                '4.6.0'
3461
-            );
3462
-            $query_params = [];
3463
-        }
3464
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3465
-        // first check if we should alter the query to account for caps or not
3466
-        // because the caps might require us to do extra joins
3467
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3468
-            $query_params[0] = array_replace_recursive(
3469
-                $query_params[0],
3470
-                $this->caps_where_conditions($query_params['caps'])
3471
-            );
3472
-        }
3473
-
3474
-        // check if we should alter the query to remove data related to protected
3475
-        // custom post types
3476
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3477
-            $where_param_key_for_password = $this->modelChainAndPassword();
3478
-            // only include if related to a cpt where no password has been set
3479
-            $query_params[0]['OR*nopassword'] = [
3480
-                $where_param_key_for_password       => '',
3481
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3482
-            ];
3483
-        }
3484
-        $query_object = $this->_extract_related_models_from_query($query_params);
3485
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3486
-        foreach ($query_params[0] as $key => $value) {
3487
-            if (is_int($key)) {
3488
-                throw new EE_Error(
3489
-                    sprintf(
3490
-                        esc_html__(
3491
-                            "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.",
3492
-                            "event_espresso"
3493
-                        ),
3494
-                        $key,
3495
-                        var_export($value, true),
3496
-                        var_export($query_params, true),
3497
-                        get_class($this)
3498
-                    )
3499
-                );
3500
-            }
3501
-        }
3502
-        if (
3503
-            array_key_exists('default_where_conditions', $query_params)
3504
-            && ! empty($query_params['default_where_conditions'])
3505
-        ) {
3506
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3507
-        } else {
3508
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3509
-        }
3510
-        $query_params[0] = array_merge(
3511
-            $this->_get_default_where_conditions_for_models_in_query(
3512
-                $query_object,
3513
-                $use_default_where_conditions,
3514
-                $query_params[0]
3515
-            ),
3516
-            $query_params[0]
3517
-        );
3518
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3519
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3520
-        // So we need to setup a subquery and use that for the main join.
3521
-        // Note for now this only works on the primary table for the model.
3522
-        // So for instance, you could set the limit array like this:
3523
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3524
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3525
-            $query_object->set_main_model_join_sql(
3526
-                $this->_construct_limit_join_select(
3527
-                    $query_params['on_join_limit'][0],
3528
-                    $query_params['on_join_limit'][1]
3529
-                )
3530
-            );
3531
-        }
3532
-        // set limit
3533
-        if (array_key_exists('limit', $query_params)) {
3534
-            if (is_array($query_params['limit'])) {
3535
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3536
-                    $e = sprintf(
3537
-                        esc_html__(
3538
-                            "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)",
3539
-                            "event_espresso"
3540
-                        ),
3541
-                        http_build_query($query_params['limit'])
3542
-                    );
3543
-                    throw new EE_Error($e . "|" . $e);
3544
-                }
3545
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3546
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3547
-            } elseif (! empty($query_params['limit'])) {
3548
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3549
-            }
3550
-        }
3551
-        // set order by
3552
-        if (array_key_exists('order_by', $query_params)) {
3553
-            if (is_array($query_params['order_by'])) {
3554
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3555
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3556
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3557
-                if (array_key_exists('order', $query_params)) {
3558
-                    throw new EE_Error(
3559
-                        sprintf(
3560
-                            esc_html__(
3561
-                                "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 ",
3562
-                                "event_espresso"
3563
-                            ),
3564
-                            get_class($this),
3565
-                            implode(", ", array_keys($query_params['order_by'])),
3566
-                            implode(", ", $query_params['order_by']),
3567
-                            $query_params['order']
3568
-                        )
3569
-                    );
3570
-                }
3571
-                $this->_extract_related_models_from_sub_params_array_keys(
3572
-                    $query_params['order_by'],
3573
-                    $query_object,
3574
-                    'order_by'
3575
-                );
3576
-                // assume it's an array of fields to order by
3577
-                $order_array = [];
3578
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3579
-                    $order         = $this->_extract_order($order);
3580
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3581
-                }
3582
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3583
-            } elseif (! empty($query_params['order_by'])) {
3584
-                $this->_extract_related_model_info_from_query_param(
3585
-                    $query_params['order_by'],
3586
-                    $query_object,
3587
-                    'order',
3588
-                    $query_params['order_by']
3589
-                );
3590
-                $order = isset($query_params['order'])
3591
-                    ? $this->_extract_order($query_params['order'])
3592
-                    : 'DESC';
3593
-                $query_object->set_order_by_sql(
3594
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3595
-                );
3596
-            }
3597
-        }
3598
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3599
-        if (
3600
-            ! array_key_exists('order_by', $query_params)
3601
-            && array_key_exists('order', $query_params)
3602
-            && ! empty($query_params['order'])
3603
-        ) {
3604
-            $pk_field = $this->get_primary_key_field();
3605
-            $order    = $this->_extract_order($query_params['order']);
3606
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3607
-        }
3608
-        // set group by
3609
-        if (array_key_exists('group_by', $query_params)) {
3610
-            if (is_array($query_params['group_by'])) {
3611
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3612
-                $group_by_array = [];
3613
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3614
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3615
-                }
3616
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3617
-            } elseif (! empty($query_params['group_by'])) {
3618
-                $query_object->set_group_by_sql(
3619
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3620
-                );
3621
-            }
3622
-        }
3623
-        // set having
3624
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3625
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3626
-        }
3627
-        // now, just verify they didn't pass anything wack
3628
-        foreach ($query_params as $query_key => $query_value) {
3629
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3630
-                throw new EE_Error(
3631
-                    sprintf(
3632
-                        esc_html__(
3633
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3634
-                            'event_espresso'
3635
-                        ),
3636
-                        $query_key,
3637
-                        get_class($this),
3638
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3639
-                        implode(',', $this->_allowed_query_params)
3640
-                    )
3641
-                );
3642
-            }
3643
-        }
3644
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3645
-        if (empty($main_model_join_sql)) {
3646
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3647
-        }
3648
-        return $query_object;
3649
-    }
3650
-
3651
-
3652
-    /**
3653
-     * Gets the where conditions that should be imposed on the query based on the
3654
-     * context (eg reading frontend, backend, edit or delete).
3655
-     *
3656
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3657
-     * @return array @see
3658
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3659
-     * @throws EE_Error
3660
-     */
3661
-    public function caps_where_conditions($context = self::caps_read)
3662
-    {
3663
-        EEM_Base::verify_is_valid_cap_context($context);
3664
-        $cap_where_conditions = [];
3665
-        $cap_restrictions     = $this->caps_missing($context);
3666
-        /**
3667
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3668
-         */
3669
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3670
-            $cap_where_conditions = array_replace_recursive(
3671
-                $cap_where_conditions,
3672
-                $restriction_if_no_cap->get_default_where_conditions()
3673
-            );
3674
-        }
3675
-        return apply_filters(
3676
-            'FHEE__EEM_Base__caps_where_conditions__return',
3677
-            $cap_where_conditions,
3678
-            $this,
3679
-            $context,
3680
-            $cap_restrictions
3681
-        );
3682
-    }
3683
-
3684
-
3685
-    /**
3686
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3687
-     * otherwise throws an exception
3688
-     *
3689
-     * @param string $should_be_order_string
3690
-     * @return string either ASC, asc, DESC or desc
3691
-     * @throws EE_Error
3692
-     */
3693
-    private function _extract_order($should_be_order_string)
3694
-    {
3695
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3696
-            return $should_be_order_string;
3697
-        }
3698
-        throw new EE_Error(
3699
-            sprintf(
3700
-                esc_html__(
3701
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3702
-                    "event_espresso"
3703
-                ),
3704
-                get_class($this),
3705
-                $should_be_order_string
3706
-            )
3707
-        );
3708
-    }
3709
-
3710
-
3711
-    /**
3712
-     * Looks at all the models which are included in this query, and asks each
3713
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3714
-     * so they can be merged
3715
-     *
3716
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3717
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3718
-     *                                                                  'none' means NO default where conditions will
3719
-     *                                                                  be used AT ALL during this query.
3720
-     *                                                                  'other_models_only' means default where
3721
-     *                                                                  conditions from other models will be used, but
3722
-     *                                                                  not for this primary model. 'all', the default,
3723
-     *                                                                  means default where conditions will apply as
3724
-     *                                                                  normal
3725
-     * @param array                       $where_query_params           @see
3726
-     *                                                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3727
-     * @throws EE_Error
3728
-     */
3729
-    private function _get_default_where_conditions_for_models_in_query(
3730
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3731
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3732
-        $where_query_params = []
3733
-    ) {
3734
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3735
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3736
-            throw new EE_Error(
3737
-                sprintf(
3738
-                    esc_html__(
3739
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3740
-                        "event_espresso"
3741
-                    ),
3742
-                    $use_default_where_conditions,
3743
-                    implode(", ", $allowed_used_default_where_conditions_values)
3744
-                )
3745
-            );
3746
-        }
3747
-        $universal_query_params = [];
3748
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3749
-            $universal_query_params = $this->_get_default_where_conditions();
3750
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3751
-            $universal_query_params = $this->_get_minimum_where_conditions();
3752
-        }
3753
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3754
-            $related_model = $this->get_related_model_obj($model_name);
3755
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3756
-                $related_model_universal_where_params =
3757
-                    $related_model->_get_default_where_conditions($model_relation_path);
3758
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3759
-                $related_model_universal_where_params =
3760
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3761
-            } else {
3762
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3763
-                continue;
3764
-            }
3765
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3766
-                $related_model_universal_where_params,
3767
-                $where_query_params,
3768
-                $related_model,
3769
-                $model_relation_path
3770
-            );
3771
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3772
-                $universal_query_params,
3773
-                $overrides
3774
-            );
3775
-        }
3776
-        return $universal_query_params;
3777
-    }
3778
-
3779
-
3780
-    /**
3781
-     * Determines whether or not we should use default where conditions for the model in question
3782
-     * (this model, or other related models).
3783
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3784
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3785
-     * We should use default where conditions on related models when they requested to use default where conditions
3786
-     * on all models, or specifically just on other related models
3787
-     *
3788
-     * @param      $default_where_conditions_value
3789
-     * @param bool $for_this_model false means this is for OTHER related models
3790
-     * @return bool
3791
-     */
3792
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3793
-    {
3794
-        return (
3795
-                   $for_this_model
3796
-                   && in_array(
3797
-                       $default_where_conditions_value,
3798
-                       [
3799
-                           EEM_Base::default_where_conditions_all,
3800
-                           EEM_Base::default_where_conditions_this_only,
3801
-                           EEM_Base::default_where_conditions_minimum_others,
3802
-                       ],
3803
-                       true
3804
-                   )
3805
-               )
3806
-               || (
3807
-                   ! $for_this_model
3808
-                   && in_array(
3809
-                       $default_where_conditions_value,
3810
-                       [
3811
-                           EEM_Base::default_where_conditions_all,
3812
-                           EEM_Base::default_where_conditions_others_only,
3813
-                       ],
3814
-                       true
3815
-                   )
3816
-               );
3817
-    }
3818
-
3819
-
3820
-    /**
3821
-     * Determines whether or not we should use default minimum conditions for the model in question
3822
-     * (this model, or other related models).
3823
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3824
-     * where conditions.
3825
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3826
-     * on this model or others
3827
-     *
3828
-     * @param      $default_where_conditions_value
3829
-     * @param bool $for_this_model false means this is for OTHER related models
3830
-     * @return bool
3831
-     */
3832
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3833
-    {
3834
-        return (
3835
-                   $for_this_model
3836
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3837
-               )
3838
-               || (
3839
-                   ! $for_this_model
3840
-                   && in_array(
3841
-                       $default_where_conditions_value,
3842
-                       [
3843
-                           EEM_Base::default_where_conditions_minimum_others,
3844
-                           EEM_Base::default_where_conditions_minimum_all,
3845
-                       ],
3846
-                       true
3847
-                   )
3848
-               );
3849
-    }
3850
-
3851
-
3852
-    /**
3853
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3854
-     * then we also add a special where condition which allows for that model's primary key
3855
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3856
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3857
-     *
3858
-     * @param array    $default_where_conditions
3859
-     * @param array    $provided_where_conditions
3860
-     * @param EEM_Base $model
3861
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3862
-     * @return array @see
3863
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3864
-     * @throws EE_Error
3865
-     */
3866
-    private function _override_defaults_or_make_null_friendly(
3867
-        $default_where_conditions,
3868
-        $provided_where_conditions,
3869
-        $model,
3870
-        $model_relation_path
3871
-    ) {
3872
-        $null_friendly_where_conditions = [];
3873
-        $none_overridden                = true;
3874
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3875
-        foreach ($default_where_conditions as $key => $val) {
3876
-            if (isset($provided_where_conditions[ $key ])) {
3877
-                $none_overridden = false;
3878
-            } else {
3879
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3880
-            }
3881
-        }
3882
-        if ($none_overridden && $default_where_conditions) {
3883
-            if ($model->has_primary_key_field()) {
3884
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3885
-                                                                                   . "."
3886
-                                                                                   . $model->primary_key_name() ] =
3887
-                    ['IS NULL'];
3888
-            }/*else{
40
+	/**
41
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
42
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
43
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
44
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
45
+	 *
46
+	 * @var boolean
47
+	 */
48
+	private $_values_already_prepared_by_model_object = 0;
49
+
50
+	/**
51
+	 * when $_values_already_prepared_by_model_object equals this, we assume
52
+	 * the data is just like form input that needs to have the model fields'
53
+	 * prepare_for_set and prepare_for_use_in_db called on it
54
+	 */
55
+	const not_prepared_by_model_object = 0;
56
+
57
+	/**
58
+	 * when $_values_already_prepared_by_model_object equals this, we
59
+	 * assume this value is coming from a model object and doesn't need to have
60
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
61
+	 */
62
+	const prepared_by_model_object = 1;
63
+
64
+	/**
65
+	 * when $_values_already_prepared_by_model_object equals this, we assume
66
+	 * the values are already to be used in the database (ie no processing is done
67
+	 * on them by the model's fields)
68
+	 */
69
+	const prepared_for_use_in_db = 2;
70
+
71
+
72
+	protected $singular_item = 'Item';
73
+
74
+	protected $plural_item   = 'Items';
75
+
76
+	/**
77
+	 * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
78
+	 */
79
+	protected $_tables;
80
+
81
+	/**
82
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
83
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
84
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
85
+	 *
86
+	 * @var EE_Model_Field_Base[][] $_fields
87
+	 */
88
+	protected $_fields;
89
+
90
+	/**
91
+	 * array of different kinds of relations
92
+	 *
93
+	 * @var EE_Model_Relation_Base[] $_model_relations
94
+	 */
95
+	protected $_model_relations = [];
96
+
97
+	/**
98
+	 * @var EE_Index[] $_indexes
99
+	 */
100
+	protected $_indexes = [];
101
+
102
+	/**
103
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
104
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
105
+	 * by setting the same columns as used in these queries in the query yourself.
106
+	 *
107
+	 * @var EE_Default_Where_Conditions
108
+	 */
109
+	protected $_default_where_conditions_strategy;
110
+
111
+	/**
112
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
113
+	 * This is particularly useful when you want something between 'none' and 'default'
114
+	 *
115
+	 * @var EE_Default_Where_Conditions
116
+	 */
117
+	protected $_minimum_where_conditions_strategy;
118
+
119
+	/**
120
+	 * String describing how to find the "owner" of this model's objects.
121
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
122
+	 * But when there isn't, this indicates which related model, or transiently-related model,
123
+	 * has the foreign key to the wp_users table.
124
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
125
+	 * related to events, and events have a foreign key to wp_users.
126
+	 * On EEM_Transaction, this would be 'Transaction.Event'
127
+	 *
128
+	 * @var string
129
+	 */
130
+	protected $_model_chain_to_wp_user = '';
131
+
132
+	/**
133
+	 * String describing how to find the model with a password controlling access to this model. This property has the
134
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
135
+	 * This value is the path of models to follow to arrive at the model with the password field.
136
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
137
+	 * model with a password that should affect reading this on the front-end.
138
+	 * Eg this is an empty string for the Event model because it has a password.
139
+	 * This is null for the Registration model, because its event's password has no bearing on whether
140
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
141
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
142
+	 * should hide tickets for datetimes for events that have a password set.
143
+	 *
144
+	 * @var string |null
145
+	 */
146
+	protected $model_chain_to_password = null;
147
+
148
+	/**
149
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
150
+	 * don't need it (particularly CPT models)
151
+	 *
152
+	 * @var bool
153
+	 */
154
+	protected $_ignore_where_strategy = false;
155
+
156
+	/**
157
+	 * String used in caps relating to this model. Eg, if the caps relating to this
158
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
159
+	 *
160
+	 * @var string. If null it hasn't been initialized yet. If false then we
161
+	 * have indicated capabilities don't apply to this
162
+	 */
163
+	protected $_caps_slug = null;
164
+
165
+	/**
166
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
167
+	 * and next-level keys are capability names, and each's value is a
168
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
169
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
170
+	 * and then each capability in the corresponding sub-array that they're missing
171
+	 * adds the where conditions onto the query.
172
+	 *
173
+	 * @var array
174
+	 */
175
+	protected $_cap_restrictions = [
176
+		self::caps_read       => [],
177
+		self::caps_read_admin => [],
178
+		self::caps_edit       => [],
179
+		self::caps_delete     => [],
180
+	];
181
+
182
+	/**
183
+	 * Array defining which cap restriction generators to use to create default
184
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
185
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
186
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
187
+	 * automatically set this to false (not just null).
188
+	 *
189
+	 * @var EE_Restriction_Generator_Base[]
190
+	 */
191
+	protected $_cap_restriction_generators = [];
192
+
193
+	/**
194
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
195
+	 */
196
+	const caps_read       = 'read';
197
+
198
+	const caps_read_admin = 'read_admin';
199
+
200
+	const caps_edit       = 'edit';
201
+
202
+	const caps_delete     = 'delete';
203
+
204
+	/**
205
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
206
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
207
+	 * maps to 'read' because when looking for relevant permissions we're going to use
208
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
209
+	 *
210
+	 * @var array
211
+	 */
212
+	protected $_cap_contexts_to_cap_action_map = [
213
+		self::caps_read       => 'read',
214
+		self::caps_read_admin => 'read',
215
+		self::caps_edit       => 'edit',
216
+		self::caps_delete     => 'delete',
217
+	];
218
+
219
+	/**
220
+	 * Timezone
221
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
222
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
223
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
224
+	 * EE_Datetime_Field data type will have access to it.
225
+	 *
226
+	 * @var string
227
+	 */
228
+	protected $_timezone;
229
+
230
+
231
+	/**
232
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
233
+	 * multisite.
234
+	 *
235
+	 * @var int
236
+	 */
237
+	protected static $_model_query_blog_id;
238
+
239
+	/**
240
+	 * A copy of _fields, except the array keys are the model names pointed to by
241
+	 * the field
242
+	 *
243
+	 * @var EE_Model_Field_Base[]
244
+	 */
245
+	private $_cache_foreign_key_to_fields = [];
246
+
247
+	/**
248
+	 * Cached list of all the fields on the model, indexed by their name
249
+	 *
250
+	 * @var EE_Model_Field_Base[]
251
+	 */
252
+	private $_cached_fields = null;
253
+
254
+	/**
255
+	 * Cached list of all the fields on the model, except those that are
256
+	 * marked as only pertinent to the database
257
+	 *
258
+	 * @var EE_Model_Field_Base[]
259
+	 */
260
+	private $_cached_fields_non_db_only = null;
261
+
262
+	/**
263
+	 * A cached reference to the primary key for quick lookup
264
+	 *
265
+	 * @var EE_Model_Field_Base
266
+	 */
267
+	private $_primary_key_field = null;
268
+
269
+	/**
270
+	 * Flag indicating whether this model has a primary key or not
271
+	 *
272
+	 * @var boolean
273
+	 */
274
+	protected $_has_primary_key_field = null;
275
+
276
+	/**
277
+	 * array in the format:  [ FK alias => full PK ]
278
+	 * where keys are local column name aliases for foreign keys
279
+	 * and values are the fully qualified column name for the primary key they represent
280
+	 *  ex:
281
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
282
+	 *
283
+	 * @var array $foreign_key_aliases
284
+	 */
285
+	protected $foreign_key_aliases = [];
286
+
287
+	/**
288
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
289
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
290
+	 * This should be true for models that deal with data that should exist independent of EE.
291
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
292
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
293
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
294
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
295
+	 *
296
+	 * @var boolean
297
+	 */
298
+	protected $_wp_core_model = false;
299
+
300
+	/**
301
+	 * @var bool stores whether this model has a password field or not.
302
+	 * null until initialized by hasPasswordField()
303
+	 */
304
+	protected $has_password_field;
305
+
306
+	/**
307
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
308
+	 */
309
+	protected $password_field;
310
+
311
+	/**
312
+	 *    List of valid operators that can be used for querying.
313
+	 * The keys are all operators we'll accept, the values are the real SQL
314
+	 * operators used
315
+	 *
316
+	 * @var array
317
+	 */
318
+	protected $_valid_operators = [
319
+		'='           => '=',
320
+		'<='          => '<=',
321
+		'<'           => '<',
322
+		'>='          => '>=',
323
+		'>'           => '>',
324
+		'!='          => '!=',
325
+		'LIKE'        => 'LIKE',
326
+		'like'        => 'LIKE',
327
+		'NOT_LIKE'    => 'NOT LIKE',
328
+		'not_like'    => 'NOT LIKE',
329
+		'NOT LIKE'    => 'NOT LIKE',
330
+		'not like'    => 'NOT LIKE',
331
+		'IN'          => 'IN',
332
+		'in'          => 'IN',
333
+		'NOT_IN'      => 'NOT IN',
334
+		'not_in'      => 'NOT IN',
335
+		'NOT IN'      => 'NOT IN',
336
+		'not in'      => 'NOT IN',
337
+		'between'     => 'BETWEEN',
338
+		'BETWEEN'     => 'BETWEEN',
339
+		'IS_NOT_NULL' => 'IS NOT NULL',
340
+		'is_not_null' => 'IS NOT NULL',
341
+		'IS NOT NULL' => 'IS NOT NULL',
342
+		'is not null' => 'IS NOT NULL',
343
+		'IS_NULL'     => 'IS NULL',
344
+		'is_null'     => 'IS NULL',
345
+		'IS NULL'     => 'IS NULL',
346
+		'is null'     => 'IS NULL',
347
+		'REGEXP'      => 'REGEXP',
348
+		'regexp'      => 'REGEXP',
349
+		'NOT_REGEXP'  => 'NOT REGEXP',
350
+		'not_regexp'  => 'NOT REGEXP',
351
+		'NOT REGEXP'  => 'NOT REGEXP',
352
+		'not regexp'  => 'NOT REGEXP',
353
+	];
354
+
355
+	/**
356
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
357
+	 *
358
+	 * @var array
359
+	 */
360
+	protected $_in_style_operators = ['IN', 'NOT IN'];
361
+
362
+	/**
363
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
364
+	 * '12-31-2012'"
365
+	 *
366
+	 * @var array
367
+	 */
368
+	protected $_between_style_operators = ['BETWEEN'];
369
+
370
+	/**
371
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
372
+	 *
373
+	 * @var array
374
+	 */
375
+	protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
376
+
377
+	/**
378
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
379
+	 * on a join table.
380
+	 *
381
+	 * @var array
382
+	 */
383
+	protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
384
+
385
+	/**
386
+	 * Allowed values for $query_params['order'] for ordering in queries
387
+	 *
388
+	 * @var array
389
+	 */
390
+	protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
391
+
392
+	/**
393
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
394
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
395
+	 *
396
+	 * @var array
397
+	 */
398
+	private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
399
+
400
+	/**
401
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
402
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
403
+	 *
404
+	 * @var array
405
+	 */
406
+	private $_allowed_query_params = [
407
+		0,
408
+		'limit',
409
+		'order_by',
410
+		'group_by',
411
+		'having',
412
+		'force_join',
413
+		'order',
414
+		'on_join_limit',
415
+		'default_where_conditions',
416
+		'caps',
417
+		'extra_selects',
418
+		'exclude_protected',
419
+	];
420
+
421
+	/**
422
+	 * All the data types that can be used in $wpdb->prepare statements.
423
+	 *
424
+	 * @var array
425
+	 */
426
+	private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
427
+
428
+	/**
429
+	 * @var EE_Registry $EE
430
+	 */
431
+	protected $EE = null;
432
+
433
+
434
+	/**
435
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
436
+	 *
437
+	 * @var int
438
+	 */
439
+	protected $_show_next_x_db_queries = 0;
440
+
441
+	/**
442
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
443
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
444
+	 * WHERE, GROUP_BY, etc.
445
+	 *
446
+	 * @var CustomSelects
447
+	 */
448
+	protected $_custom_selections = [];
449
+
450
+	/**
451
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
452
+	 * caches every model object we've fetched from the DB on this request
453
+	 *
454
+	 * @var array
455
+	 */
456
+	protected $_entity_map;
457
+
458
+	/**
459
+	 * @var LoaderInterface
460
+	 */
461
+	protected static $loader;
462
+
463
+	/**
464
+	 * @var Mirror
465
+	 */
466
+	private static $mirror;
467
+
468
+
469
+	/**
470
+	 * constant used to show EEM_Base has not yet verified the db on this http request
471
+	 */
472
+	const db_verified_none = 0;
473
+
474
+	/**
475
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
476
+	 * but not the addons' dbs
477
+	 */
478
+	const db_verified_core = 1;
479
+
480
+	/**
481
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
482
+	 * the EE core db too)
483
+	 */
484
+	const db_verified_addons = 2;
485
+
486
+	/**
487
+	 * indicates whether an EEM_Base child has already re-verified the DB
488
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
489
+	 * looking like EEM_Base::db_verified_*
490
+	 *
491
+	 * @var int - 0 = none, 1 = core, 2 = addons
492
+	 */
493
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
494
+
495
+	/**
496
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
497
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
498
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
499
+	 */
500
+	const default_where_conditions_all = 'all';
501
+
502
+	/**
503
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
504
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
505
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
506
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
507
+	 *        models which share tables with other models, this can return data for the wrong model.
508
+	 */
509
+	const default_where_conditions_this_only = 'this_model_only';
510
+
511
+	/**
512
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
513
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
514
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
515
+	 */
516
+	const default_where_conditions_others_only = 'other_models_only';
517
+
518
+	/**
519
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
520
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
521
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
522
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
523
+	 *        (regardless of whether those events and venues are trashed)
524
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
525
+	 *        events.
526
+	 */
527
+	const default_where_conditions_minimum_all = 'minimum';
528
+
529
+	/**
530
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
531
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
532
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
533
+	 *        not)
534
+	 */
535
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
536
+
537
+	/**
538
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
539
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
540
+	 *        it's possible it will return table entries for other models. You should use
541
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
542
+	 */
543
+	const default_where_conditions_none = 'none';
544
+
545
+
546
+	/**
547
+	 * About all child constructors:
548
+	 * they should define the _tables, _fields and _model_relations arrays.
549
+	 * Should ALWAYS be called after child constructor.
550
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
551
+	 * finalizes constructing all the object's attributes.
552
+	 * Generally, rather than requiring a child to code
553
+	 * $this->_tables = array(
554
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
555
+	 *        ...);
556
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
557
+	 * each EE_Table has a function to set the table's alias after the constructor, using
558
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
559
+	 * do something similar.
560
+	 *
561
+	 * @param null $timezone
562
+	 * @throws EE_Error
563
+	 */
564
+	protected function __construct($timezone = null)
565
+	{
566
+		// check that the model has not been loaded too soon
567
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
568
+			throw new EE_Error(
569
+				sprintf(
570
+					esc_html__(
571
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
572
+						'event_espresso'
573
+					),
574
+					get_class($this)
575
+				)
576
+			);
577
+		}
578
+		/**
579
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
580
+		 */
581
+		if (empty(EEM_Base::$_model_query_blog_id)) {
582
+			EEM_Base::set_model_query_blog_id();
583
+		}
584
+		/**
585
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
586
+		 * just use EE_Register_Model_Extension
587
+		 *
588
+		 * @var EE_Table_Base[] $_tables
589
+		 */
590
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
591
+		foreach ($this->_tables as $table_alias => $table_obj) {
592
+			/** @var $table_obj EE_Table_Base */
593
+			$table_obj->_construct_finalize_with_alias($table_alias);
594
+			if ($table_obj instanceof EE_Secondary_Table) {
595
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
596
+			}
597
+		}
598
+		/**
599
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
600
+		 * EE_Register_Model_Extension
601
+		 *
602
+		 * @param EE_Model_Field_Base[] $_fields
603
+		 */
604
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
605
+		$this->_invalidate_field_caches();
606
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
607
+			if (! array_key_exists($table_alias, $this->_tables)) {
608
+				throw new EE_Error(
609
+					sprintf(
610
+						esc_html__(
611
+							"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
612
+							'event_espresso'
613
+						),
614
+						$table_alias,
615
+						implode(",", $this->_fields)
616
+					)
617
+				);
618
+			}
619
+			foreach ($fields_for_table as $field_name => $field_obj) {
620
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
621
+				// primary key field base has a slightly different _construct_finalize
622
+				/** @var $field_obj EE_Model_Field_Base */
623
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
624
+			}
625
+		}
626
+		// everything is related to Extra_Meta
627
+		if (get_class($this) !== 'EEM_Extra_Meta') {
628
+			// make extra meta related to everything, but don't block deleting things just
629
+			// because they have related extra meta info. For now just orphan those extra meta
630
+			// in the future we should automatically delete them
631
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
632
+		}
633
+		// and change logs
634
+		if (get_class($this) !== 'EEM_Change_Log') {
635
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
636
+		}
637
+		/**
638
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
639
+		 * EE_Register_Model_Extension
640
+		 *
641
+		 * @param EE_Model_Relation_Base[] $_model_relations
642
+		 */
643
+		$this->_model_relations = (array) apply_filters(
644
+			'FHEE__' . get_class($this) . '__construct__model_relations',
645
+			$this->_model_relations
646
+		);
647
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
648
+			/** @var $relation_obj EE_Model_Relation_Base */
649
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
650
+		}
651
+		foreach ($this->_indexes as $index_name => $index_obj) {
652
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
653
+		}
654
+		$this->set_timezone($timezone);
655
+		// finalize default where condition strategy, or set default
656
+		if (! $this->_default_where_conditions_strategy) {
657
+			// nothing was set during child constructor, so set default
658
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
659
+		}
660
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
661
+		if (! $this->_minimum_where_conditions_strategy) {
662
+			// nothing was set during child constructor, so set default
663
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
664
+		}
665
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
666
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
667
+		// to indicate to NOT set it, set it to the logical default
668
+		if ($this->_caps_slug === null) {
669
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
670
+		}
671
+		// initialize the standard cap restriction generators if none were specified by the child constructor
672
+		if (is_array($this->_cap_restriction_generators)) {
673
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
674
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
675
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
676
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
677
+						new EE_Restriction_Generator_Protected(),
678
+						$cap_context,
679
+						$this
680
+					);
681
+				}
682
+			}
683
+		}
684
+		// if there are cap restriction generators, use them to make the default cap restrictions
685
+		if (is_array($this->_cap_restriction_generators)) {
686
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
687
+				if (! $generator_object) {
688
+					continue;
689
+				}
690
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
691
+					throw new EE_Error(
692
+						sprintf(
693
+							esc_html__(
694
+								'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.',
695
+								'event_espresso'
696
+							),
697
+							$context,
698
+							$this->get_this_model_name()
699
+						)
700
+					);
701
+				}
702
+				$action = $this->cap_action_for_context($context);
703
+				if (! $generator_object->construction_finalized()) {
704
+					$generator_object->_construct_finalize($this, $action);
705
+				}
706
+			}
707
+		}
708
+		do_action('AHEE__' . get_class($this) . '__construct__end');
709
+	}
710
+
711
+
712
+	/**
713
+	 * @return LoaderInterface
714
+	 * @throws InvalidArgumentException
715
+	 * @throws InvalidDataTypeException
716
+	 * @throws InvalidInterfaceException
717
+	 */
718
+	protected static function getLoader(): LoaderInterface
719
+	{
720
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
721
+			EEM_Base::$loader = LoaderFactory::getLoader();
722
+		}
723
+		return EEM_Base::$loader;
724
+	}
725
+
726
+
727
+	/**
728
+	 * @return Mirror
729
+	 * @since   $VID:$
730
+	 */
731
+	private static function getMirror(): Mirror
732
+	{
733
+		if (! EEM_Base::$mirror instanceof Mirror) {
734
+			EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
735
+		}
736
+		return EEM_Base::$mirror;
737
+	}
738
+
739
+
740
+	/**
741
+	 * @param string $model_class_Name
742
+	 * @param string $timezone
743
+	 * @return array
744
+	 * @throws ReflectionException
745
+	 * @since   $VID:$
746
+	 */
747
+	private static function getModelArguments(string $model_class_Name, string $timezone): array
748
+	{
749
+		$arguments = [$timezone];
750
+		$params    = EEM_Base::getMirror()->getParameters($model_class_Name);
751
+		if (count($params) > 1) {
752
+			if ($params[1]->getName() === 'model_field_factory') {
753
+				$arguments = [
754
+					$timezone,
755
+					EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
756
+				];
757
+			} elseif ($model_class_Name === 'EEM_Form_Section') {
758
+				$arguments = [
759
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
760
+					$timezone,
761
+				];
762
+			} elseif ($model_class_Name === 'EEM_Form_Element') {
763
+				$arguments = [
764
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
765
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
766
+					$timezone,
767
+				];
768
+			}
769
+		}
770
+		return $arguments;
771
+	}
772
+
773
+
774
+	/**
775
+	 * This function is a singleton method used to instantiate the Espresso_model object
776
+	 *
777
+	 * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
778
+	 *                                (and any incoming timezone data that gets saved).
779
+	 *                                Note this just sends the timezone info to the date time model field objects.
780
+	 *                                Default is NULL
781
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
782
+	 * @return static (as in the concrete child class)
783
+	 * @throws EE_Error
784
+	 * @throws ReflectionException
785
+	 */
786
+	public static function instance($timezone = null)
787
+	{
788
+		// check if instance of Espresso_model already exists
789
+		if (! static::$_instance instanceof static) {
790
+			$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
791
+			$model     = new static(...$arguments);
792
+			EEM_Base::getLoader()->share(static::class, $model, $arguments);
793
+			static::$_instance = $model;
794
+		}
795
+		// we might have a timezone set, let set_timezone decide what to do with it
796
+		if ($timezone) {
797
+			static::$_instance->set_timezone($timezone);
798
+		}
799
+		// Espresso_model object
800
+		return static::$_instance;
801
+	}
802
+
803
+
804
+	/**
805
+	 * resets the model and returns it
806
+	 *
807
+	 * @param string|null $timezone
808
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
809
+	 * all its properties reset; if it wasn't instantiated, returns null)
810
+	 * @throws EE_Error
811
+	 * @throws ReflectionException
812
+	 * @throws InvalidArgumentException
813
+	 * @throws InvalidDataTypeException
814
+	 * @throws InvalidInterfaceException
815
+	 */
816
+	public static function reset($timezone = null)
817
+	{
818
+		if (! static::$_instance instanceof EEM_Base) {
819
+			return null;
820
+		}
821
+		// Let's NOT swap out the current instance for a new one
822
+		// because if someone has a reference to it, we can't remove their reference.
823
+		// It's best to keep using the same reference but change the original object instead,
824
+		// so reset all its properties to their original values as defined in the class.
825
+		$static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
826
+		foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
827
+			// don't set instance to null like it was originally,
828
+			// but it's static anyways, and we're ignoring static properties (for now at least)
829
+			if (! isset($static_properties[ $property ])) {
830
+				static::$_instance->{$property} = $value;
831
+			}
832
+		}
833
+		// and then directly call its constructor again, like we would if we were creating a new one
834
+		$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
835
+		static::$_instance->__construct(...$arguments);
836
+		return self::instance();
837
+	}
838
+
839
+
840
+	/**
841
+	 * Used to set the $_model_query_blog_id static property.
842
+	 *
843
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
844
+	 *                      value for get_current_blog_id() will be used.
845
+	 */
846
+	public static function set_model_query_blog_id($blog_id = 0)
847
+	{
848
+		EEM_Base::$_model_query_blog_id = $blog_id > 0
849
+			? (int) $blog_id
850
+			: get_current_blog_id();
851
+	}
852
+
853
+
854
+	/**
855
+	 * Returns whatever is set as the internal $model_query_blog_id.
856
+	 *
857
+	 * @return int
858
+	 */
859
+	public static function get_model_query_blog_id()
860
+	{
861
+		return EEM_Base::$_model_query_blog_id;
862
+	}
863
+
864
+
865
+	/**
866
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
867
+	 *
868
+	 * @param boolean $translated return localized strings or JUST the array.
869
+	 * @return array
870
+	 * @throws EE_Error
871
+	 * @throws InvalidArgumentException
872
+	 * @throws InvalidDataTypeException
873
+	 * @throws InvalidInterfaceException
874
+	 * @throws ReflectionException
875
+	 */
876
+	public function status_array($translated = false)
877
+	{
878
+		if (! array_key_exists('Status', $this->_model_relations)) {
879
+			return [];
880
+		}
881
+		$model_name   = $this->get_this_model_name();
882
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
883
+		$stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
884
+		$status_array = [];
885
+		foreach ($stati as $status) {
886
+			$status_array[ $status->ID() ] = $status->get('STS_code');
887
+		}
888
+		return $translated
889
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
890
+			: $status_array;
891
+	}
892
+
893
+
894
+	/**
895
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
896
+	 *
897
+	 * @param array $query_params             @see
898
+	 *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
899
+	 *                                        or if you have the development copy of EE you can view this at the path:
900
+	 *                                        /docs/G--Model-System/model-query-params.md
901
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
902
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
903
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
904
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
905
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
906
+	 *                                        'OR'=>array(
907
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
908
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
909
+	 *                                        )
910
+	 *                                        ),
911
+	 *                                        'limit'=>10,
912
+	 *                                        'group_by'=>'TXN_ID'
913
+	 *                                        ));
914
+	 *                                        get all the answers to the question titled "shirt size" for event with id
915
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
916
+	 *                                        'Question.QST_display_text'=>'shirt size',
917
+	 *                                        'Registration.Event.EVT_ID'=>12
918
+	 *                                        ),
919
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
920
+	 *                                        ));
921
+	 * @throws EE_Error
922
+	 * @throws ReflectionException
923
+	 */
924
+	public function get_all($query_params = [])
925
+	{
926
+		if (
927
+			isset($query_params['limit'])
928
+			&& ! isset($query_params['group_by'])
929
+		) {
930
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
931
+		}
932
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
933
+	}
934
+
935
+
936
+	/**
937
+	 * Modifies the query parameters so we only get back model objects
938
+	 * that "belong" to the current user
939
+	 *
940
+	 * @param array $query_params @see
941
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
942
+	 * @return array @see
943
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
944
+	 * @throws ReflectionException
945
+	 * @throws ReflectionException
946
+	 */
947
+	public function alter_query_params_to_only_include_mine($query_params = [])
948
+	{
949
+		$wp_user_field_name = $this->wp_user_field_name();
950
+		if ($wp_user_field_name) {
951
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
952
+		}
953
+		return $query_params;
954
+	}
955
+
956
+
957
+	/**
958
+	 * Returns the name of the field's name that points to the WP_User table
959
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
960
+	 * foreign key to the WP_User table)
961
+	 *
962
+	 * @return string|boolean string on success, boolean false when there is no
963
+	 * foreign key to the WP_User table
964
+	 * @throws ReflectionException
965
+	 * @throws ReflectionException
966
+	 */
967
+	public function wp_user_field_name()
968
+	{
969
+		try {
970
+			if (! empty($this->_model_chain_to_wp_user)) {
971
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
972
+				$last_model_name              = end($models_to_follow_to_wp_users);
973
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
974
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
975
+			} else {
976
+				$model_with_fk_to_wp_users = $this;
977
+				$model_chain_to_wp_user    = '';
978
+			}
979
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
980
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
981
+		} catch (EE_Error $e) {
982
+			return false;
983
+		}
984
+	}
985
+
986
+
987
+	/**
988
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
989
+	 * (or transiently-related model) has a foreign key to the wp_users table;
990
+	 * useful for finding if model objects of this type are 'owned' by the current user.
991
+	 * This is an empty string when the foreign key is on this model and when it isn't,
992
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
993
+	 * (or transiently-related model)
994
+	 *
995
+	 * @return string
996
+	 */
997
+	public function model_chain_to_wp_user()
998
+	{
999
+		return $this->_model_chain_to_wp_user;
1000
+	}
1001
+
1002
+
1003
+	/**
1004
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1005
+	 * like how registrations don't have a foreign key to wp_users, but the
1006
+	 * events they are for are), or is unrelated to wp users.
1007
+	 * generally available
1008
+	 *
1009
+	 * @return boolean
1010
+	 */
1011
+	public function is_owned()
1012
+	{
1013
+		if ($this->model_chain_to_wp_user()) {
1014
+			return true;
1015
+		}
1016
+		try {
1017
+			$this->get_foreign_key_to('WP_User');
1018
+			return true;
1019
+		} catch (EE_Error $e) {
1020
+			return false;
1021
+		}
1022
+	}
1023
+
1024
+
1025
+	/**
1026
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1027
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1028
+	 * the model)
1029
+	 *
1030
+	 * @param array  $query_params      @see
1031
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1032
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1033
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1034
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1035
+	 *                                  override this and set the select to "*", or a specific column name, like
1036
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1037
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1038
+	 *                                  the aliases used to refer to this selection, and values are to be
1039
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1040
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1041
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1042
+	 * @throws EE_Error
1043
+	 * @throws InvalidArgumentException
1044
+	 */
1045
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1046
+	{
1047
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1048
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1049
+		$select_expressions       = $columns_to_select === null
1050
+			? $this->_construct_default_select_sql($model_query_info)
1051
+			: '';
1052
+		if ($this->_custom_selections instanceof CustomSelects) {
1053
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1054
+			$select_expressions .= $select_expressions
1055
+				? ', ' . $custom_expressions
1056
+				: $custom_expressions;
1057
+		}
1058
+
1059
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1060
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1061
+	}
1062
+
1063
+
1064
+	/**
1065
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1066
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1067
+	 * method of including extra select information.
1068
+	 *
1069
+	 * @param array             $query_params
1070
+	 * @param null|array|string $columns_to_select
1071
+	 * @return null|CustomSelects
1072
+	 * @throws InvalidArgumentException
1073
+	 */
1074
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1075
+	{
1076
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1077
+			return null;
1078
+		}
1079
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1080
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1081
+		return new CustomSelects($selects);
1082
+	}
1083
+
1084
+
1085
+	/**
1086
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1087
+	 * but you can use the model query params to more easily
1088
+	 * take care of joins, field preparation etc.
1089
+	 *
1090
+	 * @param array  $query_params      @see
1091
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1092
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1093
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1094
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1095
+	 *                                  override this and set the select to "*", or a specific column name, like
1096
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1097
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1098
+	 *                                  the aliases used to refer to this selection, and values are to be
1099
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1100
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1101
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1102
+	 * @throws EE_Error
1103
+	 */
1104
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1105
+	{
1106
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1107
+	}
1108
+
1109
+
1110
+	/**
1111
+	 * For creating a custom select statement
1112
+	 *
1113
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1114
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1115
+	 *                                 SQL, and 1=>is the datatype
1116
+	 * @return string
1117
+	 * @throws EE_Error
1118
+	 */
1119
+	private function _construct_select_from_input($columns_to_select)
1120
+	{
1121
+		if (is_array($columns_to_select)) {
1122
+			$select_sql_array = [];
1123
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1124
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1125
+					throw new EE_Error(
1126
+						sprintf(
1127
+							esc_html__(
1128
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1129
+								'event_espresso'
1130
+							),
1131
+							$selection_and_datatype,
1132
+							$alias
1133
+						)
1134
+					);
1135
+				}
1136
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1137
+					throw new EE_Error(
1138
+						sprintf(
1139
+							esc_html__(
1140
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1141
+								'event_espresso'
1142
+							),
1143
+							$selection_and_datatype[1],
1144
+							$selection_and_datatype[0],
1145
+							$alias,
1146
+							implode(', ', $this->_valid_wpdb_data_types)
1147
+						)
1148
+					);
1149
+				}
1150
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1151
+			}
1152
+			$columns_to_select_string = implode(', ', $select_sql_array);
1153
+		} else {
1154
+			$columns_to_select_string = $columns_to_select;
1155
+		}
1156
+		return $columns_to_select_string;
1157
+	}
1158
+
1159
+
1160
+	/**
1161
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1162
+	 *
1163
+	 * @return string
1164
+	 * @throws EE_Error
1165
+	 */
1166
+	public function primary_key_name()
1167
+	{
1168
+		return $this->get_primary_key_field()->get_name();
1169
+	}
1170
+
1171
+
1172
+	/**
1173
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1174
+	 * If there is no primary key on this model, $id is treated as primary key string
1175
+	 *
1176
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1177
+	 * @return EE_Base_Class|mixed|null
1178
+	 * @throws EE_Error
1179
+	 * @throws ReflectionException
1180
+	 */
1181
+	public function get_one_by_ID($id)
1182
+	{
1183
+		if ($this->get_from_entity_map($id)) {
1184
+			return $this->get_from_entity_map($id);
1185
+		}
1186
+		$model_object = $this->get_one(
1187
+			$this->alter_query_params_to_restrict_by_ID(
1188
+				$id,
1189
+				['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1190
+			)
1191
+		);
1192
+		$className    = $this->_get_class_name();
1193
+		if ($model_object instanceof $className) {
1194
+			// make sure valid objects get added to the entity map
1195
+			// so that the next call to this method doesn't trigger another trip to the db
1196
+			$this->add_to_entity_map($model_object);
1197
+		}
1198
+		return $model_object;
1199
+	}
1200
+
1201
+
1202
+	/**
1203
+	 * Alters query parameters to only get items with this ID are returned.
1204
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1205
+	 * or could just be a simple primary key ID
1206
+	 *
1207
+	 * @param int   $id
1208
+	 * @param array $query_params
1209
+	 * @return array of normal query params, @see
1210
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1211
+	 * @throws EE_Error
1212
+	 */
1213
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1214
+	{
1215
+		if (! isset($query_params[0])) {
1216
+			$query_params[0] = [];
1217
+		}
1218
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1219
+		if ($conditions_from_id === null) {
1220
+			$query_params[0][ $this->primary_key_name() ] = $id;
1221
+		} else {
1222
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1223
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1224
+		}
1225
+		return $query_params;
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1231
+	 * array. If no item is found, null is returned.
1232
+	 *
1233
+	 * @param array $query_params like EEM_Base's $query_params variable.
1234
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1235
+	 * @throws EE_Error
1236
+	 */
1237
+	public function get_one($query_params = [])
1238
+	{
1239
+		if (! is_array($query_params)) {
1240
+			EE_Error::doing_it_wrong(
1241
+				'EEM_Base::get_one',
1242
+				sprintf(
1243
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1244
+					gettype($query_params)
1245
+				),
1246
+				'4.6.0'
1247
+			);
1248
+			$query_params = [];
1249
+		}
1250
+		$query_params['limit'] = 1;
1251
+		$items                 = $this->get_all($query_params);
1252
+		if (empty($items)) {
1253
+			return null;
1254
+		}
1255
+		return array_shift($items);
1256
+	}
1257
+
1258
+
1259
+	/**
1260
+	 * Returns the next x number of items in sequence from the given value as
1261
+	 * found in the database matching the given query conditions.
1262
+	 *
1263
+	 * @param mixed $current_field_value    Value used for the reference point.
1264
+	 * @param null  $field_to_order_by      What field is used for the
1265
+	 *                                      reference point.
1266
+	 * @param int   $limit                  How many to return.
1267
+	 * @param array $query_params           Extra conditions on the query.
1268
+	 * @param null  $columns_to_select      If left null, then an array of
1269
+	 *                                      EE_Base_Class objects is returned,
1270
+	 *                                      otherwise you can indicate just the
1271
+	 *                                      columns you want returned.
1272
+	 * @return EE_Base_Class[]|array
1273
+	 * @throws EE_Error
1274
+	 */
1275
+	public function next_x(
1276
+		$current_field_value,
1277
+		$field_to_order_by = null,
1278
+		$limit = 1,
1279
+		$query_params = [],
1280
+		$columns_to_select = null
1281
+	) {
1282
+		return $this->_get_consecutive(
1283
+			$current_field_value,
1284
+			'>',
1285
+			$field_to_order_by,
1286
+			$limit,
1287
+			$query_params,
1288
+			$columns_to_select
1289
+		);
1290
+	}
1291
+
1292
+
1293
+	/**
1294
+	 * Returns the previous x number of items in sequence from the given value
1295
+	 * as found in the database matching the given query conditions.
1296
+	 *
1297
+	 * @param mixed $current_field_value    Value used for the reference point.
1298
+	 * @param null  $field_to_order_by      What field is used for the
1299
+	 *                                      reference point.
1300
+	 * @param int   $limit                  How many to return.
1301
+	 * @param array $query_params           Extra conditions on the query.
1302
+	 * @param null  $columns_to_select      If left null, then an array of
1303
+	 *                                      EE_Base_Class objects is returned,
1304
+	 *                                      otherwise you can indicate just the
1305
+	 *                                      columns you want returned.
1306
+	 * @return EE_Base_Class[]|array
1307
+	 * @throws EE_Error
1308
+	 */
1309
+	public function previous_x(
1310
+		$current_field_value,
1311
+		$field_to_order_by = null,
1312
+		$limit = 1,
1313
+		$query_params = [],
1314
+		$columns_to_select = null
1315
+	) {
1316
+		return $this->_get_consecutive(
1317
+			$current_field_value,
1318
+			'<',
1319
+			$field_to_order_by,
1320
+			$limit,
1321
+			$query_params,
1322
+			$columns_to_select
1323
+		);
1324
+	}
1325
+
1326
+
1327
+	/**
1328
+	 * Returns the next item in sequence from the given value as found in the
1329
+	 * database matching the given query conditions.
1330
+	 *
1331
+	 * @param mixed $current_field_value    Value used for the reference point.
1332
+	 * @param null  $field_to_order_by      What field is used for the
1333
+	 *                                      reference point.
1334
+	 * @param array $query_params           Extra conditions on the query.
1335
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1336
+	 *                                      object is returned, otherwise you
1337
+	 *                                      can indicate just the columns you
1338
+	 *                                      want and a single array indexed by
1339
+	 *                                      the columns will be returned.
1340
+	 * @return EE_Base_Class|null|array()
1341
+	 * @throws EE_Error
1342
+	 */
1343
+	public function next(
1344
+		$current_field_value,
1345
+		$field_to_order_by = null,
1346
+		$query_params = [],
1347
+		$columns_to_select = null
1348
+	) {
1349
+		$results = $this->_get_consecutive(
1350
+			$current_field_value,
1351
+			'>',
1352
+			$field_to_order_by,
1353
+			1,
1354
+			$query_params,
1355
+			$columns_to_select
1356
+		);
1357
+		return empty($results) ? null : reset($results);
1358
+	}
1359
+
1360
+
1361
+	/**
1362
+	 * Returns the previous item in sequence from the given value as found in
1363
+	 * the database matching the given query conditions.
1364
+	 *
1365
+	 * @param mixed $current_field_value    Value used for the reference point.
1366
+	 * @param null  $field_to_order_by      What field is used for the
1367
+	 *                                      reference point.
1368
+	 * @param array $query_params           Extra conditions on the query.
1369
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1370
+	 *                                      object is returned, otherwise you
1371
+	 *                                      can indicate just the columns you
1372
+	 *                                      want and a single array indexed by
1373
+	 *                                      the columns will be returned.
1374
+	 * @return EE_Base_Class|null|array()
1375
+	 * @throws EE_Error
1376
+	 */
1377
+	public function previous(
1378
+		$current_field_value,
1379
+		$field_to_order_by = null,
1380
+		$query_params = [],
1381
+		$columns_to_select = null
1382
+	) {
1383
+		$results = $this->_get_consecutive(
1384
+			$current_field_value,
1385
+			'<',
1386
+			$field_to_order_by,
1387
+			1,
1388
+			$query_params,
1389
+			$columns_to_select
1390
+		);
1391
+		return empty($results) ? null : reset($results);
1392
+	}
1393
+
1394
+
1395
+	/**
1396
+	 * Returns the a consecutive number of items in sequence from the given
1397
+	 * value as found in the database matching the given query conditions.
1398
+	 *
1399
+	 * @param mixed  $current_field_value   Value used for the reference point.
1400
+	 * @param string $operand               What operand is used for the sequence.
1401
+	 * @param string $field_to_order_by     What field is used for the reference point.
1402
+	 * @param int    $limit                 How many to return.
1403
+	 * @param array  $query_params          Extra conditions on the query.
1404
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1405
+	 *                                      otherwise you can indicate just the columns you want returned.
1406
+	 * @return EE_Base_Class[]|array
1407
+	 * @throws EE_Error
1408
+	 */
1409
+	protected function _get_consecutive(
1410
+		$current_field_value,
1411
+		$operand = '>',
1412
+		$field_to_order_by = null,
1413
+		$limit = 1,
1414
+		$query_params = [],
1415
+		$columns_to_select = null
1416
+	) {
1417
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1418
+		if (empty($field_to_order_by)) {
1419
+			if ($this->has_primary_key_field()) {
1420
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1421
+			} else {
1422
+				if (WP_DEBUG) {
1423
+					throw new EE_Error(
1424
+						esc_html__(
1425
+							'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1426
+							'event_espresso'
1427
+						)
1428
+					);
1429
+				}
1430
+				EE_Error::add_error(
1431
+					esc_html__('There was an error with the query.', 'event_espresso'),
1432
+					__FILE__,
1433
+					__FUNCTION__,
1434
+					__LINE__
1435
+				);
1436
+				return [];
1437
+			}
1438
+		}
1439
+		if (! is_array($query_params)) {
1440
+			EE_Error::doing_it_wrong(
1441
+				'EEM_Base::_get_consecutive',
1442
+				sprintf(
1443
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1444
+					gettype($query_params)
1445
+				),
1446
+				'4.6.0'
1447
+			);
1448
+			$query_params = [];
1449
+		}
1450
+		// let's add the where query param for consecutive look up.
1451
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1452
+		$query_params['limit']                 = $limit;
1453
+		// set direction
1454
+		$incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1455
+		$query_params['order_by'] = $operand === '>'
1456
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1457
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1458
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1459
+		if (empty($columns_to_select)) {
1460
+			return $this->get_all($query_params);
1461
+		}
1462
+		// getting just the fields
1463
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1464
+	}
1465
+
1466
+
1467
+	/**
1468
+	 * This sets the _timezone property after model object has been instantiated.
1469
+	 *
1470
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1471
+	 */
1472
+	public function set_timezone($timezone)
1473
+	{
1474
+		if ($timezone !== null) {
1475
+			$this->_timezone = $timezone;
1476
+		}
1477
+		// note we need to loop through relations and set the timezone on those objects as well.
1478
+		foreach ($this->_model_relations as $relation) {
1479
+			$relation->set_timezone($timezone);
1480
+		}
1481
+		// and finally we do the same for any datetime fields
1482
+		foreach ($this->_fields as $field) {
1483
+			if ($field instanceof EE_Datetime_Field) {
1484
+				$field->set_timezone($timezone);
1485
+			}
1486
+		}
1487
+	}
1488
+
1489
+
1490
+	/**
1491
+	 * This just returns whatever is set for the current timezone.
1492
+	 *
1493
+	 * @access public
1494
+	 * @return string
1495
+	 */
1496
+	public function get_timezone()
1497
+	{
1498
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1499
+		if (empty($this->_timezone)) {
1500
+			foreach ($this->_fields as $field) {
1501
+				if ($field instanceof EE_Datetime_Field) {
1502
+					$this->set_timezone($field->get_timezone());
1503
+					break;
1504
+				}
1505
+			}
1506
+		}
1507
+		// if timezone STILL empty then return the default timezone for the site.
1508
+		if (empty($this->_timezone)) {
1509
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1510
+		}
1511
+		return $this->_timezone;
1512
+	}
1513
+
1514
+
1515
+	/**
1516
+	 * This returns the date formats set for the given field name and also ensures that
1517
+	 * $this->_timezone property is set correctly.
1518
+	 *
1519
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1520
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1521
+	 * @return array formats in an array with the date format first, and the time format last.
1522
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1523
+	 * @since 4.6.x
1524
+	 */
1525
+	public function get_formats_for($field_name, $pretty = false)
1526
+	{
1527
+		$field_settings = $this->field_settings_for($field_name);
1528
+		// if not a valid EE_Datetime_Field then throw error
1529
+		if (! $field_settings instanceof EE_Datetime_Field) {
1530
+			throw new EE_Error(
1531
+				sprintf(
1532
+					esc_html__(
1533
+						'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.',
1534
+						'event_espresso'
1535
+					),
1536
+					$field_name
1537
+				)
1538
+			);
1539
+		}
1540
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1541
+		// the field.
1542
+		$this->_timezone = $field_settings->get_timezone();
1543
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1544
+	}
1545
+
1546
+
1547
+	/**
1548
+	 * This returns the current time in a format setup for a query on this model.
1549
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1550
+	 * it will return:
1551
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1552
+	 *  NOW
1553
+	 *  - or a unix timestamp (equivalent to time())
1554
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1555
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1556
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1557
+	 *
1558
+	 * @param string $field_name       The field the current time is needed for.
1559
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1560
+	 *                                 formatted string matching the set format for the field in the set timezone will
1561
+	 *                                 be returned.
1562
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1563
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1564
+	 *                                 exception is triggered.
1565
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1566
+	 * @throws Exception
1567
+	 * @since 4.6.x
1568
+	 */
1569
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1570
+	{
1571
+		$formats  = $this->get_formats_for($field_name);
1572
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1573
+		if ($timestamp) {
1574
+			return $DateTime->format('U');
1575
+		}
1576
+		// not returning timestamp, so return formatted string in timezone.
1577
+		switch ($what) {
1578
+			case 'time':
1579
+				return $DateTime->format($formats[1]);
1580
+			case 'date':
1581
+				return $DateTime->format($formats[0]);
1582
+			default:
1583
+				return $DateTime->format(implode(' ', $formats));
1584
+		}
1585
+	}
1586
+
1587
+
1588
+	/**
1589
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1590
+	 * for the model are.  Returns a DateTime object.
1591
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1592
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1593
+	 * ignored.
1594
+	 *
1595
+	 * @param string $field_name      The field being setup.
1596
+	 * @param string $timestring      The date time string being used.
1597
+	 * @param string $incoming_format The format for the time string.
1598
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1599
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1600
+	 *                                format is
1601
+	 *                                'U', this is ignored.
1602
+	 * @return DateTime
1603
+	 * @throws EE_Error
1604
+	 */
1605
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1606
+	{
1607
+		// just using this to ensure the timezone is set correctly internally
1608
+		$this->get_formats_for($field_name);
1609
+		// load EEH_DTT_Helper
1610
+		$set_timezone     = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1611
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1612
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1613
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1614
+	}
1615
+
1616
+
1617
+	/**
1618
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1619
+	 *
1620
+	 * @return EE_Table_Base[]
1621
+	 */
1622
+	public function get_tables()
1623
+	{
1624
+		return $this->_tables;
1625
+	}
1626
+
1627
+
1628
+	/**
1629
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1630
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1631
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1632
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1633
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1634
+	 * model object with EVT_ID = 1
1635
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1636
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1637
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1638
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1639
+	 * are not specified)
1640
+	 *
1641
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1642
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1643
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1644
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1645
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1646
+	 *                                         ID=34, we'd use this method as follows:
1647
+	 *                                         EEM_Transaction::instance()->update(
1648
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1649
+	 *                                         array(array('TXN_ID'=>34)));
1650
+	 * @param array   $query_params            @see
1651
+	 *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1652
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1653
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1654
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1655
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1656
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1657
+	 *                                         TRUE, it is assumed that you've already called
1658
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1659
+	 *                                         malicious javascript. However, if
1660
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1661
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1662
+	 *                                         and every other field, before insertion. We provide this parameter
1663
+	 *                                         because model objects perform their prepare_for_set function on all
1664
+	 *                                         their values, and so don't need to be called again (and in many cases,
1665
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1666
+	 *                                         prepare_for_set method...)
1667
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1668
+	 *                                         in this model's entity map according to $fields_n_values that match
1669
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1670
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1671
+	 *                                         could get out-of-sync with the database
1672
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1673
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1674
+	 *                                         bad)
1675
+	 * @throws EE_Error
1676
+	 * @throws ReflectionException
1677
+	 */
1678
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1679
+	{
1680
+		if (! is_array($query_params)) {
1681
+			EE_Error::doing_it_wrong(
1682
+				'EEM_Base::update',
1683
+				sprintf(
1684
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1685
+					gettype($query_params)
1686
+				),
1687
+				'4.6.0'
1688
+			);
1689
+			$query_params = [];
1690
+		}
1691
+		/**
1692
+		 * Action called before a model update call has been made.
1693
+		 *
1694
+		 * @param EEM_Base $model
1695
+		 * @param array    $fields_n_values the updated fields and their new values
1696
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1697
+		 */
1698
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1699
+		/**
1700
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1701
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1702
+		 *
1703
+		 * @param array    $fields_n_values fields and their new values
1704
+		 * @param EEM_Base $model           the model being queried
1705
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1706
+		 */
1707
+		$fields_n_values = (array) apply_filters(
1708
+			'FHEE__EEM_Base__update__fields_n_values',
1709
+			$fields_n_values,
1710
+			$this,
1711
+			$query_params
1712
+		);
1713
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1714
+		// to do that, for each table, verify that it's PK isn't null.
1715
+		$tables = $this->get_tables();
1716
+		// 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
1717
+		// NOTE: we should make this code more efficient by NOT querying twice
1718
+		// before the real update, but that needs to first go through ALPHA testing
1719
+		// as it's dangerous. says Mike August 8 2014
1720
+		// we want to make sure the default_where strategy is ignored
1721
+		$this->_ignore_where_strategy = true;
1722
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1723
+		foreach ($wpdb_select_results as $wpdb_result) {
1724
+			// type cast stdClass as array
1725
+			$wpdb_result = (array) $wpdb_result;
1726
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1727
+			if ($this->has_primary_key_field()) {
1728
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1729
+			} else {
1730
+				// 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)
1731
+				$main_table_pk_value = null;
1732
+			}
1733
+			// 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
1734
+			// 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
1735
+			if (count($tables) > 1) {
1736
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1737
+				// in that table, and so we'll want to insert one
1738
+				foreach ($tables as $table_obj) {
1739
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1740
+					// if there is no private key for this table on the results, it means there's no entry
1741
+					// in this table, right? so insert a row in the current table, using any fields available
1742
+					if (
1743
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1744
+						   && $wpdb_result[ $this_table_pk_column ])
1745
+					) {
1746
+						$success = $this->_insert_into_specific_table(
1747
+							$table_obj,
1748
+							$fields_n_values,
1749
+							$main_table_pk_value
1750
+						);
1751
+						// if we died here, report the error
1752
+						if (! $success) {
1753
+							return false;
1754
+						}
1755
+					}
1756
+				}
1757
+			}
1758
+			//              //and now check that if we have cached any models by that ID on the model, that
1759
+			//              //they also get updated properly
1760
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1761
+			//              if( $model_object ){
1762
+			//                  foreach( $fields_n_values as $field => $value ){
1763
+			//                      $model_object->set($field, $value);
1764
+			// let's make sure default_where strategy is followed now
1765
+			$this->_ignore_where_strategy = false;
1766
+		}
1767
+		// if we want to keep model objects in sync, AND
1768
+		// if this wasn't called from a model object (to update itself)
1769
+		// then we want to make sure we keep all the existing
1770
+		// model objects in sync with the db
1771
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1772
+			if ($this->has_primary_key_field()) {
1773
+				$model_objs_affected_ids = $this->get_col($query_params);
1774
+			} else {
1775
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1776
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1777
+				$model_objs_affected_ids     = [];
1778
+				foreach ($models_affected_key_columns as $row) {
1779
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1780
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1781
+				}
1782
+			}
1783
+			if (! $model_objs_affected_ids) {
1784
+				// wait wait wait- if nothing was affected let's stop here
1785
+				return 0;
1786
+			}
1787
+			foreach ($model_objs_affected_ids as $id) {
1788
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1789
+				if ($model_obj_in_entity_map) {
1790
+					foreach ($fields_n_values as $field => $new_value) {
1791
+						$model_obj_in_entity_map->set($field, $new_value);
1792
+					}
1793
+				}
1794
+			}
1795
+			// if there is a primary key on this model, we can now do a slight optimization
1796
+			if ($this->has_primary_key_field()) {
1797
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1798
+				$query_params = [
1799
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1800
+					'limit'                    => count($model_objs_affected_ids),
1801
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1802
+				];
1803
+			}
1804
+		}
1805
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1806
+		$SQL              = "UPDATE "
1807
+							. $model_query_info->get_full_join_sql()
1808
+							. " SET "
1809
+							. $this->_construct_update_sql($fields_n_values)
1810
+							. $model_query_info->get_where_sql(
1811
+							);// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1812
+		$rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1813
+		/**
1814
+		 * Action called after a model update call has been made.
1815
+		 *
1816
+		 * @param EEM_Base $model
1817
+		 * @param array    $fields_n_values the updated fields and their new values
1818
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1819
+		 * @param int      $rows_affected
1820
+		 */
1821
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1822
+		return $rows_affected;// how many supposedly got updated
1823
+	}
1824
+
1825
+
1826
+	/**
1827
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1828
+	 * are teh values of the field specified (or by default the primary key field)
1829
+	 * that matched the query params. Note that you should pass the name of the
1830
+	 * model FIELD, not the database table's column name.
1831
+	 *
1832
+	 * @param array  $query_params @see
1833
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1834
+	 * @param string $field_to_select
1835
+	 * @return array just like $wpdb->get_col()
1836
+	 * @throws EE_Error
1837
+	 */
1838
+	public function get_col($query_params = [], $field_to_select = null)
1839
+	{
1840
+		if ($field_to_select) {
1841
+			$field = $this->field_settings_for($field_to_select);
1842
+		} elseif ($this->has_primary_key_field()) {
1843
+			$field = $this->get_primary_key_field();
1844
+		} else {
1845
+			$field_settings = $this->field_settings();
1846
+			// no primary key, just grab the first column
1847
+			$field = reset($field_settings);
1848
+			// don't need this array now
1849
+			unset($field_settings);
1850
+		}
1851
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1852
+		$select_expressions = $field->get_qualified_column();
1853
+		$SQL                =
1854
+			"SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1855
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1856
+	}
1857
+
1858
+
1859
+	/**
1860
+	 * Returns a single column value for a single row from the database
1861
+	 *
1862
+	 * @param array  $query_params    @see
1863
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1864
+	 * @param string $field_to_select @see EEM_Base::get_col()
1865
+	 * @return string
1866
+	 * @throws EE_Error
1867
+	 */
1868
+	public function get_var($query_params = [], $field_to_select = null)
1869
+	{
1870
+		$query_params['limit'] = 1;
1871
+		$col                   = $this->get_col($query_params, $field_to_select);
1872
+		if (! empty($col)) {
1873
+			return reset($col);
1874
+		}
1875
+		return null;
1876
+	}
1877
+
1878
+
1879
+	/**
1880
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1881
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1882
+	 * injection, but currently no further filtering is done
1883
+	 *
1884
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1885
+	 *                               be updated to in the DB
1886
+	 * @return string of SQL
1887
+	 * @throws EE_Error
1888
+	 * @global      $wpdb
1889
+	 */
1890
+	public function _construct_update_sql($fields_n_values)
1891
+	{
1892
+		/** @type WPDB $wpdb */
1893
+		global $wpdb;
1894
+		$cols_n_values = [];
1895
+		foreach ($fields_n_values as $field_name => $value) {
1896
+			$field_obj = $this->field_settings_for($field_name);
1897
+			// if the value is NULL, we want to assign the value to that.
1898
+			// wpdb->prepare doesn't really handle that properly
1899
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1900
+			$value_sql       = $prepared_value === null ? 'NULL'
1901
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1902
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1903
+		}
1904
+		return implode(",", $cols_n_values);
1905
+	}
1906
+
1907
+
1908
+	/**
1909
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1910
+	 * Performs a HARD delete, meaning the database row should always be removed,
1911
+	 * not just have a flag field on it switched
1912
+	 * Wrapper for EEM_Base::delete_permanently()
1913
+	 *
1914
+	 * @param mixed   $id
1915
+	 * @param boolean $allow_blocking
1916
+	 * @return int the number of rows deleted
1917
+	 * @throws EE_Error
1918
+	 * @throws ReflectionException
1919
+	 */
1920
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1921
+	{
1922
+		return $this->delete_permanently(
1923
+			[
1924
+				[$this->get_primary_key_field()->get_name() => $id],
1925
+				'limit' => 1,
1926
+			],
1927
+			$allow_blocking
1928
+		);
1929
+	}
1930
+
1931
+
1932
+	/**
1933
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1934
+	 * Wrapper for EEM_Base::delete()
1935
+	 *
1936
+	 * @param mixed   $id
1937
+	 * @param boolean $allow_blocking
1938
+	 * @return int the number of rows deleted
1939
+	 * @throws EE_Error
1940
+	 */
1941
+	public function delete_by_ID($id, $allow_blocking = true)
1942
+	{
1943
+		return $this->delete(
1944
+			[
1945
+				[$this->get_primary_key_field()->get_name() => $id],
1946
+				'limit' => 1,
1947
+			],
1948
+			$allow_blocking
1949
+		);
1950
+	}
1951
+
1952
+
1953
+	/**
1954
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1955
+	 * meaning if the model has a field that indicates its been "trashed" or
1956
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1957
+	 *
1958
+	 * @param array   $query_params
1959
+	 * @param boolean $allow_blocking
1960
+	 * @return int how many rows got deleted
1961
+	 * @throws EE_Error
1962
+	 * @throws ReflectionException
1963
+	 * @see EEM_Base::delete_permanently
1964
+	 */
1965
+	public function delete($query_params, $allow_blocking = true)
1966
+	{
1967
+		return $this->delete_permanently($query_params, $allow_blocking);
1968
+	}
1969
+
1970
+
1971
+	/**
1972
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1973
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1974
+	 * as archived, not actually deleted
1975
+	 *
1976
+	 * @param array   $query_params   @see
1977
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1978
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1979
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1980
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1981
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1982
+	 *                                DB
1983
+	 * @return int how many rows got deleted
1984
+	 * @throws EE_Error
1985
+	 * @throws ReflectionException
1986
+	 */
1987
+	public function delete_permanently($query_params, $allow_blocking = true)
1988
+	{
1989
+		/**
1990
+		 * Action called just before performing a real deletion query. You can use the
1991
+		 * model and its $query_params to find exactly which items will be deleted
1992
+		 *
1993
+		 * @param EEM_Base $model
1994
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1995
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1996
+		 *                                 to block (prevent) this deletion
1997
+		 */
1998
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1999
+		// some MySQL databases may be running safe mode, which may restrict
2000
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
2001
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
2002
+		// to delete them
2003
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2004
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2005
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2006
+			$columns_and_ids_for_deleting
2007
+		);
2008
+		/**
2009
+		 * Allows client code to act on the items being deleted before the query is actually executed.
2010
+		 *
2011
+		 * @param EEM_Base $this                            The model instance being acted on.
2012
+		 * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
2013
+		 * @param bool     $allow_blocking                  @see param description in method phpdoc block.
2014
+		 * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
2015
+		 *                                                  derived from the incoming query parameters.
2016
+		 * @see details on the structure of this array in the phpdocs
2017
+		 *                                                  for the `_get_ids_for_delete_method`
2018
+		 *
2019
+		 */
2020
+		do_action(
2021
+			'AHEE__EEM_Base__delete__before_query',
2022
+			$this,
2023
+			$query_params,
2024
+			$allow_blocking,
2025
+			$columns_and_ids_for_deleting
2026
+		);
2027
+		if ($deletion_where_query_part) {
2028
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2029
+			$table_aliases    = array_keys($this->_tables);
2030
+			$SQL              = "DELETE "
2031
+								. implode(", ", $table_aliases)
2032
+								. " FROM "
2033
+								. $model_query_info->get_full_join_sql()
2034
+								. " WHERE "
2035
+								. $deletion_where_query_part;
2036
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2037
+		} else {
2038
+			$rows_deleted = 0;
2039
+		}
2040
+
2041
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2042
+		// there was no error with the delete query.
2043
+		if (
2044
+			$this->has_primary_key_field()
2045
+			&& $rows_deleted !== false
2046
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2047
+		) {
2048
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2049
+			foreach ($ids_for_removal as $id) {
2050
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2051
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2052
+				}
2053
+			}
2054
+
2055
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2056
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2057
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2058
+			// (although it is possible).
2059
+			// Note this can be skipped by using the provided filter and returning false.
2060
+			if (
2061
+				apply_filters(
2062
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2063
+					! $this instanceof EEM_Extra_Meta,
2064
+					$this
2065
+				)
2066
+			) {
2067
+				EEM_Extra_Meta::instance()->delete_permanently([
2068
+																   0 => [
2069
+																	   'EXM_type' => $this->get_this_model_name(),
2070
+																	   'OBJ_ID'   => [
2071
+																		   'IN',
2072
+																		   $ids_for_removal,
2073
+																	   ],
2074
+																   ],
2075
+															   ]);
2076
+			}
2077
+		}
2078
+
2079
+		/**
2080
+		 * Action called just after performing a real deletion query. Although at this point the
2081
+		 * items should have been deleted
2082
+		 *
2083
+		 * @param EEM_Base $model
2084
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2085
+		 * @param int      $rows_deleted
2086
+		 */
2087
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2088
+		return $rows_deleted;// how many supposedly got deleted
2089
+	}
2090
+
2091
+
2092
+	/**
2093
+	 * Checks all the relations that throw error messages when there are blocking related objects
2094
+	 * for related model objects. If there are any related model objects on those relations,
2095
+	 * adds an EE_Error, and return true
2096
+	 *
2097
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2098
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2099
+	 *                                                 should be ignored when determining whether there are related
2100
+	 *                                                 model objects which block this model object's deletion. Useful
2101
+	 *                                                 if you know A is related to B and are considering deleting A,
2102
+	 *                                                 but want to see if A has any other objects blocking its deletion
2103
+	 *                                                 before removing the relation between A and B
2104
+	 * @return boolean
2105
+	 * @throws EE_Error
2106
+	 * @throws ReflectionException
2107
+	 */
2108
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2109
+	{
2110
+		// first, if $ignore_this_model_obj was supplied, get its model
2111
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2112
+			$ignored_model = $ignore_this_model_obj->get_model();
2113
+		} else {
2114
+			$ignored_model = null;
2115
+		}
2116
+		// now check all the relations of $this_model_obj_or_id and see if there
2117
+		// are any related model objects blocking it?
2118
+		$is_blocked = false;
2119
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2120
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2121
+				// if $ignore_this_model_obj was supplied, then for the query
2122
+				// on that model needs to be told to ignore $ignore_this_model_obj
2123
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2124
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, [
2125
+						[
2126
+							$ignored_model->get_primary_key_field()->get_name() => [
2127
+								'!=',
2128
+								$ignore_this_model_obj->ID(),
2129
+							],
2130
+						],
2131
+					]);
2132
+				} else {
2133
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2134
+				}
2135
+				if ($related_model_objects) {
2136
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2137
+					$is_blocked = true;
2138
+				}
2139
+			}
2140
+		}
2141
+		return $is_blocked;
2142
+	}
2143
+
2144
+
2145
+	/**
2146
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2147
+	 *
2148
+	 * @param array $row_results_for_deleting
2149
+	 * @param bool  $allow_blocking
2150
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2151
+	 *                              model DOES have a primary_key_field, then the array will be a simple single
2152
+	 *                              dimension array where the key is the fully qualified primary key column and the
2153
+	 *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2154
+	 *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2155
+	 *                              be a two dimensional array where each element is a group of columns and values that
2156
+	 *                              get deleted. Example: array(
2157
+	 *                              0 => array(
2158
+	 *                              'Term_Relationship.object_id' => 1
2159
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2160
+	 *                              ),
2161
+	 *                              1 => array(
2162
+	 *                              'Term_Relationship.object_id' => 1
2163
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2164
+	 *                              )
2165
+	 *                              )
2166
+	 * @throws EE_Error
2167
+	 * @throws ReflectionException
2168
+	 */
2169
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2170
+	{
2171
+		$ids_to_delete_indexed_by_column = [];
2172
+		if ($this->has_primary_key_field()) {
2173
+			$primary_table                   = $this->_get_main_table();
2174
+			$primary_table_pk_field          =
2175
+				$this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2176
+			$other_tables                    = $this->_get_other_tables();
2177
+			$ids_to_delete_indexed_by_column = $query = [];
2178
+			foreach ($row_results_for_deleting as $item_to_delete) {
2179
+				// before we mark this item for deletion,
2180
+				// make sure there's no related entities blocking its deletion (if we're checking)
2181
+				if (
2182
+					$allow_blocking
2183
+					&& $this->delete_is_blocked_by_related_models(
2184
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2185
+					)
2186
+				) {
2187
+					continue;
2188
+				}
2189
+				// primary table deletes
2190
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2191
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2192
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2193
+				}
2194
+			}
2195
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2196
+			$fields = $this->get_combined_primary_key_fields();
2197
+			foreach ($row_results_for_deleting as $item_to_delete) {
2198
+				$ids_to_delete_indexed_by_column_for_row = [];
2199
+				foreach ($fields as $cpk_field) {
2200
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2201
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2202
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2203
+					}
2204
+				}
2205
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2206
+			}
2207
+		} else {
2208
+			// so there's no primary key and no combined key...
2209
+			// sorry, can't help you
2210
+			throw new EE_Error(
2211
+				sprintf(
2212
+					esc_html__(
2213
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2214
+						"event_espresso"
2215
+					),
2216
+					get_class($this)
2217
+				)
2218
+			);
2219
+		}
2220
+		return $ids_to_delete_indexed_by_column;
2221
+	}
2222
+
2223
+
2224
+	/**
2225
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2226
+	 * the corresponding query_part for the query performing the delete.
2227
+	 *
2228
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2229
+	 * @return string
2230
+	 * @throws EE_Error
2231
+	 */
2232
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2233
+	{
2234
+		$query_part = '';
2235
+		if (empty($ids_to_delete_indexed_by_column)) {
2236
+			return $query_part;
2237
+		} elseif ($this->has_primary_key_field()) {
2238
+			$query = [];
2239
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2240
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2241
+			}
2242
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2243
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2244
+			$ways_to_identify_a_row = [];
2245
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2246
+				$values_for_each_combined_primary_key_for_a_row = [];
2247
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2248
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2249
+				}
2250
+				$ways_to_identify_a_row[] = '('
2251
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2252
+											. ')';
2253
+			}
2254
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2255
+		}
2256
+		return $query_part;
2257
+	}
2258
+
2259
+
2260
+	/**
2261
+	 * Gets the model field by the fully qualified name
2262
+	 *
2263
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2264
+	 * @return EE_Model_Field_Base
2265
+	 * @throws EE_Error
2266
+	 * @throws EE_Error
2267
+	 */
2268
+	public function get_field_by_column($qualified_column_name)
2269
+	{
2270
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2271
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2272
+				return $field_obj;
2273
+			}
2274
+		}
2275
+		throw new EE_Error(
2276
+			sprintf(
2277
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2278
+				$this->get_this_model_name(),
2279
+				$qualified_column_name
2280
+			)
2281
+		);
2282
+	}
2283
+
2284
+
2285
+	/**
2286
+	 * Count all the rows that match criteria the model query params.
2287
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2288
+	 * column
2289
+	 *
2290
+	 * @param array  $query_params   @see
2291
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2292
+	 * @param string $field_to_count field on model to count by (not column name)
2293
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2294
+	 *                               that by the setting $distinct to TRUE;
2295
+	 * @return int
2296
+	 * @throws EE_Error
2297
+	 */
2298
+	public function count($query_params = [], $field_to_count = null, $distinct = false)
2299
+	{
2300
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2301
+		if ($field_to_count) {
2302
+			$field_obj       = $this->field_settings_for($field_to_count);
2303
+			$column_to_count = $field_obj->get_qualified_column();
2304
+		} elseif ($this->has_primary_key_field()) {
2305
+			$pk_field_obj    = $this->get_primary_key_field();
2306
+			$column_to_count = $pk_field_obj->get_qualified_column();
2307
+		} else {
2308
+			// there's no primary key
2309
+			// if we're counting distinct items, and there's no primary key,
2310
+			// we need to list out the columns for distinction;
2311
+			// otherwise we can just use star
2312
+			if ($distinct) {
2313
+				$columns_to_use = [];
2314
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2315
+					$columns_to_use[] = $field_obj->get_qualified_column();
2316
+				}
2317
+				$column_to_count = implode(',', $columns_to_use);
2318
+			} else {
2319
+				$column_to_count = '*';
2320
+			}
2321
+		}
2322
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2323
+		$SQL             =
2324
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2325
+		return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2326
+	}
2327
+
2328
+
2329
+	/**
2330
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2331
+	 *
2332
+	 * @param array  $query_params @see
2333
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2334
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2335
+	 * @return float
2336
+	 * @throws EE_Error
2337
+	 */
2338
+	public function sum($query_params, $field_to_sum = null)
2339
+	{
2340
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2341
+		if ($field_to_sum) {
2342
+			$field_obj = $this->field_settings_for($field_to_sum);
2343
+		} else {
2344
+			$field_obj = $this->get_primary_key_field();
2345
+		}
2346
+		$column_to_count = $field_obj->get_qualified_column();
2347
+		$SQL             =
2348
+			"SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2349
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2350
+		$data_type       = $field_obj->get_wpdb_data_type();
2351
+		if ($data_type === '%d' || $data_type === '%s') {
2352
+			return (float) $return_value;
2353
+		}
2354
+		// must be %f
2355
+		return (float) $return_value;
2356
+	}
2357
+
2358
+
2359
+	/**
2360
+	 * Just calls the specified method on $wpdb with the given arguments
2361
+	 * Consolidates a little extra error handling code
2362
+	 *
2363
+	 * @param string $wpdb_method
2364
+	 * @param array  $arguments_to_provide
2365
+	 * @return mixed
2366
+	 * @throws EE_Error
2367
+	 * @global wpdb  $wpdb
2368
+	 */
2369
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2370
+	{
2371
+		// if we're in maintenance mode level 2, DON'T run any queries
2372
+		// because level 2 indicates the database needs updating and
2373
+		// is probably out of sync with the code
2374
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2375
+			throw new EE_Error(
2376
+				sprintf(
2377
+					esc_html__(
2378
+						"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.",
2379
+						"event_espresso"
2380
+					)
2381
+				)
2382
+			);
2383
+		}
2384
+		/** @type WPDB $wpdb */
2385
+		global $wpdb;
2386
+		if (! method_exists($wpdb, $wpdb_method)) {
2387
+			throw new EE_Error(
2388
+				sprintf(
2389
+					esc_html__(
2390
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2391
+						'event_espresso'
2392
+					),
2393
+					$wpdb_method
2394
+				)
2395
+			);
2396
+		}
2397
+		if (WP_DEBUG) {
2398
+			$old_show_errors_value = $wpdb->show_errors;
2399
+			$wpdb->show_errors(false);
2400
+		}
2401
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2402
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2403
+		if (WP_DEBUG) {
2404
+			$wpdb->show_errors($old_show_errors_value);
2405
+			if (! empty($wpdb->last_error)) {
2406
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2407
+			}
2408
+			if ($result === false) {
2409
+				throw new EE_Error(
2410
+					sprintf(
2411
+						esc_html__(
2412
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2413
+							'event_espresso'
2414
+						),
2415
+						$wpdb_method,
2416
+						var_export($arguments_to_provide, true)
2417
+					)
2418
+				);
2419
+			}
2420
+		} elseif ($result === false) {
2421
+			EE_Error::add_error(
2422
+				sprintf(
2423
+					esc_html__(
2424
+						'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"',
2425
+						'event_espresso'
2426
+					),
2427
+					$wpdb_method,
2428
+					var_export($arguments_to_provide, true),
2429
+					$wpdb->last_error
2430
+				),
2431
+				__FILE__,
2432
+				__FUNCTION__,
2433
+				__LINE__
2434
+			);
2435
+		}
2436
+		return $result;
2437
+	}
2438
+
2439
+
2440
+	/**
2441
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2442
+	 * and if there's an error tries to verify the DB is correct. Uses
2443
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2444
+	 * we should try to fix the EE core db, the addons, or just give up
2445
+	 *
2446
+	 * @param string $wpdb_method
2447
+	 * @param array  $arguments_to_provide
2448
+	 * @return mixed
2449
+	 */
2450
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2451
+	{
2452
+		/** @type WPDB $wpdb */
2453
+		global $wpdb;
2454
+		$wpdb->last_error = null;
2455
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2456
+		// was there an error running the query? but we don't care on new activations
2457
+		// (we're going to setup the DB anyway on new activations)
2458
+		if (
2459
+			($result === false || ! empty($wpdb->last_error))
2460
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2461
+		) {
2462
+			switch (EEM_Base::$_db_verification_level) {
2463
+				case EEM_Base::db_verified_none:
2464
+					// let's double-check core's DB
2465
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2466
+					break;
2467
+				case EEM_Base::db_verified_core:
2468
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2469
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2470
+					break;
2471
+				case EEM_Base::db_verified_addons:
2472
+					// ummmm... you in trouble
2473
+					return $result;
2474
+			}
2475
+			if (! empty($error_message)) {
2476
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2477
+				trigger_error($error_message);
2478
+			}
2479
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2480
+		}
2481
+		return $result;
2482
+	}
2483
+
2484
+
2485
+	/**
2486
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2487
+	 * EEM_Base::$_db_verification_level
2488
+	 *
2489
+	 * @param string $wpdb_method
2490
+	 * @param array  $arguments_to_provide
2491
+	 * @return string
2492
+	 */
2493
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2494
+	{
2495
+		/** @type WPDB $wpdb */
2496
+		global $wpdb;
2497
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2498
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2499
+		$error_message                    = sprintf(
2500
+			esc_html__(
2501
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2502
+				'event_espresso'
2503
+			),
2504
+			$wpdb->last_error,
2505
+			$wpdb_method,
2506
+			wp_json_encode($arguments_to_provide)
2507
+		);
2508
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2509
+		return $error_message;
2510
+	}
2511
+
2512
+
2513
+	/**
2514
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2515
+	 * EEM_Base::$_db_verification_level
2516
+	 *
2517
+	 * @param $wpdb_method
2518
+	 * @param $arguments_to_provide
2519
+	 * @return string
2520
+	 */
2521
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2522
+	{
2523
+		/** @type WPDB $wpdb */
2524
+		global $wpdb;
2525
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2526
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2527
+		$error_message                    = sprintf(
2528
+			esc_html__(
2529
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2530
+				'event_espresso'
2531
+			),
2532
+			$wpdb->last_error,
2533
+			$wpdb_method,
2534
+			wp_json_encode($arguments_to_provide)
2535
+		);
2536
+		EE_System::instance()->initialize_addons();
2537
+		return $error_message;
2538
+	}
2539
+
2540
+
2541
+	/**
2542
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2543
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2544
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2545
+	 * ..."
2546
+	 *
2547
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2548
+	 * @return string
2549
+	 */
2550
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2551
+	{
2552
+		return " FROM " . $model_query_info->get_full_join_sql() .
2553
+			   $model_query_info->get_where_sql() .
2554
+			   $model_query_info->get_group_by_sql() .
2555
+			   $model_query_info->get_having_sql() .
2556
+			   $model_query_info->get_order_by_sql() .
2557
+			   $model_query_info->get_limit_sql();
2558
+	}
2559
+
2560
+
2561
+	/**
2562
+	 * Set to easily debug the next X queries ran from this model.
2563
+	 *
2564
+	 * @param int $count
2565
+	 */
2566
+	public function show_next_x_db_queries($count = 1)
2567
+	{
2568
+		$this->_show_next_x_db_queries = $count;
2569
+	}
2570
+
2571
+
2572
+	/**
2573
+	 * @param $sql_query
2574
+	 */
2575
+	public function show_db_query_if_previously_requested($sql_query)
2576
+	{
2577
+		if ($this->_show_next_x_db_queries > 0) {
2578
+			echo esc_html($sql_query);
2579
+			$this->_show_next_x_db_queries--;
2580
+		}
2581
+	}
2582
+
2583
+
2584
+	/**
2585
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2586
+	 * There are the 3 cases:
2587
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2588
+	 * $otherModelObject has no ID, it is first saved.
2589
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2590
+	 * has no ID, it is first saved.
2591
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2592
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2593
+	 * join table
2594
+	 *
2595
+	 * @param EE_Base_Class                     /int $thisModelObject
2596
+	 * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2597
+	 * @param string $relationName                     , key in EEM_Base::_relations
2598
+	 *                                                 an attendee to a group, you also want to specify which role they
2599
+	 *                                                 will have in that group. So you would use this parameter to
2600
+	 *                                                 specify array('role-column-name'=>'role-id')
2601
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2602
+	 *                                                 to for relation to methods that allow you to further specify
2603
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2604
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2605
+	 *                                                 because these will be inserted in any new rows created as well.
2606
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2607
+	 * @throws EE_Error
2608
+	 */
2609
+	public function add_relationship_to(
2610
+		$id_or_obj,
2611
+		$other_model_id_or_obj,
2612
+		$relationName,
2613
+		$extra_join_model_fields_n_values = []
2614
+	) {
2615
+		$relation_obj = $this->related_settings_for($relationName);
2616
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2617
+	}
2618
+
2619
+
2620
+	/**
2621
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2622
+	 * There are the 3 cases:
2623
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2624
+	 * error
2625
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2626
+	 * an error
2627
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2628
+	 *
2629
+	 * @param EE_Base_Class /int $id_or_obj
2630
+	 * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2631
+	 * @param string $relationName key in EEM_Base::_relations
2632
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2633
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2634
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2635
+	 *                             because these will be inserted in any new rows created as well.
2636
+	 * @return boolean of success
2637
+	 * @throws EE_Error
2638
+	 */
2639
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2640
+	{
2641
+		$relation_obj = $this->related_settings_for($relationName);
2642
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2643
+	}
2644
+
2645
+
2646
+	/**
2647
+	 * @param mixed  $id_or_obj
2648
+	 * @param string $relationName
2649
+	 * @param array  $where_query_params
2650
+	 * @param EE_Base_Class[] objects to which relations were removed
2651
+	 * @return EE_Base_Class[]
2652
+	 * @throws EE_Error
2653
+	 */
2654
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2655
+	{
2656
+		$relation_obj = $this->related_settings_for($relationName);
2657
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2658
+	}
2659
+
2660
+
2661
+	/**
2662
+	 * Gets all the related items of the specified $model_name, using $query_params.
2663
+	 * Note: by default, we remove the "default query params"
2664
+	 * because we want to get even deleted items etc.
2665
+	 *
2666
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2667
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2668
+	 * @param array  $query_params @see
2669
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2670
+	 * @return EE_Base_Class[]
2671
+	 * @throws EE_Error
2672
+	 * @throws ReflectionException
2673
+	 */
2674
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2675
+	{
2676
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2677
+		$relation_settings = $this->related_settings_for($model_name);
2678
+		return $relation_settings->get_all_related($model_obj, $query_params);
2679
+	}
2680
+
2681
+
2682
+	/**
2683
+	 * Deletes all the model objects across the relation indicated by $model_name
2684
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2685
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2686
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2687
+	 *
2688
+	 * @param EE_Base_Class|int|string $id_or_obj
2689
+	 * @param string                   $model_name
2690
+	 * @param array                    $query_params
2691
+	 * @return int how many deleted
2692
+	 * @throws EE_Error
2693
+	 * @throws ReflectionException
2694
+	 */
2695
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2696
+	{
2697
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2698
+		$relation_settings = $this->related_settings_for($model_name);
2699
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2700
+	}
2701
+
2702
+
2703
+	/**
2704
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2705
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2706
+	 * the model objects can't be hard deleted because of blocking related model objects,
2707
+	 * just does a soft-delete on them instead.
2708
+	 *
2709
+	 * @param EE_Base_Class|int|string $id_or_obj
2710
+	 * @param string                   $model_name
2711
+	 * @param array                    $query_params
2712
+	 * @return int how many deleted
2713
+	 * @throws EE_Error
2714
+	 * @throws ReflectionException
2715
+	 */
2716
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2717
+	{
2718
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2719
+		$relation_settings = $this->related_settings_for($model_name);
2720
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2721
+	}
2722
+
2723
+
2724
+	/**
2725
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2726
+	 * unless otherwise specified in the $query_params
2727
+	 *
2728
+	 * @param int             /EE_Base_Class $id_or_obj
2729
+	 * @param string $model_name     like 'Event', or 'Registration'
2730
+	 * @param array  $query_params   @see
2731
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2732
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2733
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2734
+	 *                               that by the setting $distinct to TRUE;
2735
+	 * @return int
2736
+	 * @throws EE_Error
2737
+	 */
2738
+	public function count_related(
2739
+		$id_or_obj,
2740
+		$model_name,
2741
+		$query_params = [],
2742
+		$field_to_count = null,
2743
+		$distinct = false
2744
+	) {
2745
+		$related_model = $this->get_related_model_obj($model_name);
2746
+		// we're just going to use the query params on the related model's normal get_all query,
2747
+		// except add a condition to say to match the current mod
2748
+		if (! isset($query_params['default_where_conditions'])) {
2749
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2750
+		}
2751
+		$this_model_name                                                 = $this->get_this_model_name();
2752
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2753
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2754
+		return $related_model->count($query_params, $field_to_count, $distinct);
2755
+	}
2756
+
2757
+
2758
+	/**
2759
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2760
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2761
+	 *
2762
+	 * @param int           /EE_Base_Class $id_or_obj
2763
+	 * @param string $model_name   like 'Event', or 'Registration'
2764
+	 * @param array  $query_params @see
2765
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2766
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2767
+	 * @return float
2768
+	 * @throws EE_Error
2769
+	 */
2770
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2771
+	{
2772
+		$related_model = $this->get_related_model_obj($model_name);
2773
+		if (! is_array($query_params)) {
2774
+			EE_Error::doing_it_wrong(
2775
+				'EEM_Base::sum_related',
2776
+				sprintf(
2777
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2778
+					gettype($query_params)
2779
+				),
2780
+				'4.6.0'
2781
+			);
2782
+			$query_params = [];
2783
+		}
2784
+		// we're just going to use the query params on the related model's normal get_all query,
2785
+		// except add a condition to say to match the current mod
2786
+		if (! isset($query_params['default_where_conditions'])) {
2787
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2788
+		}
2789
+		$this_model_name                                                 = $this->get_this_model_name();
2790
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2791
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2792
+		return $related_model->sum($query_params, $field_to_sum);
2793
+	}
2794
+
2795
+
2796
+	/**
2797
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2798
+	 * $modelObject
2799
+	 *
2800
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2801
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2802
+	 * @param array               $query_params     @see
2803
+	 *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2804
+	 * @return EE_Base_Class
2805
+	 * @throws EE_Error
2806
+	 */
2807
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2808
+	{
2809
+		$query_params['limit'] = 1;
2810
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2811
+		if ($results) {
2812
+			return array_shift($results);
2813
+		}
2814
+		return null;
2815
+	}
2816
+
2817
+
2818
+	/**
2819
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2820
+	 *
2821
+	 * @return string
2822
+	 */
2823
+	public function get_this_model_name()
2824
+	{
2825
+		return str_replace("EEM_", "", get_class($this));
2826
+	}
2827
+
2828
+
2829
+	/**
2830
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2831
+	 *
2832
+	 * @return EE_Any_Foreign_Model_Name_Field
2833
+	 * @throws EE_Error
2834
+	 */
2835
+	public function get_field_containing_related_model_name()
2836
+	{
2837
+		foreach ($this->field_settings(true) as $field) {
2838
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2839
+				$field_with_model_name = $field;
2840
+			}
2841
+		}
2842
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2843
+			throw new EE_Error(
2844
+				sprintf(
2845
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2846
+					$this->get_this_model_name()
2847
+				)
2848
+			);
2849
+		}
2850
+		return $field_with_model_name;
2851
+	}
2852
+
2853
+
2854
+	/**
2855
+	 * Inserts a new entry into the database, for each table.
2856
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2857
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2858
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2859
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2860
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2861
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2862
+	 *
2863
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2864
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2865
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2866
+	 *                              of EEM_Base)
2867
+	 * @return int|string new primary key on main table that got inserted
2868
+	 * @throws EE_Error
2869
+	 */
2870
+	public function insert($field_n_values)
2871
+	{
2872
+		/**
2873
+		 * Filters the fields and their values before inserting an item using the models
2874
+		 *
2875
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2876
+		 * @param EEM_Base $model           the model used
2877
+		 */
2878
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2879
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2880
+			$main_table = $this->_get_main_table();
2881
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2882
+			if ($new_id !== false) {
2883
+				foreach ($this->_get_other_tables() as $other_table) {
2884
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2885
+				}
2886
+			}
2887
+			/**
2888
+			 * Done just after attempting to insert a new model object
2889
+			 *
2890
+			 * @param EEM_Base $model           used
2891
+			 * @param array    $fields_n_values fields and their values
2892
+			 * @param int|string the              ID of the newly-inserted model object
2893
+			 */
2894
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2895
+			return $new_id;
2896
+		}
2897
+		return false;
2898
+	}
2899
+
2900
+
2901
+	/**
2902
+	 * Checks that the result would satisfy the unique indexes on this model
2903
+	 *
2904
+	 * @param array  $field_n_values
2905
+	 * @param string $action
2906
+	 * @return boolean
2907
+	 * @throws EE_Error
2908
+	 */
2909
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2910
+	{
2911
+		foreach ($this->unique_indexes() as $index_name => $index) {
2912
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2913
+			if ($this->exists([$uniqueness_where_params])) {
2914
+				EE_Error::add_error(
2915
+					sprintf(
2916
+						esc_html__(
2917
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2918
+							"event_espresso"
2919
+						),
2920
+						$action,
2921
+						$this->_get_class_name(),
2922
+						$index_name,
2923
+						implode(",", $index->field_names()),
2924
+						http_build_query($uniqueness_where_params)
2925
+					),
2926
+					__FILE__,
2927
+					__FUNCTION__,
2928
+					__LINE__
2929
+				);
2930
+				return false;
2931
+			}
2932
+		}
2933
+		return true;
2934
+	}
2935
+
2936
+
2937
+	/**
2938
+	 * Checks the database for an item that conflicts (ie, if this item were
2939
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2940
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2941
+	 * can be either an EE_Base_Class or an array of fields n values
2942
+	 *
2943
+	 * @param EE_Base_Class|array $obj_or_fields_array
2944
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2945
+	 *                                                 when looking for conflicts
2946
+	 *                                                 (ie, if false, we ignore the model object's primary key
2947
+	 *                                                 when finding "conflicts". If true, it's also considered).
2948
+	 *                                                 Only works for INT primary key,
2949
+	 *                                                 STRING primary keys cannot be ignored
2950
+	 * @return EE_Base_Class|array
2951
+	 * @throws EE_Error
2952
+	 * @throws ReflectionException
2953
+	 */
2954
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2955
+	{
2956
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2957
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2958
+		} elseif (is_array($obj_or_fields_array)) {
2959
+			$fields_n_values = $obj_or_fields_array;
2960
+		} else {
2961
+			throw new EE_Error(
2962
+				sprintf(
2963
+					esc_html__(
2964
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2965
+						"event_espresso"
2966
+					),
2967
+					get_class($this),
2968
+					$obj_or_fields_array
2969
+				)
2970
+			);
2971
+		}
2972
+		$query_params = [];
2973
+		if (
2974
+			$this->has_primary_key_field()
2975
+			&& ($include_primary_key
2976
+				|| $this->get_primary_key_field()
2977
+				   instanceof
2978
+				   EE_Primary_Key_String_Field)
2979
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2980
+		) {
2981
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2982
+		}
2983
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2984
+			$uniqueness_where_params                              =
2985
+				array_intersect_key($fields_n_values, $unique_index->fields());
2986
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2987
+		}
2988
+		// if there is nothing to base this search on, then we shouldn't find anything
2989
+		if (empty($query_params)) {
2990
+			return [];
2991
+		}
2992
+		return $this->get_one($query_params);
2993
+	}
2994
+
2995
+
2996
+	/**
2997
+	 * Like count, but is optimized and returns a boolean instead of an int
2998
+	 *
2999
+	 * @param array $query_params
3000
+	 * @return boolean
3001
+	 * @throws EE_Error
3002
+	 */
3003
+	public function exists($query_params)
3004
+	{
3005
+		$query_params['limit'] = 1;
3006
+		return $this->count($query_params) > 0;
3007
+	}
3008
+
3009
+
3010
+	/**
3011
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
3012
+	 *
3013
+	 * @param int|string $id
3014
+	 * @return boolean
3015
+	 * @throws EE_Error
3016
+	 */
3017
+	public function exists_by_ID($id)
3018
+	{
3019
+		return $this->exists(
3020
+			[
3021
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3022
+				[
3023
+					$this->primary_key_name() => $id,
3024
+				],
3025
+			]
3026
+		);
3027
+	}
3028
+
3029
+
3030
+	/**
3031
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3032
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3033
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3034
+	 * on the main table)
3035
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3036
+	 * cases where we want to call it directly rather than via insert().
3037
+	 *
3038
+	 * @access   protected
3039
+	 * @param EE_Table_Base $table
3040
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3041
+	 *                                       float
3042
+	 * @param int           $new_id          for now we assume only int keys
3043
+	 * @return int ID of new row inserted, or FALSE on failure
3044
+	 * @throws EE_Error
3045
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3046
+	 */
3047
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3048
+	{
3049
+		global $wpdb;
3050
+		$insertion_col_n_values = [];
3051
+		$format_for_insertion   = [];
3052
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3053
+		foreach ($fields_on_table as $field_name => $field_obj) {
3054
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3055
+			if ($field_obj->is_auto_increment()) {
3056
+				continue;
3057
+			}
3058
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3059
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3060
+			if ($prepared_value !== null) {
3061
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3062
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3063
+			}
3064
+		}
3065
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3066
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3067
+			// so add the fk to the main table as a column
3068
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3069
+			$format_for_insertion[]                              =
3070
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3071
+		}
3072
+
3073
+		// insert the new entry
3074
+		$result = $this->_do_wpdb_query(
3075
+			'insert',
3076
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3077
+		);
3078
+		if ($result === false) {
3079
+			return false;
3080
+		}
3081
+		// ok, now what do we return for the ID of the newly-inserted thing?
3082
+		if ($this->has_primary_key_field()) {
3083
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3084
+				return $wpdb->insert_id;
3085
+			}
3086
+			// it's not an auto-increment primary key, so
3087
+			// it must have been supplied
3088
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3089
+		}
3090
+		// we can't return a  primary key because there is none. instead return
3091
+		// a unique string indicating this model
3092
+		return $this->get_index_primary_key_string($fields_n_values);
3093
+	}
3094
+
3095
+
3096
+	/**
3097
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3098
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3099
+	 * and there is no default, we pass it along. WPDB will take care of it)
3100
+	 *
3101
+	 * @param EE_Model_Field_Base $field_obj
3102
+	 * @param array               $fields_n_values
3103
+	 * @return mixed string|int|float depending on what the table column will be expecting
3104
+	 * @throws EE_Error
3105
+	 */
3106
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3107
+	{
3108
+		$field_name = $field_obj->get_name();
3109
+		// if this field doesn't allow nullable, don't allow it
3110
+		if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3111
+			$fields_n_values[ $field_name ] = $field_obj->get_default_value();
3112
+		}
3113
+		$unprepared_value = $fields_n_values[ $field_name ] ?? null;
3114
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3115
+	}
3116
+
3117
+
3118
+	/**
3119
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3120
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3121
+	 * the field's prepare_for_set() method.
3122
+	 *
3123
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3124
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3125
+	 *                                   top of file)
3126
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3127
+	 *                                   $value is a custom selection
3128
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3129
+	 */
3130
+	private function _prepare_value_for_use_in_db($value, $field)
3131
+	{
3132
+		if ($field instanceof EE_Model_Field_Base) {
3133
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3134
+			switch ($this->_values_already_prepared_by_model_object) {
3135
+				/** @noinspection PhpMissingBreakStatementInspection */
3136
+				case self::not_prepared_by_model_object:
3137
+					$value = $field->prepare_for_set($value);
3138
+				// purposefully left out "return"
3139
+				// no break
3140
+				case self::prepared_by_model_object:
3141
+					/** @noinspection SuspiciousAssignmentsInspection */
3142
+					$value = $field->prepare_for_use_in_db($value);
3143
+				// no break
3144
+				case self::prepared_for_use_in_db:
3145
+					// leave the value alone
3146
+			}
3147
+			// phpcs:enable
3148
+		}
3149
+		return $value;
3150
+	}
3151
+
3152
+
3153
+	/**
3154
+	 * Returns the main table on this model
3155
+	 *
3156
+	 * @return EE_Primary_Table
3157
+	 * @throws EE_Error
3158
+	 */
3159
+	protected function _get_main_table()
3160
+	{
3161
+		foreach ($this->_tables as $table) {
3162
+			if ($table instanceof EE_Primary_Table) {
3163
+				return $table;
3164
+			}
3165
+		}
3166
+		throw new EE_Error(
3167
+			sprintf(
3168
+				esc_html__(
3169
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3170
+					'event_espresso'
3171
+				),
3172
+				get_class($this)
3173
+			)
3174
+		);
3175
+	}
3176
+
3177
+
3178
+	/**
3179
+	 * table
3180
+	 * returns EE_Primary_Table table name
3181
+	 *
3182
+	 * @return string
3183
+	 * @throws EE_Error
3184
+	 */
3185
+	public function table()
3186
+	{
3187
+		return $this->_get_main_table()->get_table_name();
3188
+	}
3189
+
3190
+
3191
+	/**
3192
+	 * table
3193
+	 * returns first EE_Secondary_Table table name
3194
+	 *
3195
+	 * @return string
3196
+	 */
3197
+	public function second_table()
3198
+	{
3199
+		// grab second table from tables array
3200
+		$second_table = end($this->_tables);
3201
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3202
+	}
3203
+
3204
+
3205
+	/**
3206
+	 * get_table_obj_by_alias
3207
+	 * returns table name given it's alias
3208
+	 *
3209
+	 * @param string $table_alias
3210
+	 * @return EE_Primary_Table | EE_Secondary_Table
3211
+	 */
3212
+	public function get_table_obj_by_alias($table_alias = '')
3213
+	{
3214
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3215
+	}
3216
+
3217
+
3218
+	/**
3219
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3220
+	 *
3221
+	 * @return EE_Secondary_Table[]
3222
+	 */
3223
+	protected function _get_other_tables()
3224
+	{
3225
+		$other_tables = [];
3226
+		foreach ($this->_tables as $table_alias => $table) {
3227
+			if ($table instanceof EE_Secondary_Table) {
3228
+				$other_tables[ $table_alias ] = $table;
3229
+			}
3230
+		}
3231
+		return $other_tables;
3232
+	}
3233
+
3234
+
3235
+	/**
3236
+	 * Finds all the fields that correspond to the given table
3237
+	 *
3238
+	 * @param string $table_alias , array key in EEM_Base::_tables
3239
+	 * @return EE_Model_Field_Base[]
3240
+	 */
3241
+	public function _get_fields_for_table($table_alias)
3242
+	{
3243
+		return $this->_fields[ $table_alias ];
3244
+	}
3245
+
3246
+
3247
+	/**
3248
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3249
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3250
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3251
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3252
+	 * related Registration, Transaction, and Payment models.
3253
+	 *
3254
+	 * @param array $query_params @see
3255
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3256
+	 * @return EE_Model_Query_Info_Carrier
3257
+	 * @throws EE_Error
3258
+	 */
3259
+	public function _extract_related_models_from_query($query_params)
3260
+	{
3261
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3262
+		if (array_key_exists(0, $query_params)) {
3263
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3264
+		}
3265
+		if (array_key_exists('group_by', $query_params)) {
3266
+			if (is_array($query_params['group_by'])) {
3267
+				$this->_extract_related_models_from_sub_params_array_values(
3268
+					$query_params['group_by'],
3269
+					$query_info_carrier,
3270
+					'group_by'
3271
+				);
3272
+			} elseif (! empty($query_params['group_by'])) {
3273
+				$this->_extract_related_model_info_from_query_param(
3274
+					$query_params['group_by'],
3275
+					$query_info_carrier,
3276
+					'group_by'
3277
+				);
3278
+			}
3279
+		}
3280
+		if (array_key_exists('having', $query_params)) {
3281
+			$this->_extract_related_models_from_sub_params_array_keys(
3282
+				$query_params[0],
3283
+				$query_info_carrier,
3284
+				'having'
3285
+			);
3286
+		}
3287
+		if (array_key_exists('order_by', $query_params)) {
3288
+			if (is_array($query_params['order_by'])) {
3289
+				$this->_extract_related_models_from_sub_params_array_keys(
3290
+					$query_params['order_by'],
3291
+					$query_info_carrier,
3292
+					'order_by'
3293
+				);
3294
+			} elseif (! empty($query_params['order_by'])) {
3295
+				$this->_extract_related_model_info_from_query_param(
3296
+					$query_params['order_by'],
3297
+					$query_info_carrier,
3298
+					'order_by'
3299
+				);
3300
+			}
3301
+		}
3302
+		if (array_key_exists('force_join', $query_params)) {
3303
+			$this->_extract_related_models_from_sub_params_array_values(
3304
+				$query_params['force_join'],
3305
+				$query_info_carrier,
3306
+				'force_join'
3307
+			);
3308
+		}
3309
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3310
+		return $query_info_carrier;
3311
+	}
3312
+
3313
+
3314
+	/**
3315
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3316
+	 *
3317
+	 * @param array                       $sub_query_params @see
3318
+	 *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3319
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3320
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3321
+	 * @return EE_Model_Query_Info_Carrier
3322
+	 * @throws EE_Error
3323
+	 */
3324
+	private function _extract_related_models_from_sub_params_array_keys(
3325
+		$sub_query_params,
3326
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3327
+		$query_param_type
3328
+	) {
3329
+		if (! empty($sub_query_params)) {
3330
+			$sub_query_params = (array) $sub_query_params;
3331
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3332
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3333
+				$this->_extract_related_model_info_from_query_param(
3334
+					$param,
3335
+					$model_query_info_carrier,
3336
+					$query_param_type
3337
+				);
3338
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3339
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3340
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3341
+				// of array('Registration.TXN_ID'=>23)
3342
+				$query_param_sans_stars =
3343
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3344
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3345
+					if (! is_array($possibly_array_of_params)) {
3346
+						throw new EE_Error(
3347
+							sprintf(
3348
+								esc_html__(
3349
+									"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'))",
3350
+									"event_espresso"
3351
+								),
3352
+								$param,
3353
+								$possibly_array_of_params
3354
+							)
3355
+						);
3356
+					}
3357
+					$this->_extract_related_models_from_sub_params_array_keys(
3358
+						$possibly_array_of_params,
3359
+						$model_query_info_carrier,
3360
+						$query_param_type
3361
+					);
3362
+				} elseif (
3363
+					$query_param_type === 0 // ie WHERE
3364
+					&& is_array($possibly_array_of_params)
3365
+					&& isset($possibly_array_of_params[2])
3366
+					&& $possibly_array_of_params[2] == true
3367
+				) {
3368
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3369
+					// indicating that $possible_array_of_params[1] is actually a field name,
3370
+					// from which we should extract query parameters!
3371
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3372
+						throw new EE_Error(
3373
+							sprintf(
3374
+								esc_html__(
3375
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3376
+									"event_espresso"
3377
+								),
3378
+								$query_param_type,
3379
+								implode(",", $possibly_array_of_params)
3380
+							)
3381
+						);
3382
+					}
3383
+					$this->_extract_related_model_info_from_query_param(
3384
+						$possibly_array_of_params[1],
3385
+						$model_query_info_carrier,
3386
+						$query_param_type
3387
+					);
3388
+				}
3389
+			}
3390
+		}
3391
+		return $model_query_info_carrier;
3392
+	}
3393
+
3394
+
3395
+	/**
3396
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3397
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3398
+	 *
3399
+	 * @param array                       $sub_query_params @see
3400
+	 *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3401
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3402
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3403
+	 * @return EE_Model_Query_Info_Carrier
3404
+	 * @throws EE_Error
3405
+	 */
3406
+	private function _extract_related_models_from_sub_params_array_values(
3407
+		$sub_query_params,
3408
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3409
+		$query_param_type
3410
+	) {
3411
+		if (! empty($sub_query_params)) {
3412
+			if (! is_array($sub_query_params)) {
3413
+				throw new EE_Error(
3414
+					sprintf(
3415
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3416
+						$sub_query_params
3417
+					)
3418
+				);
3419
+			}
3420
+			foreach ($sub_query_params as $param) {
3421
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3422
+				$this->_extract_related_model_info_from_query_param(
3423
+					$param,
3424
+					$model_query_info_carrier,
3425
+					$query_param_type
3426
+				);
3427
+			}
3428
+		}
3429
+		return $model_query_info_carrier;
3430
+	}
3431
+
3432
+
3433
+	/**
3434
+	 * Extract all the query parts from  model query params
3435
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3436
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3437
+	 * but use them in a different order. Eg, we need to know what models we are querying
3438
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3439
+	 * other models before we can finalize the where clause SQL.
3440
+	 *
3441
+	 * @param array $query_params @see
3442
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3443
+	 * @return EE_Model_Query_Info_Carrier
3444
+	 * @throws EE_Error
3445
+	 * @throws ModelConfigurationException*@throws ReflectionException
3446
+	 * @throws ReflectionException
3447
+	 */
3448
+	public function _create_model_query_info_carrier($query_params)
3449
+	{
3450
+		if (! is_array($query_params)) {
3451
+			EE_Error::doing_it_wrong(
3452
+				'EEM_Base::_create_model_query_info_carrier',
3453
+				sprintf(
3454
+					esc_html__(
3455
+						'$query_params should be an array, you passed a variable of type %s',
3456
+						'event_espresso'
3457
+					),
3458
+					gettype($query_params)
3459
+				),
3460
+				'4.6.0'
3461
+			);
3462
+			$query_params = [];
3463
+		}
3464
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3465
+		// first check if we should alter the query to account for caps or not
3466
+		// because the caps might require us to do extra joins
3467
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3468
+			$query_params[0] = array_replace_recursive(
3469
+				$query_params[0],
3470
+				$this->caps_where_conditions($query_params['caps'])
3471
+			);
3472
+		}
3473
+
3474
+		// check if we should alter the query to remove data related to protected
3475
+		// custom post types
3476
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3477
+			$where_param_key_for_password = $this->modelChainAndPassword();
3478
+			// only include if related to a cpt where no password has been set
3479
+			$query_params[0]['OR*nopassword'] = [
3480
+				$where_param_key_for_password       => '',
3481
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3482
+			];
3483
+		}
3484
+		$query_object = $this->_extract_related_models_from_query($query_params);
3485
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3486
+		foreach ($query_params[0] as $key => $value) {
3487
+			if (is_int($key)) {
3488
+				throw new EE_Error(
3489
+					sprintf(
3490
+						esc_html__(
3491
+							"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.",
3492
+							"event_espresso"
3493
+						),
3494
+						$key,
3495
+						var_export($value, true),
3496
+						var_export($query_params, true),
3497
+						get_class($this)
3498
+					)
3499
+				);
3500
+			}
3501
+		}
3502
+		if (
3503
+			array_key_exists('default_where_conditions', $query_params)
3504
+			&& ! empty($query_params['default_where_conditions'])
3505
+		) {
3506
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3507
+		} else {
3508
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3509
+		}
3510
+		$query_params[0] = array_merge(
3511
+			$this->_get_default_where_conditions_for_models_in_query(
3512
+				$query_object,
3513
+				$use_default_where_conditions,
3514
+				$query_params[0]
3515
+			),
3516
+			$query_params[0]
3517
+		);
3518
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3519
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3520
+		// So we need to setup a subquery and use that for the main join.
3521
+		// Note for now this only works on the primary table for the model.
3522
+		// So for instance, you could set the limit array like this:
3523
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3524
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3525
+			$query_object->set_main_model_join_sql(
3526
+				$this->_construct_limit_join_select(
3527
+					$query_params['on_join_limit'][0],
3528
+					$query_params['on_join_limit'][1]
3529
+				)
3530
+			);
3531
+		}
3532
+		// set limit
3533
+		if (array_key_exists('limit', $query_params)) {
3534
+			if (is_array($query_params['limit'])) {
3535
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3536
+					$e = sprintf(
3537
+						esc_html__(
3538
+							"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)",
3539
+							"event_espresso"
3540
+						),
3541
+						http_build_query($query_params['limit'])
3542
+					);
3543
+					throw new EE_Error($e . "|" . $e);
3544
+				}
3545
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3546
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3547
+			} elseif (! empty($query_params['limit'])) {
3548
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3549
+			}
3550
+		}
3551
+		// set order by
3552
+		if (array_key_exists('order_by', $query_params)) {
3553
+			if (is_array($query_params['order_by'])) {
3554
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3555
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3556
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3557
+				if (array_key_exists('order', $query_params)) {
3558
+					throw new EE_Error(
3559
+						sprintf(
3560
+							esc_html__(
3561
+								"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 ",
3562
+								"event_espresso"
3563
+							),
3564
+							get_class($this),
3565
+							implode(", ", array_keys($query_params['order_by'])),
3566
+							implode(", ", $query_params['order_by']),
3567
+							$query_params['order']
3568
+						)
3569
+					);
3570
+				}
3571
+				$this->_extract_related_models_from_sub_params_array_keys(
3572
+					$query_params['order_by'],
3573
+					$query_object,
3574
+					'order_by'
3575
+				);
3576
+				// assume it's an array of fields to order by
3577
+				$order_array = [];
3578
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3579
+					$order         = $this->_extract_order($order);
3580
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3581
+				}
3582
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3583
+			} elseif (! empty($query_params['order_by'])) {
3584
+				$this->_extract_related_model_info_from_query_param(
3585
+					$query_params['order_by'],
3586
+					$query_object,
3587
+					'order',
3588
+					$query_params['order_by']
3589
+				);
3590
+				$order = isset($query_params['order'])
3591
+					? $this->_extract_order($query_params['order'])
3592
+					: 'DESC';
3593
+				$query_object->set_order_by_sql(
3594
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3595
+				);
3596
+			}
3597
+		}
3598
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3599
+		if (
3600
+			! array_key_exists('order_by', $query_params)
3601
+			&& array_key_exists('order', $query_params)
3602
+			&& ! empty($query_params['order'])
3603
+		) {
3604
+			$pk_field = $this->get_primary_key_field();
3605
+			$order    = $this->_extract_order($query_params['order']);
3606
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3607
+		}
3608
+		// set group by
3609
+		if (array_key_exists('group_by', $query_params)) {
3610
+			if (is_array($query_params['group_by'])) {
3611
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3612
+				$group_by_array = [];
3613
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3614
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3615
+				}
3616
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3617
+			} elseif (! empty($query_params['group_by'])) {
3618
+				$query_object->set_group_by_sql(
3619
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3620
+				);
3621
+			}
3622
+		}
3623
+		// set having
3624
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3625
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3626
+		}
3627
+		// now, just verify they didn't pass anything wack
3628
+		foreach ($query_params as $query_key => $query_value) {
3629
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3630
+				throw new EE_Error(
3631
+					sprintf(
3632
+						esc_html__(
3633
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3634
+							'event_espresso'
3635
+						),
3636
+						$query_key,
3637
+						get_class($this),
3638
+						//                      print_r( $this->_allowed_query_params, TRUE )
3639
+						implode(',', $this->_allowed_query_params)
3640
+					)
3641
+				);
3642
+			}
3643
+		}
3644
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3645
+		if (empty($main_model_join_sql)) {
3646
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3647
+		}
3648
+		return $query_object;
3649
+	}
3650
+
3651
+
3652
+	/**
3653
+	 * Gets the where conditions that should be imposed on the query based on the
3654
+	 * context (eg reading frontend, backend, edit or delete).
3655
+	 *
3656
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3657
+	 * @return array @see
3658
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3659
+	 * @throws EE_Error
3660
+	 */
3661
+	public function caps_where_conditions($context = self::caps_read)
3662
+	{
3663
+		EEM_Base::verify_is_valid_cap_context($context);
3664
+		$cap_where_conditions = [];
3665
+		$cap_restrictions     = $this->caps_missing($context);
3666
+		/**
3667
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3668
+		 */
3669
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3670
+			$cap_where_conditions = array_replace_recursive(
3671
+				$cap_where_conditions,
3672
+				$restriction_if_no_cap->get_default_where_conditions()
3673
+			);
3674
+		}
3675
+		return apply_filters(
3676
+			'FHEE__EEM_Base__caps_where_conditions__return',
3677
+			$cap_where_conditions,
3678
+			$this,
3679
+			$context,
3680
+			$cap_restrictions
3681
+		);
3682
+	}
3683
+
3684
+
3685
+	/**
3686
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3687
+	 * otherwise throws an exception
3688
+	 *
3689
+	 * @param string $should_be_order_string
3690
+	 * @return string either ASC, asc, DESC or desc
3691
+	 * @throws EE_Error
3692
+	 */
3693
+	private function _extract_order($should_be_order_string)
3694
+	{
3695
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3696
+			return $should_be_order_string;
3697
+		}
3698
+		throw new EE_Error(
3699
+			sprintf(
3700
+				esc_html__(
3701
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3702
+					"event_espresso"
3703
+				),
3704
+				get_class($this),
3705
+				$should_be_order_string
3706
+			)
3707
+		);
3708
+	}
3709
+
3710
+
3711
+	/**
3712
+	 * Looks at all the models which are included in this query, and asks each
3713
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3714
+	 * so they can be merged
3715
+	 *
3716
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3717
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3718
+	 *                                                                  'none' means NO default where conditions will
3719
+	 *                                                                  be used AT ALL during this query.
3720
+	 *                                                                  'other_models_only' means default where
3721
+	 *                                                                  conditions from other models will be used, but
3722
+	 *                                                                  not for this primary model. 'all', the default,
3723
+	 *                                                                  means default where conditions will apply as
3724
+	 *                                                                  normal
3725
+	 * @param array                       $where_query_params           @see
3726
+	 *                                                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3727
+	 * @throws EE_Error
3728
+	 */
3729
+	private function _get_default_where_conditions_for_models_in_query(
3730
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3731
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3732
+		$where_query_params = []
3733
+	) {
3734
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3735
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3736
+			throw new EE_Error(
3737
+				sprintf(
3738
+					esc_html__(
3739
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3740
+						"event_espresso"
3741
+					),
3742
+					$use_default_where_conditions,
3743
+					implode(", ", $allowed_used_default_where_conditions_values)
3744
+				)
3745
+			);
3746
+		}
3747
+		$universal_query_params = [];
3748
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3749
+			$universal_query_params = $this->_get_default_where_conditions();
3750
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3751
+			$universal_query_params = $this->_get_minimum_where_conditions();
3752
+		}
3753
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3754
+			$related_model = $this->get_related_model_obj($model_name);
3755
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3756
+				$related_model_universal_where_params =
3757
+					$related_model->_get_default_where_conditions($model_relation_path);
3758
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3759
+				$related_model_universal_where_params =
3760
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3761
+			} else {
3762
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3763
+				continue;
3764
+			}
3765
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3766
+				$related_model_universal_where_params,
3767
+				$where_query_params,
3768
+				$related_model,
3769
+				$model_relation_path
3770
+			);
3771
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3772
+				$universal_query_params,
3773
+				$overrides
3774
+			);
3775
+		}
3776
+		return $universal_query_params;
3777
+	}
3778
+
3779
+
3780
+	/**
3781
+	 * Determines whether or not we should use default where conditions for the model in question
3782
+	 * (this model, or other related models).
3783
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3784
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3785
+	 * We should use default where conditions on related models when they requested to use default where conditions
3786
+	 * on all models, or specifically just on other related models
3787
+	 *
3788
+	 * @param      $default_where_conditions_value
3789
+	 * @param bool $for_this_model false means this is for OTHER related models
3790
+	 * @return bool
3791
+	 */
3792
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3793
+	{
3794
+		return (
3795
+				   $for_this_model
3796
+				   && in_array(
3797
+					   $default_where_conditions_value,
3798
+					   [
3799
+						   EEM_Base::default_where_conditions_all,
3800
+						   EEM_Base::default_where_conditions_this_only,
3801
+						   EEM_Base::default_where_conditions_minimum_others,
3802
+					   ],
3803
+					   true
3804
+				   )
3805
+			   )
3806
+			   || (
3807
+				   ! $for_this_model
3808
+				   && in_array(
3809
+					   $default_where_conditions_value,
3810
+					   [
3811
+						   EEM_Base::default_where_conditions_all,
3812
+						   EEM_Base::default_where_conditions_others_only,
3813
+					   ],
3814
+					   true
3815
+				   )
3816
+			   );
3817
+	}
3818
+
3819
+
3820
+	/**
3821
+	 * Determines whether or not we should use default minimum conditions for the model in question
3822
+	 * (this model, or other related models).
3823
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3824
+	 * where conditions.
3825
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3826
+	 * on this model or others
3827
+	 *
3828
+	 * @param      $default_where_conditions_value
3829
+	 * @param bool $for_this_model false means this is for OTHER related models
3830
+	 * @return bool
3831
+	 */
3832
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3833
+	{
3834
+		return (
3835
+				   $for_this_model
3836
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3837
+			   )
3838
+			   || (
3839
+				   ! $for_this_model
3840
+				   && in_array(
3841
+					   $default_where_conditions_value,
3842
+					   [
3843
+						   EEM_Base::default_where_conditions_minimum_others,
3844
+						   EEM_Base::default_where_conditions_minimum_all,
3845
+					   ],
3846
+					   true
3847
+				   )
3848
+			   );
3849
+	}
3850
+
3851
+
3852
+	/**
3853
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3854
+	 * then we also add a special where condition which allows for that model's primary key
3855
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3856
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3857
+	 *
3858
+	 * @param array    $default_where_conditions
3859
+	 * @param array    $provided_where_conditions
3860
+	 * @param EEM_Base $model
3861
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3862
+	 * @return array @see
3863
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3864
+	 * @throws EE_Error
3865
+	 */
3866
+	private function _override_defaults_or_make_null_friendly(
3867
+		$default_where_conditions,
3868
+		$provided_where_conditions,
3869
+		$model,
3870
+		$model_relation_path
3871
+	) {
3872
+		$null_friendly_where_conditions = [];
3873
+		$none_overridden                = true;
3874
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3875
+		foreach ($default_where_conditions as $key => $val) {
3876
+			if (isset($provided_where_conditions[ $key ])) {
3877
+				$none_overridden = false;
3878
+			} else {
3879
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3880
+			}
3881
+		}
3882
+		if ($none_overridden && $default_where_conditions) {
3883
+			if ($model->has_primary_key_field()) {
3884
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3885
+																				   . "."
3886
+																				   . $model->primary_key_name() ] =
3887
+					['IS NULL'];
3888
+			}/*else{
3889 3889
                 //@todo NO PK, use other defaults
3890 3890
             }*/
3891
-        }
3892
-        return $null_friendly_where_conditions;
3893
-    }
3894
-
3895
-
3896
-    /**
3897
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3898
-     * default where conditions on all get_all, update, and delete queries done by this model.
3899
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3900
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3901
-     *
3902
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3903
-     * @return array @see
3904
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3905
-     * @throws EE_Error
3906
-     * @throws EE_Error
3907
-     */
3908
-    private function _get_default_where_conditions($model_relation_path = '')
3909
-    {
3910
-        if ($this->_ignore_where_strategy) {
3911
-            return [];
3912
-        }
3913
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3914
-    }
3915
-
3916
-
3917
-    /**
3918
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3919
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3920
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3921
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3922
-     * Similar to _get_default_where_conditions
3923
-     *
3924
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3925
-     * @return array @see
3926
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3927
-     * @throws EE_Error
3928
-     * @throws EE_Error
3929
-     */
3930
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3931
-    {
3932
-        if ($this->_ignore_where_strategy) {
3933
-            return [];
3934
-        }
3935
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3936
-    }
3937
-
3938
-
3939
-    /**
3940
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3941
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3942
-     *
3943
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3944
-     * @return string
3945
-     * @throws EE_Error
3946
-     */
3947
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3948
-    {
3949
-        $selects = $this->_get_columns_to_select_for_this_model();
3950
-        foreach (
3951
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3952
-        ) {
3953
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3954
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3955
-            foreach ($other_model_selects as $key => $value) {
3956
-                $selects[] = $value;
3957
-            }
3958
-        }
3959
-        return implode(", ", $selects);
3960
-    }
3961
-
3962
-
3963
-    /**
3964
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3965
-     * So that's going to be the columns for all the fields on the model
3966
-     *
3967
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3968
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3969
-     */
3970
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3971
-    {
3972
-        $fields                                       = $this->field_settings();
3973
-        $selects                                      = [];
3974
-        $table_alias_with_model_relation_chain_prefix =
3975
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3976
-                $model_relation_chain,
3977
-                $this->get_this_model_name()
3978
-            );
3979
-        foreach ($fields as $field_obj) {
3980
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3981
-                         . $field_obj->get_table_alias()
3982
-                         . "."
3983
-                         . $field_obj->get_table_column()
3984
-                         . " AS '"
3985
-                         . $table_alias_with_model_relation_chain_prefix
3986
-                         . $field_obj->get_table_alias()
3987
-                         . "."
3988
-                         . $field_obj->get_table_column()
3989
-                         . "'";
3990
-        }
3991
-        // make sure we are also getting the PKs of each table
3992
-        $tables = $this->get_tables();
3993
-        if (count($tables) > 1) {
3994
-            foreach ($tables as $table_obj) {
3995
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3996
-                                       . $table_obj->get_fully_qualified_pk_column();
3997
-                if (! in_array($qualified_pk_column, $selects)) {
3998
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3999
-                }
4000
-            }
4001
-        }
4002
-        return $selects;
4003
-    }
4004
-
4005
-
4006
-    /**
4007
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4008
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4009
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4010
-     * SQL for joining, and the data types
4011
-     *
4012
-     * @param null|string                 $original_query_param
4013
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
4014
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4015
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4016
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4017
-     *                                                          column name. We only want model names, eg 'Event.Venue'
4018
-     *                                                          or 'Registration's
4019
-     * @param string                      $original_query_param what it originally was (eg
4020
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4021
-     *                                                          matches $query_param
4022
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4023
-     * @throws EE_Error
4024
-     */
4025
-    private function _extract_related_model_info_from_query_param(
4026
-        $query_param,
4027
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4028
-        $query_param_type,
4029
-        $original_query_param = null
4030
-    ) {
4031
-        if ($original_query_param === null) {
4032
-            $original_query_param = $query_param;
4033
-        }
4034
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4035
-        // check to see if we have a field on this model
4036
-        $this_model_fields = $this->field_settings(true);
4037
-        if (array_key_exists($query_param, $this_model_fields)) {
4038
-            $field_is_allowed = in_array(
4039
-                $query_param_type,
4040
-                [0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4041
-                true
4042
-            );
4043
-            if ($field_is_allowed) {
4044
-                return;
4045
-            }
4046
-            throw new EE_Error(
4047
-                sprintf(
4048
-                    esc_html__(
4049
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4050
-                        "event_espresso"
4051
-                    ),
4052
-                    $query_param,
4053
-                    get_class($this),
4054
-                    $query_param_type,
4055
-                    $original_query_param
4056
-                )
4057
-            );
4058
-        }
4059
-        // check if this is a special logic query param
4060
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4061
-            $operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4062
-            if ($operator_is_allowed) {
4063
-                return;
4064
-            }
4065
-            throw new EE_Error(
4066
-                sprintf(
4067
-                    esc_html__(
4068
-                        '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',
4069
-                        'event_espresso'
4070
-                    ),
4071
-                    implode('", "', $this->_logic_query_param_keys),
4072
-                    $query_param,
4073
-                    get_class($this),
4074
-                    '<br />',
4075
-                    "\t"
4076
-                    . ' $passed_in_query_info = <pre>'
4077
-                    . print_r($passed_in_query_info, true)
4078
-                    . '</pre>'
4079
-                    . "\n\t"
4080
-                    . ' $query_param_type = '
4081
-                    . $query_param_type
4082
-                    . "\n\t"
4083
-                    . ' $original_query_param = '
4084
-                    . $original_query_param
4085
-                )
4086
-            );
4087
-        }
4088
-        // check if it's a custom selection
4089
-        if (
4090
-            $this->_custom_selections instanceof CustomSelects
4091
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4092
-        ) {
4093
-            return;
4094
-        }
4095
-        // check if has a model name at the beginning
4096
-        // and
4097
-        // check if it's a field on a related model
4098
-        if (
4099
-            $this->extractJoinModelFromQueryParams(
4100
-                $passed_in_query_info,
4101
-                $query_param,
4102
-                $original_query_param,
4103
-                $query_param_type
4104
-            )
4105
-        ) {
4106
-            return;
4107
-        }
4108
-
4109
-        // ok so $query_param didn't start with a model name
4110
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4111
-        // it's wack, that's what it is
4112
-        throw new EE_Error(
4113
-            sprintf(
4114
-                esc_html__(
4115
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4116
-                    "event_espresso"
4117
-                ),
4118
-                $query_param,
4119
-                get_class($this),
4120
-                $query_param_type,
4121
-                $original_query_param
4122
-            )
4123
-        );
4124
-    }
4125
-
4126
-
4127
-    /**
4128
-     * Extracts any possible join model information from the provided possible_join_string.
4129
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4130
-     * join
4131
-     * parts that should be added to the query.
4132
-     *
4133
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4134
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4135
-     * @param null|string                 $original_query_param
4136
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4137
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4138
-     *                                                           etc.)
4139
-     * @return bool  returns true if a join was added and false if not.
4140
-     * @throws EE_Error
4141
-     */
4142
-    private function extractJoinModelFromQueryParams(
4143
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4144
-        $possible_join_string,
4145
-        $original_query_param,
4146
-        $query_parameter_type
4147
-    ) {
4148
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4149
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4150
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4151
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4152
-                if ($possible_join_string === '') {
4153
-                    // nothing left to $query_param
4154
-                    // we should actually end in a field name, not a model like this!
4155
-                    throw new EE_Error(
4156
-                        sprintf(
4157
-                            esc_html__(
4158
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4159
-                                "event_espresso"
4160
-                            ),
4161
-                            $possible_join_string,
4162
-                            $query_parameter_type,
4163
-                            get_class($this),
4164
-                            $valid_related_model_name
4165
-                        )
4166
-                    );
4167
-                }
4168
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4169
-                $related_model_obj->_extract_related_model_info_from_query_param(
4170
-                    $possible_join_string,
4171
-                    $query_info_carrier,
4172
-                    $query_parameter_type,
4173
-                    $original_query_param
4174
-                );
4175
-                return true;
4176
-            }
4177
-            if ($possible_join_string === $valid_related_model_name) {
4178
-                $this->_add_join_to_model(
4179
-                    $valid_related_model_name,
4180
-                    $query_info_carrier,
4181
-                    $original_query_param
4182
-                );
4183
-                return true;
4184
-            }
4185
-        }
4186
-        return false;
4187
-    }
4188
-
4189
-
4190
-    /**
4191
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4192
-     *
4193
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4194
-     * @throws EE_Error
4195
-     */
4196
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4197
-    {
4198
-        if (
4199
-            $this->_custom_selections instanceof CustomSelects
4200
-            && (
4201
-                $this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4202
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4203
-            )
4204
-        ) {
4205
-            $original_selects = $this->_custom_selections->originalSelects();
4206
-            foreach ($original_selects as $alias => $select_configuration) {
4207
-                $this->extractJoinModelFromQueryParams(
4208
-                    $query_info_carrier,
4209
-                    $select_configuration[0],
4210
-                    $select_configuration[0],
4211
-                    'custom_selects'
4212
-                );
4213
-            }
4214
-        }
4215
-    }
4216
-
4217
-
4218
-    /**
4219
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4220
-     * and store it on $passed_in_query_info
4221
-     *
4222
-     * @param string                      $model_name
4223
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4224
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4225
-     *                                                          model and $model_name. Eg, if we are querying Event,
4226
-     *                                                          and are adding a join to 'Payment' with the original
4227
-     *                                                          query param key
4228
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4229
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4230
-     *                                                          Payment wants to add default query params so that it
4231
-     *                                                          will know what models to prepend onto its default query
4232
-     *                                                          params or in case it wants to rename tables (in case
4233
-     *                                                          there are multiple joins to the same table)
4234
-     * @return void
4235
-     * @throws EE_Error
4236
-     */
4237
-    private function _add_join_to_model(
4238
-        $model_name,
4239
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4240
-        $original_query_param
4241
-    ) {
4242
-        $relation_obj         = $this->related_settings_for($model_name);
4243
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4244
-        // check if the relation is HABTM, because then we're essentially doing two joins
4245
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4246
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4247
-            $join_model_obj = $relation_obj->get_join_model();
4248
-            // replace the model specified with the join model for this relation chain, whi
4249
-            $relation_chain_to_join_model =
4250
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4251
-                    $model_name,
4252
-                    $join_model_obj->get_this_model_name(),
4253
-                    $model_relation_chain
4254
-                );
4255
-            $passed_in_query_info->merge(
4256
-                new EE_Model_Query_Info_Carrier(
4257
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4258
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4259
-                )
4260
-            );
4261
-        }
4262
-        // now just join to the other table pointed to by the relation object, and add its data types
4263
-        $passed_in_query_info->merge(
4264
-            new EE_Model_Query_Info_Carrier(
4265
-                [$model_relation_chain => $model_name],
4266
-                $relation_obj->get_join_statement($model_relation_chain)
4267
-            )
4268
-        );
4269
-    }
4270
-
4271
-
4272
-    /**
4273
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4274
-     *
4275
-     * @param array $where_params @see
4276
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4277
-     * @return string of SQL
4278
-     * @throws EE_Error
4279
-     */
4280
-    private function _construct_where_clause($where_params)
4281
-    {
4282
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4283
-        if ($SQL) {
4284
-            return " WHERE " . $SQL;
4285
-        }
4286
-        return '';
4287
-    }
4288
-
4289
-
4290
-    /**
4291
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4292
-     * and should be passed HAVING parameters, not WHERE parameters
4293
-     *
4294
-     * @param array $having_params
4295
-     * @return string
4296
-     * @throws EE_Error
4297
-     */
4298
-    private function _construct_having_clause($having_params)
4299
-    {
4300
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4301
-        if ($SQL) {
4302
-            return " HAVING " . $SQL;
4303
-        }
4304
-        return '';
4305
-    }
4306
-
4307
-
4308
-    /**
4309
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4310
-     * Event_Meta.meta_value = 'foo'))"
4311
-     *
4312
-     * @param array  $where_params @see
4313
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4314
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4315
-     * @return string of SQL
4316
-     * @throws EE_Error
4317
-     */
4318
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4319
-    {
4320
-        $where_clauses = [];
4321
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4322
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4323
-            if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4324
-                switch ($query_param) {
4325
-                    case 'not':
4326
-                    case 'NOT':
4327
-                        $where_clauses[] = "! ("
4328
-                                           . $this->_construct_condition_clause_recursive(
4329
-                                               $op_and_value_or_sub_condition,
4330
-                                               $glue
4331
-                                           )
4332
-                                           . ")";
4333
-                        break;
4334
-                    case 'and':
4335
-                    case 'AND':
4336
-                        $where_clauses[] = " ("
4337
-                                           . $this->_construct_condition_clause_recursive(
4338
-                                               $op_and_value_or_sub_condition,
4339
-                                               ' AND '
4340
-                                           )
4341
-                                           . ")";
4342
-                        break;
4343
-                    case 'or':
4344
-                    case 'OR':
4345
-                        $where_clauses[] = " ("
4346
-                                           . $this->_construct_condition_clause_recursive(
4347
-                                               $op_and_value_or_sub_condition,
4348
-                                               ' OR '
4349
-                                           )
4350
-                                           . ")";
4351
-                        break;
4352
-                }
4353
-            } else {
4354
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4355
-                // if it's not a normal field, maybe it's a custom selection?
4356
-                if (! $field_obj) {
4357
-                    if ($this->_custom_selections instanceof CustomSelects) {
4358
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4359
-                    } else {
4360
-                        throw new EE_Error(
4361
-                            sprintf(
4362
-                                esc_html__(
4363
-                                    "%s is neither a valid model field name, nor a custom selection",
4364
-                                    "event_espresso"
4365
-                                ),
4366
-                                $query_param
4367
-                            )
4368
-                        );
4369
-                    }
4370
-                }
4371
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4372
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4373
-            }
4374
-        }
4375
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4376
-    }
4377
-
4378
-
4379
-    /**
4380
-     * Takes the input parameter and extract the table name (alias) and column name
4381
-     *
4382
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4383
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4384
-     * @throws EE_Error
4385
-     */
4386
-    private function _deduce_column_name_from_query_param($query_param)
4387
-    {
4388
-        $field = $this->_deduce_field_from_query_param($query_param);
4389
-        if ($field) {
4390
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4391
-                $field->get_model_name(),
4392
-                $query_param
4393
-            );
4394
-            return $table_alias_prefix . $field->get_qualified_column();
4395
-        }
4396
-        if (
4397
-            $this->_custom_selections instanceof CustomSelects
4398
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4399
-        ) {
4400
-            // maybe it's custom selection item?
4401
-            // if so, just use it as the "column name"
4402
-            return $query_param;
4403
-        }
4404
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4405
-            ? implode(',', $this->_custom_selections->columnAliases())
4406
-            : '';
4407
-        throw new EE_Error(
4408
-            sprintf(
4409
-                esc_html__(
4410
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4411
-                    "event_espresso"
4412
-                ),
4413
-                $query_param,
4414
-                $custom_select_aliases
4415
-            )
4416
-        );
4417
-    }
4418
-
4419
-
4420
-    /**
4421
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4422
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4423
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4424
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4425
-     *
4426
-     * @param string $condition_query_param_key
4427
-     * @return string
4428
-     */
4429
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4430
-    {
4431
-        $pos_of_star = strpos($condition_query_param_key, '*');
4432
-        if ($pos_of_star === false) {
4433
-            return $condition_query_param_key;
4434
-        }
4435
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4436
-        return $condition_query_param_sans_star;
4437
-    }
4438
-
4439
-
4440
-    /**
4441
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4442
-     *
4443
-     * @param mixed      array | string    $op_and_value
4444
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4445
-     * @return string
4446
-     * @throws EE_Error
4447
-     */
4448
-    private function _construct_op_and_value($op_and_value, $field_obj)
4449
-    {
4450
-        if (is_array($op_and_value)) {
4451
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4452
-            if (! $operator) {
4453
-                $php_array_like_string = [];
4454
-                foreach ($op_and_value as $key => $value) {
4455
-                    $php_array_like_string[] = "$key=>$value";
4456
-                }
4457
-                throw new EE_Error(
4458
-                    sprintf(
4459
-                        esc_html__(
4460
-                            "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))",
4461
-                            "event_espresso"
4462
-                        ),
4463
-                        implode(",", $php_array_like_string)
4464
-                    )
4465
-                );
4466
-            }
4467
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4468
-        } else {
4469
-            $operator = '=';
4470
-            $value    = $op_and_value;
4471
-        }
4472
-        // check to see if the value is actually another field
4473
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4474
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4475
-        }
4476
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4477
-            // in this case, the value should be an array, or at least a comma-separated list
4478
-            // it will need to handle a little differently
4479
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4480
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4481
-            return $operator . SP . $cleaned_value;
4482
-        }
4483
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4484
-            // the value should be an array with count of two.
4485
-            if (count($value) !== 2) {
4486
-                throw new EE_Error(
4487
-                    sprintf(
4488
-                        esc_html__(
4489
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4490
-                            'event_espresso'
4491
-                        ),
4492
-                        "BETWEEN"
4493
-                    )
4494
-                );
4495
-            }
4496
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4497
-            return $operator . SP . $cleaned_value;
4498
-        }
4499
-        if (in_array($operator, $this->valid_null_style_operators())) {
4500
-            if ($value !== null) {
4501
-                throw new EE_Error(
4502
-                    sprintf(
4503
-                        esc_html__(
4504
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4505
-                            "event_espresso"
4506
-                        ),
4507
-                        $value,
4508
-                        $operator
4509
-                    )
4510
-                );
4511
-            }
4512
-            return $operator;
4513
-        }
4514
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4515
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4516
-            // remove other junk. So just treat it as a string.
4517
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4518
-        }
4519
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4520
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4521
-        }
4522
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4523
-            throw new EE_Error(
4524
-                sprintf(
4525
-                    esc_html__(
4526
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4527
-                        'event_espresso'
4528
-                    ),
4529
-                    $operator,
4530
-                    $operator
4531
-                )
4532
-            );
4533
-        }
4534
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4535
-            throw new EE_Error(
4536
-                sprintf(
4537
-                    esc_html__(
4538
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4539
-                        'event_espresso'
4540
-                    ),
4541
-                    $operator,
4542
-                    $operator
4543
-                )
4544
-            );
4545
-        }
4546
-        throw new EE_Error(
4547
-            sprintf(
4548
-                esc_html__(
4549
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4550
-                    "event_espresso"
4551
-                ),
4552
-                http_build_query($op_and_value)
4553
-            )
4554
-        );
4555
-    }
4556
-
4557
-
4558
-    /**
4559
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4560
-     *
4561
-     * @param array                      $values
4562
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4563
-     *                                              '%s'
4564
-     * @return string
4565
-     * @throws EE_Error
4566
-     */
4567
-    public function _construct_between_value($values, $field_obj)
4568
-    {
4569
-        $cleaned_values = [];
4570
-        foreach ($values as $value) {
4571
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4572
-        }
4573
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4574
-    }
4575
-
4576
-
4577
-    /**
4578
-     * Takes an array or a comma-separated list of $values and cleans them
4579
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4580
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4581
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4582
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4583
-     *
4584
-     * @param mixed                      $values    array or comma-separated string
4585
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4586
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4587
-     * @throws EE_Error
4588
-     */
4589
-    public function _construct_in_value($values, $field_obj)
4590
-    {
4591
-        $prepped = [];
4592
-        // check if the value is a CSV list
4593
-        if (is_string($values)) {
4594
-            // in which case, turn it into an array
4595
-            $values = explode(',', $values);
4596
-        }
4597
-        // make sure we only have one of each value in the list
4598
-        $values = array_unique($values);
4599
-        foreach ($values as $value) {
4600
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4601
-        }
4602
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4603
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4604
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4605
-        if (empty($prepped)) {
4606
-            $all_fields  = $this->field_settings();
4607
-            $first_field = reset($all_fields);
4608
-            $main_table  = $this->_get_main_table();
4609
-            $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4610
-        }
4611
-        return '(' . implode(',', $prepped) . ')';
4612
-    }
4613
-
4614
-
4615
-    /**
4616
-     * @param mixed                      $value
4617
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4618
-     * @return false|null|string
4619
-     * @throws EE_Error
4620
-     */
4621
-    private function _wpdb_prepare_using_field($value, $field_obj)
4622
-    {
4623
-        /** @type WPDB $wpdb */
4624
-        global $wpdb;
4625
-        if ($field_obj instanceof EE_Model_Field_Base) {
4626
-            return $wpdb->prepare(
4627
-                $field_obj->get_wpdb_data_type(),
4628
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4629
-            );
4630
-        } //$field_obj should really just be a data type
4631
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4632
-            throw new EE_Error(
4633
-                sprintf(
4634
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4635
-                    $field_obj,
4636
-                    implode(",", $this->_valid_wpdb_data_types)
4637
-                )
4638
-            );
4639
-        }
4640
-        return $wpdb->prepare($field_obj, $value);
4641
-    }
4642
-
4643
-
4644
-    /**
4645
-     * Takes the input parameter and finds the model field that it indicates.
4646
-     *
4647
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4648
-     * @return EE_Model_Field_Base
4649
-     * @throws EE_Error
4650
-     */
4651
-    protected function _deduce_field_from_query_param($query_param_name)
4652
-    {
4653
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4654
-        // which will help us find the database table and column
4655
-        $query_param_parts = explode(".", $query_param_name);
4656
-        if (empty($query_param_parts)) {
4657
-            throw new EE_Error(
4658
-                sprintf(
4659
-                    esc_html__(
4660
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4661
-                        'event_espresso'
4662
-                    ),
4663
-                    $query_param_name
4664
-                )
4665
-            );
4666
-        }
4667
-        $number_of_parts       = count($query_param_parts);
4668
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4669
-        if ($number_of_parts === 1) {
4670
-            $field_name = $last_query_param_part;
4671
-            $model_obj  = $this;
4672
-        } else {// $number_of_parts >= 2
4673
-            // the last part is the column name, and there are only 2parts. therefore...
4674
-            $field_name = $last_query_param_part;
4675
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4676
-        }
4677
-        try {
4678
-            return $model_obj->field_settings_for($field_name);
4679
-        } catch (EE_Error $e) {
4680
-            return null;
4681
-        }
4682
-    }
4683
-
4684
-
4685
-    /**
4686
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4687
-     * alias and column which corresponds to it
4688
-     *
4689
-     * @param string $field_name
4690
-     * @return string
4691
-     * @throws EE_Error
4692
-     */
4693
-    public function _get_qualified_column_for_field($field_name)
4694
-    {
4695
-        $all_fields = $this->field_settings();
4696
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4697
-        if ($field) {
4698
-            return $field->get_qualified_column();
4699
-        }
4700
-        throw new EE_Error(
4701
-            sprintf(
4702
-                esc_html__(
4703
-                    "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.",
4704
-                    'event_espresso'
4705
-                ),
4706
-                $field_name,
4707
-                get_class($this)
4708
-            )
4709
-        );
4710
-    }
4711
-
4712
-
4713
-    /**
4714
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4715
-     * Example usage:
4716
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4717
-     *      array(),
4718
-     *      ARRAY_A,
4719
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4720
-     *  );
4721
-     * is equivalent to
4722
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4723
-     * and
4724
-     *  EEM_Event::instance()->get_all_wpdb_results(
4725
-     *      array(
4726
-     *          array(
4727
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4728
-     *          ),
4729
-     *          ARRAY_A,
4730
-     *          implode(
4731
-     *              ', ',
4732
-     *              array_merge(
4733
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4734
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4735
-     *              )
4736
-     *          )
4737
-     *      )
4738
-     *  );
4739
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4740
-     *
4741
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4742
-     *                                            and the one whose fields you are selecting for example: when querying
4743
-     *                                            tickets model and selecting fields from the tickets model you would
4744
-     *                                            leave this parameter empty, because no models are needed to join
4745
-     *                                            between the queried model and the selected one. Likewise when
4746
-     *                                            querying the datetime model and selecting fields from the tickets
4747
-     *                                            model, it would also be left empty, because there is a direct
4748
-     *                                            relation from datetimes to tickets, so no model is needed to join
4749
-     *                                            them together. However, when querying from the event model and
4750
-     *                                            selecting fields from the ticket model, you should provide the string
4751
-     *                                            'Datetime', indicating that the event model must first join to the
4752
-     *                                            datetime model in order to find its relation to ticket model.
4753
-     *                                            Also, when querying from the venue model and selecting fields from
4754
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4755
-     *                                            indicating you need to join the venue model to the event model,
4756
-     *                                            to the datetime model, in order to find its relation to the ticket
4757
-     *                                            model. This string is used to deduce the prefix that gets added onto
4758
-     *                                            the models' tables qualified columns
4759
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4760
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4761
-     *                                            qualified column names
4762
-     * @return array|string
4763
-     */
4764
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4765
-    {
4766
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4767
-        $qualified_columns = [];
4768
-        foreach ($this->field_settings() as $field_name => $field) {
4769
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4770
-        }
4771
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4772
-    }
4773
-
4774
-
4775
-    /**
4776
-     * constructs the select use on special limit joins
4777
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4778
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4779
-     * (as that is typically where the limits would be set).
4780
-     *
4781
-     * @param string       $table_alias The table the select is being built for
4782
-     * @param mixed|string $limit       The limit for this select
4783
-     * @return string                The final select join element for the query.
4784
-     * @throws EE_Error
4785
-     * @throws EE_Error
4786
-     */
4787
-    public function _construct_limit_join_select($table_alias, $limit)
4788
-    {
4789
-        $SQL = '';
4790
-        foreach ($this->_tables as $table_obj) {
4791
-            if ($table_obj instanceof EE_Primary_Table) {
4792
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4793
-                    ? $table_obj->get_select_join_limit($limit)
4794
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4795
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4796
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4797
-                    ? $table_obj->get_select_join_limit_join($limit)
4798
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4799
-            }
4800
-        }
4801
-        return $SQL;
4802
-    }
4803
-
4804
-
4805
-    /**
4806
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4807
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4808
-     *
4809
-     * @return string SQL
4810
-     * @throws EE_Error
4811
-     */
4812
-    public function _construct_internal_join()
4813
-    {
4814
-        $SQL = $this->_get_main_table()->get_table_sql();
4815
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4816
-        return $SQL;
4817
-    }
4818
-
4819
-
4820
-    /**
4821
-     * Constructs the SQL for joining all the tables on this model.
4822
-     * Normally $alias should be the primary table's alias, but in cases where
4823
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4824
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4825
-     * alias, this will construct SQL like:
4826
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4827
-     * With $alias being a secondary table's alias, this will construct SQL like:
4828
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4829
-     *
4830
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4831
-     * @return string
4832
-     * @throws EE_Error
4833
-     * @throws EE_Error
4834
-     */
4835
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4836
-    {
4837
-        $SQL               = '';
4838
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4839
-        foreach ($this->_tables as $table_obj) {
4840
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4841
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4842
-                    // so we're joining to this table, meaning the table is already in
4843
-                    // the FROM statement, BUT the primary table isn't. So we want
4844
-                    // to add the inverse join sql
4845
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4846
-                } else {
4847
-                    // just add a regular JOIN to this table from the primary table
4848
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4849
-                }
4850
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4851
-        }
4852
-        return $SQL;
4853
-    }
4854
-
4855
-
4856
-    /**
4857
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4858
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4859
-     * their data type (eg, '%s', '%d', etc)
4860
-     *
4861
-     * @return array
4862
-     */
4863
-    public function _get_data_types()
4864
-    {
4865
-        $data_types = [];
4866
-        foreach ($this->field_settings() as $field_obj) {
4867
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4868
-            /** @var $field_obj EE_Model_Field_Base */
4869
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4870
-        }
4871
-        return $data_types;
4872
-    }
4873
-
4874
-
4875
-    /**
4876
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4877
-     *
4878
-     * @param string $model_name
4879
-     * @return EEM_Base
4880
-     * @throws EE_Error
4881
-     */
4882
-    public function get_related_model_obj($model_name)
4883
-    {
4884
-        $model_classname = "EEM_" . $model_name;
4885
-        if (! class_exists($model_classname)) {
4886
-            throw new EE_Error(
4887
-                sprintf(
4888
-                    esc_html__(
4889
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4890
-                        'event_espresso'
4891
-                    ),
4892
-                    $model_name,
4893
-                    $model_classname
4894
-                )
4895
-            );
4896
-        }
4897
-        return call_user_func($model_classname . "::instance");
4898
-    }
4899
-
4900
-
4901
-    /**
4902
-     * Returns the array of EE_ModelRelations for this model.
4903
-     *
4904
-     * @return EE_Model_Relation_Base[]
4905
-     */
4906
-    public function relation_settings()
4907
-    {
4908
-        return $this->_model_relations;
4909
-    }
4910
-
4911
-
4912
-    /**
4913
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4914
-     * because without THOSE models, this model probably doesn't have much purpose.
4915
-     * (Eg, without an event, datetimes have little purpose.)
4916
-     *
4917
-     * @return EE_Belongs_To_Relation[]
4918
-     */
4919
-    public function belongs_to_relations()
4920
-    {
4921
-        $belongs_to_relations = [];
4922
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4923
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4924
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4925
-            }
4926
-        }
4927
-        return $belongs_to_relations;
4928
-    }
4929
-
4930
-
4931
-    /**
4932
-     * Returns the specified EE_Model_Relation, or throws an exception
4933
-     *
4934
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4935
-     * @return EE_Model_Relation_Base
4936
-     * @throws EE_Error
4937
-     */
4938
-    public function related_settings_for($relation_name)
4939
-    {
4940
-        $relatedModels = $this->relation_settings();
4941
-        if (! array_key_exists($relation_name, $relatedModels)) {
4942
-            throw new EE_Error(
4943
-                sprintf(
4944
-                    esc_html__(
4945
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4946
-                        'event_espresso'
4947
-                    ),
4948
-                    $relation_name,
4949
-                    $this->_get_class_name(),
4950
-                    implode(', ', array_keys($relatedModels))
4951
-                )
4952
-            );
4953
-        }
4954
-        return $relatedModels[ $relation_name ];
4955
-    }
4956
-
4957
-
4958
-    /**
4959
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4960
-     * fields
4961
-     *
4962
-     * @param string  $fieldName
4963
-     * @param boolean $include_db_only_fields
4964
-     * @return EE_Model_Field_Base
4965
-     * @throws EE_Error
4966
-     */
4967
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4968
-    {
4969
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4970
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4971
-            throw new EE_Error(
4972
-                sprintf(
4973
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4974
-                    $fieldName,
4975
-                    get_class($this)
4976
-                )
4977
-            );
4978
-        }
4979
-        return $fieldSettings[ $fieldName ];
4980
-    }
4981
-
4982
-
4983
-    /**
4984
-     * Checks if this field exists on this model
4985
-     *
4986
-     * @param string $fieldName a key in the model's _field_settings array
4987
-     * @return boolean
4988
-     */
4989
-    public function has_field($fieldName)
4990
-    {
4991
-        $fieldSettings = $this->field_settings(true);
4992
-        if (isset($fieldSettings[ $fieldName ])) {
4993
-            return true;
4994
-        }
4995
-        return false;
4996
-    }
4997
-
4998
-
4999
-    /**
5000
-     * Returns whether or not this model has a relation to the specified model
5001
-     *
5002
-     * @param string $relation_name possibly one of the keys in the relation_settings array
5003
-     * @return boolean
5004
-     */
5005
-    public function has_relation($relation_name)
5006
-    {
5007
-        $relations = $this->relation_settings();
5008
-        if (isset($relations[ $relation_name ])) {
5009
-            return true;
5010
-        }
5011
-        return false;
5012
-    }
5013
-
5014
-
5015
-    /**
5016
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5017
-     * Eg, on EE_Answer that would be ANS_ID field object
5018
-     *
5019
-     * @param $field_obj
5020
-     * @return boolean
5021
-     */
5022
-    public function is_primary_key_field($field_obj)
5023
-    {
5024
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
5025
-    }
5026
-
5027
-
5028
-    /**
5029
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5030
-     * Eg, on EE_Answer that would be ANS_ID field object
5031
-     *
5032
-     * @return EE_Primary_Key_Field_Base
5033
-     * @throws EE_Error
5034
-     */
5035
-    public function get_primary_key_field()
5036
-    {
5037
-        if ($this->_primary_key_field === null) {
5038
-            foreach ($this->field_settings(true) as $field_obj) {
5039
-                if ($this->is_primary_key_field($field_obj)) {
5040
-                    $this->_primary_key_field = $field_obj;
5041
-                    break;
5042
-                }
5043
-            }
5044
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5045
-                throw new EE_Error(
5046
-                    sprintf(
5047
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5048
-                        get_class($this)
5049
-                    )
5050
-                );
5051
-            }
5052
-        }
5053
-        return $this->_primary_key_field;
5054
-    }
5055
-
5056
-
5057
-    /**
5058
-     * Returns whether or not not there is a primary key on this model.
5059
-     * Internally does some caching.
5060
-     *
5061
-     * @return boolean
5062
-     */
5063
-    public function has_primary_key_field()
5064
-    {
5065
-        if ($this->_has_primary_key_field === null) {
5066
-            try {
5067
-                $this->get_primary_key_field();
5068
-                $this->_has_primary_key_field = true;
5069
-            } catch (EE_Error $e) {
5070
-                $this->_has_primary_key_field = false;
5071
-            }
5072
-        }
5073
-        return $this->_has_primary_key_field;
5074
-    }
5075
-
5076
-
5077
-    /**
5078
-     * Finds the first field of type $field_class_name.
5079
-     *
5080
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5081
-     *                                 EE_Foreign_Key_Field, etc
5082
-     * @return EE_Model_Field_Base or null if none is found
5083
-     */
5084
-    public function get_a_field_of_type($field_class_name)
5085
-    {
5086
-        foreach ($this->field_settings() as $field) {
5087
-            if ($field instanceof $field_class_name) {
5088
-                return $field;
5089
-            }
5090
-        }
5091
-        return null;
5092
-    }
5093
-
5094
-
5095
-    /**
5096
-     * Gets a foreign key field pointing to model.
5097
-     *
5098
-     * @param string $model_name eg Event, Registration, not EEM_Event
5099
-     * @return EE_Foreign_Key_Field_Base
5100
-     * @throws EE_Error
5101
-     */
5102
-    public function get_foreign_key_to($model_name)
5103
-    {
5104
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5105
-            foreach ($this->field_settings() as $field) {
5106
-                if (
5107
-                    $field instanceof EE_Foreign_Key_Field_Base
5108
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5109
-                ) {
5110
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5111
-                    break;
5112
-                }
5113
-            }
5114
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5115
-                throw new EE_Error(
5116
-                    sprintf(
5117
-                        esc_html__(
5118
-                            "There is no foreign key field pointing to model %s on model %s",
5119
-                            'event_espresso'
5120
-                        ),
5121
-                        $model_name,
5122
-                        get_class($this)
5123
-                    )
5124
-                );
5125
-            }
5126
-        }
5127
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5128
-    }
5129
-
5130
-
5131
-    /**
5132
-     * Gets the table name (including $wpdb->prefix) for the table alias
5133
-     *
5134
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5135
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5136
-     *                            Either one works
5137
-     * @return string
5138
-     */
5139
-    public function get_table_for_alias($table_alias)
5140
-    {
5141
-        $table_alias_sans_model_relation_chain_prefix =
5142
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5143
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5144
-    }
5145
-
5146
-
5147
-    /**
5148
-     * Returns a flat array of all field son this model, instead of organizing them
5149
-     * by table_alias as they are in the constructor.
5150
-     *
5151
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5152
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5153
-     */
5154
-    public function field_settings($include_db_only_fields = false)
5155
-    {
5156
-        if ($include_db_only_fields) {
5157
-            if ($this->_cached_fields === null) {
5158
-                $this->_cached_fields = [];
5159
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5160
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5161
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5162
-                    }
5163
-                }
5164
-            }
5165
-            return $this->_cached_fields;
5166
-        }
5167
-        if ($this->_cached_fields_non_db_only === null) {
5168
-            $this->_cached_fields_non_db_only = [];
5169
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5170
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5171
-                    /** @var $field_obj EE_Model_Field_Base */
5172
-                    if (! $field_obj->is_db_only_field()) {
5173
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5174
-                    }
5175
-                }
5176
-            }
5177
-        }
5178
-        return $this->_cached_fields_non_db_only;
5179
-    }
5180
-
5181
-
5182
-    /**
5183
-     *        cycle though array of attendees and create objects out of each item
5184
-     *
5185
-     * @access        private
5186
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5187
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5188
-     *                           numerically indexed)
5189
-     * @throws EE_Error
5190
-     * @throws ReflectionException
5191
-     */
5192
-    protected function _create_objects($rows = [])
5193
-    {
5194
-        $array_of_objects = [];
5195
-        if (empty($rows)) {
5196
-            return [];
5197
-        }
5198
-        $count_if_model_has_no_primary_key = 0;
5199
-        $has_primary_key                   = $this->has_primary_key_field();
5200
-        $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5201
-        foreach ((array) $rows as $row) {
5202
-            if (empty($row)) {
5203
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5204
-                return [];
5205
-            }
5206
-            // check if we've already set this object in the results array,
5207
-            // in which case there's no need to process it further (again)
5208
-            if ($has_primary_key) {
5209
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5210
-                    $row,
5211
-                    $primary_key_field->get_qualified_column(),
5212
-                    $primary_key_field->get_table_column()
5213
-                );
5214
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5215
-                    continue;
5216
-                }
5217
-            }
5218
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5219
-            if (! $classInstance) {
5220
-                throw new EE_Error(
5221
-                    sprintf(
5222
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5223
-                        $this->get_this_model_name(),
5224
-                        http_build_query($row)
5225
-                    )
5226
-                );
5227
-            }
5228
-            // set the timezone on the instantiated objects
5229
-            $classInstance->set_timezone($this->_timezone);
5230
-            // make sure if there is any timezone setting present that we set the timezone for the object
5231
-            $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5232
-            $array_of_objects[ $key ] = $classInstance;
5233
-            // also, for all the relations of type BelongsTo, see if we can cache
5234
-            // those related models
5235
-            // (we could do this for other relations too, but if there are conditions
5236
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5237
-            // so it requires a little more thought than just caching them immediately...)
5238
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5239
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5240
-                    // check if this model's INFO is present. If so, cache it on the model
5241
-                    $other_model           = $relation_obj->get_other_model();
5242
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5243
-                    // if we managed to make a model object from the results, cache it on the main model object
5244
-                    if ($other_model_obj_maybe) {
5245
-                        // set timezone on these other model objects if they are present
5246
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5247
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5248
-                    }
5249
-                }
5250
-            }
5251
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5252
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5253
-            // the field in the CustomSelects object
5254
-            if ($this->_custom_selections instanceof CustomSelects) {
5255
-                $classInstance->setCustomSelectsValues(
5256
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5257
-                );
5258
-            }
5259
-        }
5260
-        return $array_of_objects;
5261
-    }
5262
-
5263
-
5264
-    /**
5265
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5266
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5267
-     *
5268
-     * @param array $db_results_row
5269
-     * @return array
5270
-     */
5271
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5272
-    {
5273
-        $results = [];
5274
-        if ($this->_custom_selections instanceof CustomSelects) {
5275
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5276
-                if (isset($db_results_row[ $alias ])) {
5277
-                    $results[ $alias ] = $this->convertValueToDataType(
5278
-                        $db_results_row[ $alias ],
5279
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5280
-                    );
5281
-                }
5282
-            }
5283
-        }
5284
-        return $results;
5285
-    }
5286
-
5287
-
5288
-    /**
5289
-     * This will set the value for the given alias
5290
-     *
5291
-     * @param string $value
5292
-     * @param string $datatype (one of %d, %s, %f)
5293
-     * @return int|string|float (int for %d, string for %s, float for %f)
5294
-     */
5295
-    protected function convertValueToDataType($value, $datatype)
5296
-    {
5297
-        switch ($datatype) {
5298
-            case '%f':
5299
-                return (float) $value;
5300
-            case '%d':
5301
-                return (int) $value;
5302
-            default:
5303
-                return (string) $value;
5304
-        }
5305
-    }
5306
-
5307
-
5308
-    /**
5309
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5310
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5311
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5312
-     * object (as set in the model_field!).
5313
-     *
5314
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5315
-     * @throws EE_Error
5316
-     * @throws ReflectionException
5317
-     */
5318
-    public function create_default_object()
5319
-    {
5320
-        $this_model_fields_and_values = [];
5321
-        // setup the row using default values;
5322
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5323
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5324
-        }
5325
-        $className     = $this->_get_class_name();
5326
-        return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5327
-    }
5328
-
5329
-
5330
-    /**
5331
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5332
-     *                             or an stdClass where each property is the name of a column,
5333
-     * @return EE_Base_Class
5334
-     * @throws EE_Error
5335
-     * @throws ReflectionException
5336
-     */
5337
-    public function instantiate_class_from_array_or_object($cols_n_values)
5338
-    {
5339
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5340
-            $cols_n_values = get_object_vars($cols_n_values);
5341
-        }
5342
-        $primary_key = null;
5343
-        // make sure the array only has keys that are fields/columns on this model
5344
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5345
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5346
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5347
-        }
5348
-        $className = $this->_get_class_name();
5349
-        // check we actually found results that we can use to build our model object
5350
-        // if not, return null
5351
-        if ($this->has_primary_key_field()) {
5352
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5353
-                return null;
5354
-            }
5355
-        } elseif ($this->unique_indexes()) {
5356
-            $first_column = reset($this_model_fields_n_values);
5357
-            if (empty($first_column)) {
5358
-                return null;
5359
-            }
5360
-        }
5361
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5362
-        if ($primary_key) {
5363
-            $classInstance = $this->get_from_entity_map($primary_key);
5364
-            if (! $classInstance) {
5365
-                $classInstance = EE_Registry::instance()
5366
-                                            ->load_class(
5367
-                                                $className,
5368
-                                                [$this_model_fields_n_values, $this->_timezone],
5369
-                                                true,
5370
-                                                false
5371
-                                            );
5372
-                // add this new object to the entity map
5373
-                $classInstance = $this->add_to_entity_map($classInstance);
5374
-            }
5375
-        } else {
5376
-            $classInstance = EE_Registry::instance()
5377
-                                        ->load_class(
5378
-                                            $className,
5379
-                                            [$this_model_fields_n_values, $this->_timezone],
5380
-                                            true,
5381
-                                            false
5382
-                                        );
5383
-        }
5384
-        return $classInstance;
5385
-    }
5386
-
5387
-
5388
-    /**
5389
-     * Gets the model object from the  entity map if it exists
5390
-     *
5391
-     * @param int|string $id the ID of the model object
5392
-     * @return EE_Base_Class
5393
-     */
5394
-    public function get_from_entity_map($id)
5395
-    {
5396
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5397
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5398
-    }
5399
-
5400
-
5401
-    /**
5402
-     * add_to_entity_map
5403
-     * Adds the object to the model's entity mappings
5404
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5405
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5406
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5407
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5408
-     *        then this method should be called immediately after the update query
5409
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5410
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5411
-     *
5412
-     * @param EE_Base_Class $object
5413
-     * @return EE_Base_Class
5414
-     * @throws EE_Error
5415
-     * @throws ReflectionException
5416
-     */
5417
-    public function add_to_entity_map(EE_Base_Class $object)
5418
-    {
5419
-        $className = $this->_get_class_name();
5420
-        if (! $object instanceof $className) {
5421
-            throw new EE_Error(
5422
-                sprintf(
5423
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5424
-                    is_object($object) ? get_class($object) : $object,
5425
-                    $className
5426
-                )
5427
-            );
5428
-        }
5429
-        /** @var $object EE_Base_Class */
5430
-        if (! $object->ID()) {
5431
-            throw new EE_Error(
5432
-                sprintf(
5433
-                    esc_html__(
5434
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5435
-                        "event_espresso"
5436
-                    ),
5437
-                    get_class($this)
5438
-                )
5439
-            );
5440
-        }
5441
-        // double check it's not already there
5442
-        $classInstance = $this->get_from_entity_map($object->ID());
5443
-        if ($classInstance) {
5444
-            return $classInstance;
5445
-        }
5446
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5447
-        return $object;
5448
-    }
5449
-
5450
-
5451
-    /**
5452
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5453
-     * if no identifier is provided, then the entire entity map is emptied
5454
-     *
5455
-     * @param int|string $id the ID of the model object
5456
-     * @return boolean
5457
-     */
5458
-    public function clear_entity_map($id = null)
5459
-    {
5460
-        if (empty($id)) {
5461
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5462
-            return true;
5463
-        }
5464
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5465
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5466
-            return true;
5467
-        }
5468
-        return false;
5469
-    }
5470
-
5471
-
5472
-    /**
5473
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5474
-     * Given an array where keys are column (or column alias) names and values,
5475
-     * returns an array of their corresponding field names and database values
5476
-     *
5477
-     * @param array $cols_n_values
5478
-     * @return array
5479
-     * @throws EE_Error
5480
-     * @throws ReflectionException
5481
-     */
5482
-    public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5483
-    {
5484
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5485
-    }
5486
-
5487
-
5488
-    /**
5489
-     * _deduce_fields_n_values_from_cols_n_values
5490
-     * Given an array where keys are column (or column alias) names and values,
5491
-     * returns an array of their corresponding field names and database values
5492
-     *
5493
-     * @param array|stdClass $cols_n_values
5494
-     * @return array
5495
-     * @throws EE_Error
5496
-     * @throws ReflectionException
5497
-     */
5498
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5499
-    {
5500
-        if ($cols_n_values instanceof stdClass) {
5501
-            $cols_n_values = get_object_vars($cols_n_values);
5502
-        }
5503
-        $this_model_fields_n_values = [];
5504
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5505
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5506
-                $cols_n_values,
5507
-                $table_obj->get_fully_qualified_pk_column(),
5508
-                $table_obj->get_pk_column()
5509
-            );
5510
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5511
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5512
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5513
-                    if (! $field_obj->is_db_only_field()) {
5514
-                        // prepare field as if its coming from db
5515
-                        $prepared_value                            =
5516
-                            $field_obj->prepare_for_set($field_obj->get_default_value());
5517
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5518
-                    }
5519
-                }
5520
-            } else {
5521
-                // the table's rows existed. Use their values
5522
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5523
-                    if (! $field_obj->is_db_only_field()) {
5524
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5525
-                            $cols_n_values,
5526
-                            $field_obj->get_qualified_column(),
5527
-                            $field_obj->get_table_column()
5528
-                        );
5529
-                    }
5530
-                }
5531
-            }
5532
-        }
5533
-        return $this_model_fields_n_values;
5534
-    }
5535
-
5536
-
5537
-    /**
5538
-     * @param $cols_n_values
5539
-     * @param $qualified_column
5540
-     * @param $regular_column
5541
-     * @return null
5542
-     * @throws EE_Error
5543
-     * @throws ReflectionException
5544
-     */
5545
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5546
-    {
5547
-        $value = null;
5548
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5549
-        // does the field on the model relate to this column retrieved from the db?
5550
-        // or is it a db-only field? (not relating to the model)
5551
-        if (isset($cols_n_values[ $qualified_column ])) {
5552
-            $value = $cols_n_values[ $qualified_column ];
5553
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5554
-            $value = $cols_n_values[ $regular_column ];
5555
-        } elseif (! empty($this->foreign_key_aliases)) {
5556
-            // no PK?  ok check if there is a foreign key alias set for this table
5557
-            // then check if that alias exists in the incoming data
5558
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5559
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5560
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5561
-                    $value = $cols_n_values[ $FK_alias ];
5562
-                    [$pk_class] = explode('.', $PK_column);
5563
-                    $pk_model_name = "EEM_{$pk_class}";
5564
-                    /** @var EEM_Base $pk_model */
5565
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5566
-                    if ($pk_model instanceof EEM_Base) {
5567
-                        // make sure object is pulled from db and added to entity map
5568
-                        $pk_model->get_one_by_ID($value);
5569
-                    }
5570
-                    break;
5571
-                }
5572
-            }
5573
-        }
5574
-        return $value;
5575
-    }
5576
-
5577
-
5578
-    /**
5579
-     * refresh_entity_map_from_db
5580
-     * Makes sure the model object in the entity map at $id assumes the values
5581
-     * of the database (opposite of EE_base_Class::save())
5582
-     *
5583
-     * @param int|string $id
5584
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5585
-     * @throws EE_Error
5586
-     * @throws ReflectionException
5587
-     */
5588
-    public function refresh_entity_map_from_db($id)
5589
-    {
5590
-        $obj_in_map = $this->get_from_entity_map($id);
5591
-        if ($obj_in_map) {
5592
-            $wpdb_results = $this->_get_all_wpdb_results(
5593
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5594
-            );
5595
-            if ($wpdb_results && is_array($wpdb_results)) {
5596
-                $one_row = reset($wpdb_results);
5597
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5598
-                    $obj_in_map->set_from_db($field_name, $db_value);
5599
-                }
5600
-                // clear the cache of related model objects
5601
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5602
-                    $obj_in_map->clear_cache($relation_name, null, true);
5603
-                }
5604
-            }
5605
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5606
-            return $obj_in_map;
5607
-        }
5608
-        return $this->get_one_by_ID($id);
5609
-    }
5610
-
5611
-
5612
-    /**
5613
-     * refresh_entity_map_with
5614
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5615
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5616
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5617
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5618
-     *
5619
-     * @param int|string    $id
5620
-     * @param EE_Base_Class $replacing_model_obj
5621
-     * @return EE_Base_Class
5622
-     * @throws EE_Error
5623
-     * @throws ReflectionException
5624
-     */
5625
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5626
-    {
5627
-        $obj_in_map = $this->get_from_entity_map($id);
5628
-        if ($obj_in_map) {
5629
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5630
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5631
-                    $obj_in_map->set($field_name, $value);
5632
-                }
5633
-                // make the model object in the entity map's cache match the $replacing_model_obj
5634
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5635
-                    $obj_in_map->clear_cache($relation_name, null, true);
5636
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5637
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5638
-                    }
5639
-                }
5640
-            }
5641
-            return $obj_in_map;
5642
-        }
5643
-        $this->add_to_entity_map($replacing_model_obj);
5644
-        return $replacing_model_obj;
5645
-    }
5646
-
5647
-
5648
-    /**
5649
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5650
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5651
-     * require_once($this->_getClassName().".class.php");
5652
-     *
5653
-     * @return string
5654
-     */
5655
-    private function _get_class_name()
5656
-    {
5657
-        return "EE_" . $this->get_this_model_name();
5658
-    }
5659
-
5660
-
5661
-    /**
5662
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5663
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5664
-     * it would be 'Events'.
5665
-     *
5666
-     * @param int|float|null $quantity
5667
-     * @return string
5668
-     */
5669
-    public function item_name($quantity = 1): string
5670
-    {
5671
-        $quantity = floor($quantity);
5672
-        return apply_filters(
5673
-            'FHEE__EEM_Base__item_name__plural_or_singular',
5674
-            $quantity > 1 ? $this->plural_item : $this->singular_item,
5675
-            $quantity,
5676
-            $this->plural_item,
5677
-            $this->singular_item
5678
-        );
5679
-    }
5680
-
5681
-
5682
-    /**
5683
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5684
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5685
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5686
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5687
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5688
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5689
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5690
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5691
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5692
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5693
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5694
-     *        return $previousReturnValue.$returnString;
5695
-     * }
5696
-     * require('EEM_Answer.model.php');
5697
-     * echo EEM_Answer::instance()->my_callback('monkeys',100);
5698
-     * // will output "you called my_callback! and passed args:monkeys,100"
5699
-     *
5700
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5701
-     * @param array  $args       array of original arguments passed to the function
5702
-     * @return mixed whatever the plugin which calls add_filter decides
5703
-     * @throws EE_Error
5704
-     */
5705
-    public function __call($methodName, $args)
5706
-    {
5707
-        $className = get_class($this);
5708
-        $tagName   = "FHEE__{$className}__{$methodName}";
5709
-        if (! has_filter($tagName)) {
5710
-            throw new EE_Error(
5711
-                sprintf(
5712
-                    esc_html__(
5713
-                        '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 );',
5714
-                        'event_espresso'
5715
-                    ),
5716
-                    $methodName,
5717
-                    $className,
5718
-                    $tagName,
5719
-                    '<br />'
5720
-                )
5721
-            );
5722
-        }
5723
-        return apply_filters($tagName, null, $this, $args);
5724
-    }
5725
-
5726
-
5727
-    /**
5728
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5729
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5730
-     *
5731
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5732
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5733
-     *                                                       the object's class name
5734
-     *                                                       or object's ID
5735
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5736
-     *                                                       exists in the database. If it does not, we add it
5737
-     * @return EE_Base_Class
5738
-     * @throws EE_Error
5739
-     * @throws ReflectionException
5740
-     */
5741
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5742
-    {
5743
-        $className = $this->_get_class_name();
5744
-        if ($base_class_obj_or_id instanceof $className) {
5745
-            $model_object = $base_class_obj_or_id;
5746
-        } else {
5747
-            $primary_key_field = $this->get_primary_key_field();
5748
-            if (
5749
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5750
-                && (
5751
-                    is_int($base_class_obj_or_id)
5752
-                    || is_string($base_class_obj_or_id)
5753
-                )
5754
-            ) {
5755
-                // assume it's an ID.
5756
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5757
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5758
-            } elseif (
5759
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5760
-                && is_string($base_class_obj_or_id)
5761
-            ) {
5762
-                // assume its a string representation of the object
5763
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5764
-            } else {
5765
-                throw new EE_Error(
5766
-                    sprintf(
5767
-                        esc_html__(
5768
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5769
-                            'event_espresso'
5770
-                        ),
5771
-                        $base_class_obj_or_id,
5772
-                        $this->_get_class_name(),
5773
-                        print_r($base_class_obj_or_id, true)
5774
-                    )
5775
-                );
5776
-            }
5777
-        }
5778
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5779
-            $model_object->save();
5780
-        }
5781
-        return $model_object;
5782
-    }
5783
-
5784
-
5785
-    /**
5786
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5787
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5788
-     * returns it ID.
5789
-     *
5790
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5791
-     * @return int|string depending on the type of this model object's ID
5792
-     * @throws EE_Error
5793
-     * @throws ReflectionException
5794
-     */
5795
-    public function ensure_is_ID($base_class_obj_or_id)
5796
-    {
5797
-        $className = $this->_get_class_name();
5798
-        if ($base_class_obj_or_id instanceof $className) {
5799
-            /** @var $base_class_obj_or_id EE_Base_Class */
5800
-            $id = $base_class_obj_or_id->ID();
5801
-        } elseif (is_int($base_class_obj_or_id)) {
5802
-            // assume it's an ID
5803
-            $id = $base_class_obj_or_id;
5804
-        } elseif (is_string($base_class_obj_or_id)) {
5805
-            // assume its a string representation of the object
5806
-            $id = $base_class_obj_or_id;
5807
-        } else {
5808
-            throw new EE_Error(
5809
-                sprintf(
5810
-                    esc_html__(
5811
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5812
-                        'event_espresso'
5813
-                    ),
5814
-                    $base_class_obj_or_id,
5815
-                    $this->_get_class_name(),
5816
-                    print_r($base_class_obj_or_id, true)
5817
-                )
5818
-            );
5819
-        }
5820
-        return $id;
5821
-    }
5822
-
5823
-
5824
-    /**
5825
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5826
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5827
-     * been sanitized and converted into the appropriate domain.
5828
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5829
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5830
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5831
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5832
-     * $EVT = EEM_Event::instance(); $old_setting =
5833
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5834
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5835
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5836
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5837
-     *
5838
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5839
-     * @return void
5840
-     */
5841
-    public function assume_values_already_prepared_by_model_object(
5842
-        $values_already_prepared = self::not_prepared_by_model_object
5843
-    ) {
5844
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5845
-    }
5846
-
5847
-
5848
-    /**
5849
-     * Read comments for assume_values_already_prepared_by_model_object()
5850
-     *
5851
-     * @return int
5852
-     */
5853
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5854
-    {
5855
-        return $this->_values_already_prepared_by_model_object;
5856
-    }
5857
-
5858
-
5859
-    /**
5860
-     * Gets all the indexes on this model
5861
-     *
5862
-     * @return EE_Index[]
5863
-     */
5864
-    public function indexes()
5865
-    {
5866
-        return $this->_indexes;
5867
-    }
5868
-
5869
-
5870
-    /**
5871
-     * Gets all the Unique Indexes on this model
5872
-     *
5873
-     * @return EE_Unique_Index[]
5874
-     */
5875
-    public function unique_indexes()
5876
-    {
5877
-        $unique_indexes = [];
5878
-        foreach ($this->_indexes as $name => $index) {
5879
-            if ($index instanceof EE_Unique_Index) {
5880
-                $unique_indexes [ $name ] = $index;
5881
-            }
5882
-        }
5883
-        return $unique_indexes;
5884
-    }
5885
-
5886
-
5887
-    /**
5888
-     * Gets all the fields which, when combined, make the primary key.
5889
-     * This is usually just an array with 1 element (the primary key), but in cases
5890
-     * where there is no primary key, it's a combination of fields as defined
5891
-     * on a primary index
5892
-     *
5893
-     * @return EE_Model_Field_Base[] indexed by the field's name
5894
-     * @throws EE_Error
5895
-     */
5896
-    public function get_combined_primary_key_fields()
5897
-    {
5898
-        foreach ($this->indexes() as $index) {
5899
-            if ($index instanceof EE_Primary_Key_Index) {
5900
-                return $index->fields();
5901
-            }
5902
-        }
5903
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5904
-    }
5905
-
5906
-
5907
-    /**
5908
-     * Used to build a primary key string (when the model has no primary key),
5909
-     * which can be used a unique string to identify this model object.
5910
-     *
5911
-     * @param array $fields_n_values keys are field names, values are their values.
5912
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5913
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5914
-     *                               before passing it to this function (that will convert it from columns-n-values
5915
-     *                               to field-names-n-values).
5916
-     * @return string
5917
-     * @throws EE_Error
5918
-     */
5919
-    public function get_index_primary_key_string($fields_n_values)
5920
-    {
5921
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5922
-            $fields_n_values,
5923
-            $this->get_combined_primary_key_fields()
5924
-        );
5925
-        return http_build_query($cols_n_values_for_primary_key_index);
5926
-    }
5927
-
5928
-
5929
-    /**
5930
-     * Gets the field values from the primary key string
5931
-     *
5932
-     * @param string $index_primary_key_string
5933
-     * @return null|array
5934
-     * @throws EE_Error
5935
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5936
-     */
5937
-    public function parse_index_primary_key_string($index_primary_key_string)
5938
-    {
5939
-        $key_fields = $this->get_combined_primary_key_fields();
5940
-        // check all of them are in the $id
5941
-        $key_vals_in_combined_pk = [];
5942
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5943
-        foreach ($key_fields as $key_field_name => $field_obj) {
5944
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5945
-                return null;
5946
-            }
5947
-        }
5948
-        return $key_vals_in_combined_pk;
5949
-    }
5950
-
5951
-
5952
-    /**
5953
-     * verifies that an array of key-value pairs for model fields has a key
5954
-     * for each field comprising the primary key index
5955
-     *
5956
-     * @param array $key_vals
5957
-     * @return boolean
5958
-     * @throws EE_Error
5959
-     */
5960
-    public function has_all_combined_primary_key_fields($key_vals)
5961
-    {
5962
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5963
-        foreach ($keys_it_should_have as $key) {
5964
-            if (! isset($key_vals[ $key ])) {
5965
-                return false;
5966
-            }
5967
-        }
5968
-        return true;
5969
-    }
5970
-
5971
-
5972
-    /**
5973
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5974
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5975
-     *
5976
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5977
-     * @param array               $query_params                     @see
5978
-     *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5979
-     * @throws EE_Error
5980
-     * @throws ReflectionException
5981
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5982
-     *                                                              indexed)
5983
-     */
5984
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5985
-    {
5986
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5987
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5988
-        } elseif (is_array($model_object_or_attributes_array)) {
5989
-            $attributes_array = $model_object_or_attributes_array;
5990
-        } else {
5991
-            throw new EE_Error(
5992
-                sprintf(
5993
-                    esc_html__(
5994
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5995
-                        "event_espresso"
5996
-                    ),
5997
-                    $model_object_or_attributes_array
5998
-                )
5999
-            );
6000
-        }
6001
-        // even copies obviously won't have the same ID, so remove the primary key
6002
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
6003
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6004
-            unset($attributes_array[ $this->primary_key_name() ]);
6005
-        }
6006
-        if (isset($query_params[0])) {
6007
-            $query_params[0] = array_merge($attributes_array, $query_params);
6008
-        } else {
6009
-            $query_params[0] = $attributes_array;
6010
-        }
6011
-        return $this->get_all($query_params);
6012
-    }
6013
-
6014
-
6015
-    /**
6016
-     * Gets the first copy we find. See get_all_copies for more details
6017
-     *
6018
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6019
-     * @param array $query_params
6020
-     * @return EE_Base_Class
6021
-     * @throws EE_Error
6022
-     * @throws ReflectionException
6023
-     */
6024
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6025
-    {
6026
-        if (! is_array($query_params)) {
6027
-            EE_Error::doing_it_wrong(
6028
-                'EEM_Base::get_one_copy',
6029
-                sprintf(
6030
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6031
-                    gettype($query_params)
6032
-                ),
6033
-                '4.6.0'
6034
-            );
6035
-            $query_params = [];
6036
-        }
6037
-        $query_params['limit'] = 1;
6038
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6039
-        if (is_array($copies)) {
6040
-            return array_shift($copies);
6041
-        }
6042
-        return null;
6043
-    }
6044
-
6045
-
6046
-    /**
6047
-     * Updates the item with the specified id. Ignores default query parameters because
6048
-     * we have specified the ID, and its assumed we KNOW what we're doing
6049
-     *
6050
-     * @param array      $fields_n_values keys are field names, values are their new values
6051
-     * @param int|string $id              the value of the primary key to update
6052
-     * @return int number of rows updated
6053
-     * @throws EE_Error
6054
-     * @throws ReflectionException
6055
-     */
6056
-    public function update_by_ID($fields_n_values, $id)
6057
-    {
6058
-        $query_params = [
6059
-            0                          => [$this->get_primary_key_field()->get_name() => $id],
6060
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6061
-        ];
6062
-        return $this->update($fields_n_values, $query_params);
6063
-    }
6064
-
6065
-
6066
-    /**
6067
-     * Changes an operator which was supplied to the models into one usable in SQL
6068
-     *
6069
-     * @param string $operator_supplied
6070
-     * @return string an operator which can be used in SQL
6071
-     * @throws EE_Error
6072
-     */
6073
-    private function _prepare_operator_for_sql($operator_supplied)
6074
-    {
6075
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6076
-        if ($sql_operator) {
6077
-            return $sql_operator;
6078
-        }
6079
-        throw new EE_Error(
6080
-            sprintf(
6081
-                esc_html__(
6082
-                    "The operator '%s' is not in the list of valid operators: %s",
6083
-                    "event_espresso"
6084
-                ),
6085
-                $operator_supplied,
6086
-                implode(",", array_keys($this->_valid_operators))
6087
-            )
6088
-        );
6089
-    }
6090
-
6091
-
6092
-    /**
6093
-     * Gets the valid operators
6094
-     *
6095
-     * @return array keys are accepted strings, values are the SQL they are converted to
6096
-     */
6097
-    public function valid_operators()
6098
-    {
6099
-        return $this->_valid_operators;
6100
-    }
6101
-
6102
-
6103
-    /**
6104
-     * Gets the between-style operators (take 2 arguments).
6105
-     *
6106
-     * @return array keys are accepted strings, values are the SQL they are converted to
6107
-     */
6108
-    public function valid_between_style_operators()
6109
-    {
6110
-        return array_intersect(
6111
-            $this->valid_operators(),
6112
-            $this->_between_style_operators
6113
-        );
6114
-    }
6115
-
6116
-
6117
-    /**
6118
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6119
-     *
6120
-     * @return array keys are accepted strings, values are the SQL they are converted to
6121
-     */
6122
-    public function valid_like_style_operators()
6123
-    {
6124
-        return array_intersect(
6125
-            $this->valid_operators(),
6126
-            $this->_like_style_operators
6127
-        );
6128
-    }
6129
-
6130
-
6131
-    /**
6132
-     * Gets the "in"-style operators
6133
-     *
6134
-     * @return array keys are accepted strings, values are the SQL they are converted to
6135
-     */
6136
-    public function valid_in_style_operators()
6137
-    {
6138
-        return array_intersect(
6139
-            $this->valid_operators(),
6140
-            $this->_in_style_operators
6141
-        );
6142
-    }
6143
-
6144
-
6145
-    /**
6146
-     * Gets the "null"-style operators (accept no arguments)
6147
-     *
6148
-     * @return array keys are accepted strings, values are the SQL they are converted to
6149
-     */
6150
-    public function valid_null_style_operators()
6151
-    {
6152
-        return array_intersect(
6153
-            $this->valid_operators(),
6154
-            $this->_null_style_operators
6155
-        );
6156
-    }
6157
-
6158
-
6159
-    /**
6160
-     * Gets an array where keys are the primary keys and values are their 'names'
6161
-     * (as determined by the model object's name() function, which is often overridden)
6162
-     *
6163
-     * @param array $query_params like get_all's
6164
-     * @return string[]
6165
-     * @throws EE_Error
6166
-     * @throws ReflectionException
6167
-     */
6168
-    public function get_all_names($query_params = [])
6169
-    {
6170
-        $objs  = $this->get_all($query_params);
6171
-        $names = [];
6172
-        foreach ($objs as $obj) {
6173
-            $names[ $obj->ID() ] = $obj->name();
6174
-        }
6175
-        return $names;
6176
-    }
6177
-
6178
-
6179
-    /**
6180
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6181
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6182
-     * this is duplicated effort and reduces efficiency) you would be better to use
6183
-     * array_keys() on $model_objects.
6184
-     *
6185
-     * @param \EE_Base_Class[] $model_objects
6186
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6187
-     *                                               in the returned array
6188
-     * @return array
6189
-     * @throws EE_Error
6190
-     * @throws ReflectionException
6191
-     */
6192
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6193
-    {
6194
-        if (! $this->has_primary_key_field()) {
6195
-            if (WP_DEBUG) {
6196
-                EE_Error::add_error(
6197
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6198
-                    __FILE__,
6199
-                    __FUNCTION__,
6200
-                    __LINE__
6201
-                );
6202
-            }
6203
-        }
6204
-        $IDs = [];
6205
-        foreach ($model_objects as $model_object) {
6206
-            $id = $model_object->ID();
6207
-            if (! $id) {
6208
-                if ($filter_out_empty_ids) {
6209
-                    continue;
6210
-                }
6211
-                if (WP_DEBUG) {
6212
-                    EE_Error::add_error(
6213
-                        esc_html__(
6214
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6215
-                            'event_espresso'
6216
-                        ),
6217
-                        __FILE__,
6218
-                        __FUNCTION__,
6219
-                        __LINE__
6220
-                    );
6221
-                }
6222
-            }
6223
-            $IDs[] = $id;
6224
-        }
6225
-        return $IDs;
6226
-    }
6227
-
6228
-
6229
-    /**
6230
-     * Returns the string used in capabilities relating to this model. If there
6231
-     * are no capabilities that relate to this model returns false
6232
-     *
6233
-     * @return string|false
6234
-     */
6235
-    public function cap_slug()
6236
-    {
6237
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6238
-    }
6239
-
6240
-
6241
-    /**
6242
-     * Returns the capability-restrictions array (@param string $context
6243
-     *
6244
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6245
-     * @throws EE_Error
6246
-     * @see EEM_Base::_cap_restrictions).
6247
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6248
-     *      only returns the cap restrictions array in that context (ie, the array
6249
-     *      at that key)
6250
-     *
6251
-     */
6252
-    public function cap_restrictions($context = EEM_Base::caps_read)
6253
-    {
6254
-        EEM_Base::verify_is_valid_cap_context($context);
6255
-        // check if we ought to run the restriction generator first
6256
-        if (
6257
-            isset($this->_cap_restriction_generators[ $context ])
6258
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6259
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6260
-        ) {
6261
-            $this->_cap_restrictions[ $context ] = array_merge(
6262
-                $this->_cap_restrictions[ $context ],
6263
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6264
-            );
6265
-        }
6266
-        // and make sure we've finalized the construction of each restriction
6267
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6268
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6269
-                $where_conditions_obj->_finalize_construct($this);
6270
-            }
6271
-        }
6272
-        return $this->_cap_restrictions[ $context ];
6273
-    }
6274
-
6275
-
6276
-    /**
6277
-     * Indicating whether or not this model thinks its a wp core model
6278
-     *
6279
-     * @return boolean
6280
-     */
6281
-    public function is_wp_core_model()
6282
-    {
6283
-        return $this->_wp_core_model;
6284
-    }
6285
-
6286
-
6287
-    /**
6288
-     * Gets all the caps that are missing which impose a restriction on
6289
-     * queries made in this context
6290
-     *
6291
-     * @param string $context one of EEM_Base::caps_ constants
6292
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6293
-     * @throws EE_Error
6294
-     */
6295
-    public function caps_missing($context = EEM_Base::caps_read)
6296
-    {
6297
-        $missing_caps     = [];
6298
-        $cap_restrictions = $this->cap_restrictions($context);
6299
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6300
-            if (
6301
-                ! EE_Capabilities::instance()
6302
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6303
-            ) {
6304
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6305
-            }
6306
-        }
6307
-        return $missing_caps;
6308
-    }
6309
-
6310
-
6311
-    /**
6312
-     * Gets the mapping from capability contexts to action strings used in capability names
6313
-     *
6314
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6315
-     * one of 'read', 'edit', or 'delete'
6316
-     */
6317
-    public function cap_contexts_to_cap_action_map()
6318
-    {
6319
-        return apply_filters(
6320
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6321
-            $this->_cap_contexts_to_cap_action_map,
6322
-            $this
6323
-        );
6324
-    }
6325
-
6326
-
6327
-    /**
6328
-     * Gets the action string for the specified capability context
6329
-     *
6330
-     * @param string $context
6331
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6332
-     * @throws EE_Error
6333
-     */
6334
-    public function cap_action_for_context($context)
6335
-    {
6336
-        $mapping = $this->cap_contexts_to_cap_action_map();
6337
-        if (isset($mapping[ $context ])) {
6338
-            return $mapping[ $context ];
6339
-        }
6340
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6341
-            return $action;
6342
-        }
6343
-        throw new EE_Error(
6344
-            sprintf(
6345
-                esc_html__(
6346
-                    'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6347
-                    'event_espresso'
6348
-                ),
6349
-                $context,
6350
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6351
-            )
6352
-        );
6353
-    }
6354
-
6355
-
6356
-    /**
6357
-     * Returns all the capability contexts which are valid when querying models
6358
-     *
6359
-     * @return array
6360
-     */
6361
-    public static function valid_cap_contexts()
6362
-    {
6363
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', [
6364
-            self::caps_read,
6365
-            self::caps_read_admin,
6366
-            self::caps_edit,
6367
-            self::caps_delete,
6368
-        ]);
6369
-    }
6370
-
6371
-
6372
-    /**
6373
-     * Returns all valid options for 'default_where_conditions'
6374
-     *
6375
-     * @return array
6376
-     */
6377
-    public static function valid_default_where_conditions()
6378
-    {
6379
-        return [
6380
-            EEM_Base::default_where_conditions_all,
6381
-            EEM_Base::default_where_conditions_this_only,
6382
-            EEM_Base::default_where_conditions_others_only,
6383
-            EEM_Base::default_where_conditions_minimum_all,
6384
-            EEM_Base::default_where_conditions_minimum_others,
6385
-            EEM_Base::default_where_conditions_none,
6386
-        ];
6387
-    }
6388
-
6389
-    // public static function default_where_conditions_full
6390
-
6391
-
6392
-    /**
6393
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6394
-     *
6395
-     * @param string $context
6396
-     * @return bool
6397
-     * @throws EE_Error
6398
-     */
6399
-    public static function verify_is_valid_cap_context($context)
6400
-    {
6401
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6402
-        if (in_array($context, $valid_cap_contexts)) {
6403
-            return true;
6404
-        }
6405
-        throw new EE_Error(
6406
-            sprintf(
6407
-                esc_html__(
6408
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6409
-                    'event_espresso'
6410
-                ),
6411
-                $context,
6412
-                'EEM_Base',
6413
-                implode(',', $valid_cap_contexts)
6414
-            )
6415
-        );
6416
-    }
6417
-
6418
-
6419
-    /**
6420
-     * Clears all the models field caches. This is only useful when a sub-class
6421
-     * might have added a field or something and these caches might be invalidated
6422
-     */
6423
-    protected function _invalidate_field_caches()
6424
-    {
6425
-        $this->_cache_foreign_key_to_fields = [];
6426
-        $this->_cached_fields               = null;
6427
-        $this->_cached_fields_non_db_only   = null;
6428
-    }
6429
-
6430
-
6431
-    /**
6432
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6433
-     * (eg "and", "or", "not").
6434
-     *
6435
-     * @return array
6436
-     */
6437
-    public function logic_query_param_keys()
6438
-    {
6439
-        return $this->_logic_query_param_keys;
6440
-    }
6441
-
6442
-
6443
-    /**
6444
-     * Determines whether or not the where query param array key is for a logic query param.
6445
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6446
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6447
-     *
6448
-     * @param $query_param_key
6449
-     * @return bool
6450
-     */
6451
-    public function is_logic_query_param_key($query_param_key)
6452
-    {
6453
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6454
-            if (
6455
-                $query_param_key === $logic_query_param_key
6456
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6457
-            ) {
6458
-                return true;
6459
-            }
6460
-        }
6461
-        return false;
6462
-    }
6463
-
6464
-
6465
-    /**
6466
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6467
-     *
6468
-     * @return boolean
6469
-     * @since 4.9.74.p
6470
-     */
6471
-    public function hasPassword()
6472
-    {
6473
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6474
-        if ($this->has_password_field === null) {
6475
-            $password_field           = $this->getPasswordField();
6476
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6477
-        }
6478
-        return $this->has_password_field;
6479
-    }
6480
-
6481
-
6482
-    /**
6483
-     * Returns the password field on this model, if there is one
6484
-     *
6485
-     * @return EE_Password_Field|null
6486
-     * @since 4.9.74.p
6487
-     */
6488
-    public function getPasswordField()
6489
-    {
6490
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6491
-        // there's no need to search for it. If we don't know yet, then find out
6492
-        if ($this->has_password_field === null && $this->password_field === null) {
6493
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6494
-        }
6495
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6496
-        return $this->password_field;
6497
-    }
6498
-
6499
-
6500
-    /**
6501
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6502
-     *
6503
-     * @return EE_Model_Field_Base[]
6504
-     * @throws EE_Error
6505
-     * @since 4.9.74.p
6506
-     */
6507
-    public function getPasswordProtectedFields()
6508
-    {
6509
-        $password_field = $this->getPasswordField();
6510
-        $fields         = [];
6511
-        if ($password_field instanceof EE_Password_Field) {
6512
-            $field_names = $password_field->protectedFields();
6513
-            foreach ($field_names as $field_name) {
6514
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6515
-            }
6516
-        }
6517
-        return $fields;
6518
-    }
6519
-
6520
-
6521
-    /**
6522
-     * Checks if the current user can perform the requested action on this model
6523
-     *
6524
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6525
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6526
-     * @return bool
6527
-     * @throws EE_Error
6528
-     * @throws InvalidArgumentException
6529
-     * @throws InvalidDataTypeException
6530
-     * @throws InvalidInterfaceException
6531
-     * @throws ReflectionException
6532
-     * @throws UnexpectedEntityException
6533
-     * @since 4.9.74.p
6534
-     */
6535
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6536
-    {
6537
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6538
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6539
-        }
6540
-        if (! is_array($model_obj_or_fields_n_values)) {
6541
-            throw new UnexpectedEntityException(
6542
-                $model_obj_or_fields_n_values,
6543
-                'EE_Base_Class',
6544
-                sprintf(
6545
-                    esc_html__(
6546
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6547
-                        'event_espresso'
6548
-                    ),
6549
-                    __FUNCTION__
6550
-                )
6551
-            );
6552
-        }
6553
-        return $this->exists(
6554
-            $this->alter_query_params_to_restrict_by_ID(
6555
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6556
-                [
6557
-                    'default_where_conditions' => 'none',
6558
-                    'caps'                     => $cap_to_check,
6559
-                ]
6560
-            )
6561
-        );
6562
-    }
6563
-
6564
-
6565
-    /**
6566
-     * Returns the query param where conditions key to the password affecting this model.
6567
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6568
-     *
6569
-     * @return null|string
6570
-     * @throws EE_Error
6571
-     * @throws InvalidArgumentException
6572
-     * @throws InvalidDataTypeException
6573
-     * @throws InvalidInterfaceException
6574
-     * @throws ModelConfigurationException
6575
-     * @throws ReflectionException
6576
-     * @since 4.9.74.p
6577
-     */
6578
-    public function modelChainAndPassword()
6579
-    {
6580
-        if ($this->model_chain_to_password === null) {
6581
-            throw new ModelConfigurationException(
6582
-                $this,
6583
-                esc_html_x(
6584
-                // @codingStandardsIgnoreStart
6585
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6586
-                    // @codingStandardsIgnoreEnd
6587
-                    '1: model name',
6588
-                    'event_espresso'
6589
-                )
6590
-            );
6591
-        }
6592
-        if ($this->model_chain_to_password === '') {
6593
-            $model_with_password = $this;
6594
-        } else {
6595
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6596
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6597
-            } else {
6598
-                $last_model_in_chain = $this->model_chain_to_password;
6599
-            }
6600
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6601
-        }
6602
-
6603
-        $password_field = $model_with_password->getPasswordField();
6604
-        if ($password_field instanceof EE_Password_Field) {
6605
-            $password_field_name = $password_field->get_name();
6606
-        } else {
6607
-            throw new ModelConfigurationException(
6608
-                $this,
6609
-                sprintf(
6610
-                    esc_html_x(
6611
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6612
-                        '1: model name, 2: special string',
6613
-                        'event_espresso'
6614
-                    ),
6615
-                    $model_with_password->get_this_model_name(),
6616
-                    $this->model_chain_to_password
6617
-                )
6618
-            );
6619
-        }
6620
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6621
-    }
6622
-
6623
-
6624
-    /**
6625
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6626
-     * or if this model itself has a password affecting access to some of its other fields.
6627
-     *
6628
-     * @return boolean
6629
-     * @since 4.9.74.p
6630
-     */
6631
-    public function restrictedByRelatedModelPassword()
6632
-    {
6633
-        return $this->model_chain_to_password !== null;
6634
-    }
3891
+		}
3892
+		return $null_friendly_where_conditions;
3893
+	}
3894
+
3895
+
3896
+	/**
3897
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3898
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3899
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3900
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3901
+	 *
3902
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3903
+	 * @return array @see
3904
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3905
+	 * @throws EE_Error
3906
+	 * @throws EE_Error
3907
+	 */
3908
+	private function _get_default_where_conditions($model_relation_path = '')
3909
+	{
3910
+		if ($this->_ignore_where_strategy) {
3911
+			return [];
3912
+		}
3913
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3914
+	}
3915
+
3916
+
3917
+	/**
3918
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3919
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3920
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3921
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3922
+	 * Similar to _get_default_where_conditions
3923
+	 *
3924
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3925
+	 * @return array @see
3926
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3927
+	 * @throws EE_Error
3928
+	 * @throws EE_Error
3929
+	 */
3930
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3931
+	{
3932
+		if ($this->_ignore_where_strategy) {
3933
+			return [];
3934
+		}
3935
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3936
+	}
3937
+
3938
+
3939
+	/**
3940
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3941
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3942
+	 *
3943
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3944
+	 * @return string
3945
+	 * @throws EE_Error
3946
+	 */
3947
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3948
+	{
3949
+		$selects = $this->_get_columns_to_select_for_this_model();
3950
+		foreach (
3951
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3952
+		) {
3953
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3954
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3955
+			foreach ($other_model_selects as $key => $value) {
3956
+				$selects[] = $value;
3957
+			}
3958
+		}
3959
+		return implode(", ", $selects);
3960
+	}
3961
+
3962
+
3963
+	/**
3964
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3965
+	 * So that's going to be the columns for all the fields on the model
3966
+	 *
3967
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3968
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3969
+	 */
3970
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3971
+	{
3972
+		$fields                                       = $this->field_settings();
3973
+		$selects                                      = [];
3974
+		$table_alias_with_model_relation_chain_prefix =
3975
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3976
+				$model_relation_chain,
3977
+				$this->get_this_model_name()
3978
+			);
3979
+		foreach ($fields as $field_obj) {
3980
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3981
+						 . $field_obj->get_table_alias()
3982
+						 . "."
3983
+						 . $field_obj->get_table_column()
3984
+						 . " AS '"
3985
+						 . $table_alias_with_model_relation_chain_prefix
3986
+						 . $field_obj->get_table_alias()
3987
+						 . "."
3988
+						 . $field_obj->get_table_column()
3989
+						 . "'";
3990
+		}
3991
+		// make sure we are also getting the PKs of each table
3992
+		$tables = $this->get_tables();
3993
+		if (count($tables) > 1) {
3994
+			foreach ($tables as $table_obj) {
3995
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3996
+									   . $table_obj->get_fully_qualified_pk_column();
3997
+				if (! in_array($qualified_pk_column, $selects)) {
3998
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3999
+				}
4000
+			}
4001
+		}
4002
+		return $selects;
4003
+	}
4004
+
4005
+
4006
+	/**
4007
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4008
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4009
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4010
+	 * SQL for joining, and the data types
4011
+	 *
4012
+	 * @param null|string                 $original_query_param
4013
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
4014
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4015
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4016
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4017
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
4018
+	 *                                                          or 'Registration's
4019
+	 * @param string                      $original_query_param what it originally was (eg
4020
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4021
+	 *                                                          matches $query_param
4022
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4023
+	 * @throws EE_Error
4024
+	 */
4025
+	private function _extract_related_model_info_from_query_param(
4026
+		$query_param,
4027
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4028
+		$query_param_type,
4029
+		$original_query_param = null
4030
+	) {
4031
+		if ($original_query_param === null) {
4032
+			$original_query_param = $query_param;
4033
+		}
4034
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4035
+		// check to see if we have a field on this model
4036
+		$this_model_fields = $this->field_settings(true);
4037
+		if (array_key_exists($query_param, $this_model_fields)) {
4038
+			$field_is_allowed = in_array(
4039
+				$query_param_type,
4040
+				[0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4041
+				true
4042
+			);
4043
+			if ($field_is_allowed) {
4044
+				return;
4045
+			}
4046
+			throw new EE_Error(
4047
+				sprintf(
4048
+					esc_html__(
4049
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4050
+						"event_espresso"
4051
+					),
4052
+					$query_param,
4053
+					get_class($this),
4054
+					$query_param_type,
4055
+					$original_query_param
4056
+				)
4057
+			);
4058
+		}
4059
+		// check if this is a special logic query param
4060
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4061
+			$operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4062
+			if ($operator_is_allowed) {
4063
+				return;
4064
+			}
4065
+			throw new EE_Error(
4066
+				sprintf(
4067
+					esc_html__(
4068
+						'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',
4069
+						'event_espresso'
4070
+					),
4071
+					implode('", "', $this->_logic_query_param_keys),
4072
+					$query_param,
4073
+					get_class($this),
4074
+					'<br />',
4075
+					"\t"
4076
+					. ' $passed_in_query_info = <pre>'
4077
+					. print_r($passed_in_query_info, true)
4078
+					. '</pre>'
4079
+					. "\n\t"
4080
+					. ' $query_param_type = '
4081
+					. $query_param_type
4082
+					. "\n\t"
4083
+					. ' $original_query_param = '
4084
+					. $original_query_param
4085
+				)
4086
+			);
4087
+		}
4088
+		// check if it's a custom selection
4089
+		if (
4090
+			$this->_custom_selections instanceof CustomSelects
4091
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4092
+		) {
4093
+			return;
4094
+		}
4095
+		// check if has a model name at the beginning
4096
+		// and
4097
+		// check if it's a field on a related model
4098
+		if (
4099
+			$this->extractJoinModelFromQueryParams(
4100
+				$passed_in_query_info,
4101
+				$query_param,
4102
+				$original_query_param,
4103
+				$query_param_type
4104
+			)
4105
+		) {
4106
+			return;
4107
+		}
4108
+
4109
+		// ok so $query_param didn't start with a model name
4110
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4111
+		// it's wack, that's what it is
4112
+		throw new EE_Error(
4113
+			sprintf(
4114
+				esc_html__(
4115
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4116
+					"event_espresso"
4117
+				),
4118
+				$query_param,
4119
+				get_class($this),
4120
+				$query_param_type,
4121
+				$original_query_param
4122
+			)
4123
+		);
4124
+	}
4125
+
4126
+
4127
+	/**
4128
+	 * Extracts any possible join model information from the provided possible_join_string.
4129
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4130
+	 * join
4131
+	 * parts that should be added to the query.
4132
+	 *
4133
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4134
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4135
+	 * @param null|string                 $original_query_param
4136
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4137
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4138
+	 *                                                           etc.)
4139
+	 * @return bool  returns true if a join was added and false if not.
4140
+	 * @throws EE_Error
4141
+	 */
4142
+	private function extractJoinModelFromQueryParams(
4143
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4144
+		$possible_join_string,
4145
+		$original_query_param,
4146
+		$query_parameter_type
4147
+	) {
4148
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4149
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4150
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4151
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4152
+				if ($possible_join_string === '') {
4153
+					// nothing left to $query_param
4154
+					// we should actually end in a field name, not a model like this!
4155
+					throw new EE_Error(
4156
+						sprintf(
4157
+							esc_html__(
4158
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4159
+								"event_espresso"
4160
+							),
4161
+							$possible_join_string,
4162
+							$query_parameter_type,
4163
+							get_class($this),
4164
+							$valid_related_model_name
4165
+						)
4166
+					);
4167
+				}
4168
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4169
+				$related_model_obj->_extract_related_model_info_from_query_param(
4170
+					$possible_join_string,
4171
+					$query_info_carrier,
4172
+					$query_parameter_type,
4173
+					$original_query_param
4174
+				);
4175
+				return true;
4176
+			}
4177
+			if ($possible_join_string === $valid_related_model_name) {
4178
+				$this->_add_join_to_model(
4179
+					$valid_related_model_name,
4180
+					$query_info_carrier,
4181
+					$original_query_param
4182
+				);
4183
+				return true;
4184
+			}
4185
+		}
4186
+		return false;
4187
+	}
4188
+
4189
+
4190
+	/**
4191
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4192
+	 *
4193
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4194
+	 * @throws EE_Error
4195
+	 */
4196
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4197
+	{
4198
+		if (
4199
+			$this->_custom_selections instanceof CustomSelects
4200
+			&& (
4201
+				$this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4202
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4203
+			)
4204
+		) {
4205
+			$original_selects = $this->_custom_selections->originalSelects();
4206
+			foreach ($original_selects as $alias => $select_configuration) {
4207
+				$this->extractJoinModelFromQueryParams(
4208
+					$query_info_carrier,
4209
+					$select_configuration[0],
4210
+					$select_configuration[0],
4211
+					'custom_selects'
4212
+				);
4213
+			}
4214
+		}
4215
+	}
4216
+
4217
+
4218
+	/**
4219
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4220
+	 * and store it on $passed_in_query_info
4221
+	 *
4222
+	 * @param string                      $model_name
4223
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4224
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4225
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4226
+	 *                                                          and are adding a join to 'Payment' with the original
4227
+	 *                                                          query param key
4228
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4229
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4230
+	 *                                                          Payment wants to add default query params so that it
4231
+	 *                                                          will know what models to prepend onto its default query
4232
+	 *                                                          params or in case it wants to rename tables (in case
4233
+	 *                                                          there are multiple joins to the same table)
4234
+	 * @return void
4235
+	 * @throws EE_Error
4236
+	 */
4237
+	private function _add_join_to_model(
4238
+		$model_name,
4239
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4240
+		$original_query_param
4241
+	) {
4242
+		$relation_obj         = $this->related_settings_for($model_name);
4243
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4244
+		// check if the relation is HABTM, because then we're essentially doing two joins
4245
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4246
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4247
+			$join_model_obj = $relation_obj->get_join_model();
4248
+			// replace the model specified with the join model for this relation chain, whi
4249
+			$relation_chain_to_join_model =
4250
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4251
+					$model_name,
4252
+					$join_model_obj->get_this_model_name(),
4253
+					$model_relation_chain
4254
+				);
4255
+			$passed_in_query_info->merge(
4256
+				new EE_Model_Query_Info_Carrier(
4257
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4258
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4259
+				)
4260
+			);
4261
+		}
4262
+		// now just join to the other table pointed to by the relation object, and add its data types
4263
+		$passed_in_query_info->merge(
4264
+			new EE_Model_Query_Info_Carrier(
4265
+				[$model_relation_chain => $model_name],
4266
+				$relation_obj->get_join_statement($model_relation_chain)
4267
+			)
4268
+		);
4269
+	}
4270
+
4271
+
4272
+	/**
4273
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4274
+	 *
4275
+	 * @param array $where_params @see
4276
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4277
+	 * @return string of SQL
4278
+	 * @throws EE_Error
4279
+	 */
4280
+	private function _construct_where_clause($where_params)
4281
+	{
4282
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4283
+		if ($SQL) {
4284
+			return " WHERE " . $SQL;
4285
+		}
4286
+		return '';
4287
+	}
4288
+
4289
+
4290
+	/**
4291
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4292
+	 * and should be passed HAVING parameters, not WHERE parameters
4293
+	 *
4294
+	 * @param array $having_params
4295
+	 * @return string
4296
+	 * @throws EE_Error
4297
+	 */
4298
+	private function _construct_having_clause($having_params)
4299
+	{
4300
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4301
+		if ($SQL) {
4302
+			return " HAVING " . $SQL;
4303
+		}
4304
+		return '';
4305
+	}
4306
+
4307
+
4308
+	/**
4309
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4310
+	 * Event_Meta.meta_value = 'foo'))"
4311
+	 *
4312
+	 * @param array  $where_params @see
4313
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4314
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4315
+	 * @return string of SQL
4316
+	 * @throws EE_Error
4317
+	 */
4318
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4319
+	{
4320
+		$where_clauses = [];
4321
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4322
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4323
+			if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4324
+				switch ($query_param) {
4325
+					case 'not':
4326
+					case 'NOT':
4327
+						$where_clauses[] = "! ("
4328
+										   . $this->_construct_condition_clause_recursive(
4329
+											   $op_and_value_or_sub_condition,
4330
+											   $glue
4331
+										   )
4332
+										   . ")";
4333
+						break;
4334
+					case 'and':
4335
+					case 'AND':
4336
+						$where_clauses[] = " ("
4337
+										   . $this->_construct_condition_clause_recursive(
4338
+											   $op_and_value_or_sub_condition,
4339
+											   ' AND '
4340
+										   )
4341
+										   . ")";
4342
+						break;
4343
+					case 'or':
4344
+					case 'OR':
4345
+						$where_clauses[] = " ("
4346
+										   . $this->_construct_condition_clause_recursive(
4347
+											   $op_and_value_or_sub_condition,
4348
+											   ' OR '
4349
+										   )
4350
+										   . ")";
4351
+						break;
4352
+				}
4353
+			} else {
4354
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4355
+				// if it's not a normal field, maybe it's a custom selection?
4356
+				if (! $field_obj) {
4357
+					if ($this->_custom_selections instanceof CustomSelects) {
4358
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4359
+					} else {
4360
+						throw new EE_Error(
4361
+							sprintf(
4362
+								esc_html__(
4363
+									"%s is neither a valid model field name, nor a custom selection",
4364
+									"event_espresso"
4365
+								),
4366
+								$query_param
4367
+							)
4368
+						);
4369
+					}
4370
+				}
4371
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4372
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4373
+			}
4374
+		}
4375
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4376
+	}
4377
+
4378
+
4379
+	/**
4380
+	 * Takes the input parameter and extract the table name (alias) and column name
4381
+	 *
4382
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4383
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4384
+	 * @throws EE_Error
4385
+	 */
4386
+	private function _deduce_column_name_from_query_param($query_param)
4387
+	{
4388
+		$field = $this->_deduce_field_from_query_param($query_param);
4389
+		if ($field) {
4390
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4391
+				$field->get_model_name(),
4392
+				$query_param
4393
+			);
4394
+			return $table_alias_prefix . $field->get_qualified_column();
4395
+		}
4396
+		if (
4397
+			$this->_custom_selections instanceof CustomSelects
4398
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4399
+		) {
4400
+			// maybe it's custom selection item?
4401
+			// if so, just use it as the "column name"
4402
+			return $query_param;
4403
+		}
4404
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4405
+			? implode(',', $this->_custom_selections->columnAliases())
4406
+			: '';
4407
+		throw new EE_Error(
4408
+			sprintf(
4409
+				esc_html__(
4410
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4411
+					"event_espresso"
4412
+				),
4413
+				$query_param,
4414
+				$custom_select_aliases
4415
+			)
4416
+		);
4417
+	}
4418
+
4419
+
4420
+	/**
4421
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4422
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4423
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4424
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4425
+	 *
4426
+	 * @param string $condition_query_param_key
4427
+	 * @return string
4428
+	 */
4429
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4430
+	{
4431
+		$pos_of_star = strpos($condition_query_param_key, '*');
4432
+		if ($pos_of_star === false) {
4433
+			return $condition_query_param_key;
4434
+		}
4435
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4436
+		return $condition_query_param_sans_star;
4437
+	}
4438
+
4439
+
4440
+	/**
4441
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4442
+	 *
4443
+	 * @param mixed      array | string    $op_and_value
4444
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4445
+	 * @return string
4446
+	 * @throws EE_Error
4447
+	 */
4448
+	private function _construct_op_and_value($op_and_value, $field_obj)
4449
+	{
4450
+		if (is_array($op_and_value)) {
4451
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4452
+			if (! $operator) {
4453
+				$php_array_like_string = [];
4454
+				foreach ($op_and_value as $key => $value) {
4455
+					$php_array_like_string[] = "$key=>$value";
4456
+				}
4457
+				throw new EE_Error(
4458
+					sprintf(
4459
+						esc_html__(
4460
+							"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))",
4461
+							"event_espresso"
4462
+						),
4463
+						implode(",", $php_array_like_string)
4464
+					)
4465
+				);
4466
+			}
4467
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4468
+		} else {
4469
+			$operator = '=';
4470
+			$value    = $op_and_value;
4471
+		}
4472
+		// check to see if the value is actually another field
4473
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4474
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4475
+		}
4476
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4477
+			// in this case, the value should be an array, or at least a comma-separated list
4478
+			// it will need to handle a little differently
4479
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4480
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4481
+			return $operator . SP . $cleaned_value;
4482
+		}
4483
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4484
+			// the value should be an array with count of two.
4485
+			if (count($value) !== 2) {
4486
+				throw new EE_Error(
4487
+					sprintf(
4488
+						esc_html__(
4489
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4490
+							'event_espresso'
4491
+						),
4492
+						"BETWEEN"
4493
+					)
4494
+				);
4495
+			}
4496
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4497
+			return $operator . SP . $cleaned_value;
4498
+		}
4499
+		if (in_array($operator, $this->valid_null_style_operators())) {
4500
+			if ($value !== null) {
4501
+				throw new EE_Error(
4502
+					sprintf(
4503
+						esc_html__(
4504
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4505
+							"event_espresso"
4506
+						),
4507
+						$value,
4508
+						$operator
4509
+					)
4510
+				);
4511
+			}
4512
+			return $operator;
4513
+		}
4514
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4515
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4516
+			// remove other junk. So just treat it as a string.
4517
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4518
+		}
4519
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4520
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4521
+		}
4522
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4523
+			throw new EE_Error(
4524
+				sprintf(
4525
+					esc_html__(
4526
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4527
+						'event_espresso'
4528
+					),
4529
+					$operator,
4530
+					$operator
4531
+				)
4532
+			);
4533
+		}
4534
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4535
+			throw new EE_Error(
4536
+				sprintf(
4537
+					esc_html__(
4538
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4539
+						'event_espresso'
4540
+					),
4541
+					$operator,
4542
+					$operator
4543
+				)
4544
+			);
4545
+		}
4546
+		throw new EE_Error(
4547
+			sprintf(
4548
+				esc_html__(
4549
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4550
+					"event_espresso"
4551
+				),
4552
+				http_build_query($op_and_value)
4553
+			)
4554
+		);
4555
+	}
4556
+
4557
+
4558
+	/**
4559
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4560
+	 *
4561
+	 * @param array                      $values
4562
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4563
+	 *                                              '%s'
4564
+	 * @return string
4565
+	 * @throws EE_Error
4566
+	 */
4567
+	public function _construct_between_value($values, $field_obj)
4568
+	{
4569
+		$cleaned_values = [];
4570
+		foreach ($values as $value) {
4571
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4572
+		}
4573
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4574
+	}
4575
+
4576
+
4577
+	/**
4578
+	 * Takes an array or a comma-separated list of $values and cleans them
4579
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4580
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4581
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4582
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4583
+	 *
4584
+	 * @param mixed                      $values    array or comma-separated string
4585
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4586
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4587
+	 * @throws EE_Error
4588
+	 */
4589
+	public function _construct_in_value($values, $field_obj)
4590
+	{
4591
+		$prepped = [];
4592
+		// check if the value is a CSV list
4593
+		if (is_string($values)) {
4594
+			// in which case, turn it into an array
4595
+			$values = explode(',', $values);
4596
+		}
4597
+		// make sure we only have one of each value in the list
4598
+		$values = array_unique($values);
4599
+		foreach ($values as $value) {
4600
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4601
+		}
4602
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4603
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4604
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4605
+		if (empty($prepped)) {
4606
+			$all_fields  = $this->field_settings();
4607
+			$first_field = reset($all_fields);
4608
+			$main_table  = $this->_get_main_table();
4609
+			$prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4610
+		}
4611
+		return '(' . implode(',', $prepped) . ')';
4612
+	}
4613
+
4614
+
4615
+	/**
4616
+	 * @param mixed                      $value
4617
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4618
+	 * @return false|null|string
4619
+	 * @throws EE_Error
4620
+	 */
4621
+	private function _wpdb_prepare_using_field($value, $field_obj)
4622
+	{
4623
+		/** @type WPDB $wpdb */
4624
+		global $wpdb;
4625
+		if ($field_obj instanceof EE_Model_Field_Base) {
4626
+			return $wpdb->prepare(
4627
+				$field_obj->get_wpdb_data_type(),
4628
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4629
+			);
4630
+		} //$field_obj should really just be a data type
4631
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4632
+			throw new EE_Error(
4633
+				sprintf(
4634
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4635
+					$field_obj,
4636
+					implode(",", $this->_valid_wpdb_data_types)
4637
+				)
4638
+			);
4639
+		}
4640
+		return $wpdb->prepare($field_obj, $value);
4641
+	}
4642
+
4643
+
4644
+	/**
4645
+	 * Takes the input parameter and finds the model field that it indicates.
4646
+	 *
4647
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4648
+	 * @return EE_Model_Field_Base
4649
+	 * @throws EE_Error
4650
+	 */
4651
+	protected function _deduce_field_from_query_param($query_param_name)
4652
+	{
4653
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4654
+		// which will help us find the database table and column
4655
+		$query_param_parts = explode(".", $query_param_name);
4656
+		if (empty($query_param_parts)) {
4657
+			throw new EE_Error(
4658
+				sprintf(
4659
+					esc_html__(
4660
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4661
+						'event_espresso'
4662
+					),
4663
+					$query_param_name
4664
+				)
4665
+			);
4666
+		}
4667
+		$number_of_parts       = count($query_param_parts);
4668
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4669
+		if ($number_of_parts === 1) {
4670
+			$field_name = $last_query_param_part;
4671
+			$model_obj  = $this;
4672
+		} else {// $number_of_parts >= 2
4673
+			// the last part is the column name, and there are only 2parts. therefore...
4674
+			$field_name = $last_query_param_part;
4675
+			$model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4676
+		}
4677
+		try {
4678
+			return $model_obj->field_settings_for($field_name);
4679
+		} catch (EE_Error $e) {
4680
+			return null;
4681
+		}
4682
+	}
4683
+
4684
+
4685
+	/**
4686
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4687
+	 * alias and column which corresponds to it
4688
+	 *
4689
+	 * @param string $field_name
4690
+	 * @return string
4691
+	 * @throws EE_Error
4692
+	 */
4693
+	public function _get_qualified_column_for_field($field_name)
4694
+	{
4695
+		$all_fields = $this->field_settings();
4696
+		$field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4697
+		if ($field) {
4698
+			return $field->get_qualified_column();
4699
+		}
4700
+		throw new EE_Error(
4701
+			sprintf(
4702
+				esc_html__(
4703
+					"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.",
4704
+					'event_espresso'
4705
+				),
4706
+				$field_name,
4707
+				get_class($this)
4708
+			)
4709
+		);
4710
+	}
4711
+
4712
+
4713
+	/**
4714
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4715
+	 * Example usage:
4716
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4717
+	 *      array(),
4718
+	 *      ARRAY_A,
4719
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4720
+	 *  );
4721
+	 * is equivalent to
4722
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4723
+	 * and
4724
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4725
+	 *      array(
4726
+	 *          array(
4727
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4728
+	 *          ),
4729
+	 *          ARRAY_A,
4730
+	 *          implode(
4731
+	 *              ', ',
4732
+	 *              array_merge(
4733
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4734
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4735
+	 *              )
4736
+	 *          )
4737
+	 *      )
4738
+	 *  );
4739
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4740
+	 *
4741
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4742
+	 *                                            and the one whose fields you are selecting for example: when querying
4743
+	 *                                            tickets model and selecting fields from the tickets model you would
4744
+	 *                                            leave this parameter empty, because no models are needed to join
4745
+	 *                                            between the queried model and the selected one. Likewise when
4746
+	 *                                            querying the datetime model and selecting fields from the tickets
4747
+	 *                                            model, it would also be left empty, because there is a direct
4748
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4749
+	 *                                            them together. However, when querying from the event model and
4750
+	 *                                            selecting fields from the ticket model, you should provide the string
4751
+	 *                                            'Datetime', indicating that the event model must first join to the
4752
+	 *                                            datetime model in order to find its relation to ticket model.
4753
+	 *                                            Also, when querying from the venue model and selecting fields from
4754
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4755
+	 *                                            indicating you need to join the venue model to the event model,
4756
+	 *                                            to the datetime model, in order to find its relation to the ticket
4757
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4758
+	 *                                            the models' tables qualified columns
4759
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4760
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4761
+	 *                                            qualified column names
4762
+	 * @return array|string
4763
+	 */
4764
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4765
+	{
4766
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4767
+		$qualified_columns = [];
4768
+		foreach ($this->field_settings() as $field_name => $field) {
4769
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4770
+		}
4771
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4772
+	}
4773
+
4774
+
4775
+	/**
4776
+	 * constructs the select use on special limit joins
4777
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4778
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4779
+	 * (as that is typically where the limits would be set).
4780
+	 *
4781
+	 * @param string       $table_alias The table the select is being built for
4782
+	 * @param mixed|string $limit       The limit for this select
4783
+	 * @return string                The final select join element for the query.
4784
+	 * @throws EE_Error
4785
+	 * @throws EE_Error
4786
+	 */
4787
+	public function _construct_limit_join_select($table_alias, $limit)
4788
+	{
4789
+		$SQL = '';
4790
+		foreach ($this->_tables as $table_obj) {
4791
+			if ($table_obj instanceof EE_Primary_Table) {
4792
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4793
+					? $table_obj->get_select_join_limit($limit)
4794
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4795
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4796
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4797
+					? $table_obj->get_select_join_limit_join($limit)
4798
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4799
+			}
4800
+		}
4801
+		return $SQL;
4802
+	}
4803
+
4804
+
4805
+	/**
4806
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4807
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4808
+	 *
4809
+	 * @return string SQL
4810
+	 * @throws EE_Error
4811
+	 */
4812
+	public function _construct_internal_join()
4813
+	{
4814
+		$SQL = $this->_get_main_table()->get_table_sql();
4815
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4816
+		return $SQL;
4817
+	}
4818
+
4819
+
4820
+	/**
4821
+	 * Constructs the SQL for joining all the tables on this model.
4822
+	 * Normally $alias should be the primary table's alias, but in cases where
4823
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4824
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4825
+	 * alias, this will construct SQL like:
4826
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4827
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4828
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4829
+	 *
4830
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4831
+	 * @return string
4832
+	 * @throws EE_Error
4833
+	 * @throws EE_Error
4834
+	 */
4835
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4836
+	{
4837
+		$SQL               = '';
4838
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4839
+		foreach ($this->_tables as $table_obj) {
4840
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4841
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4842
+					// so we're joining to this table, meaning the table is already in
4843
+					// the FROM statement, BUT the primary table isn't. So we want
4844
+					// to add the inverse join sql
4845
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4846
+				} else {
4847
+					// just add a regular JOIN to this table from the primary table
4848
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4849
+				}
4850
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4851
+		}
4852
+		return $SQL;
4853
+	}
4854
+
4855
+
4856
+	/**
4857
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4858
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4859
+	 * their data type (eg, '%s', '%d', etc)
4860
+	 *
4861
+	 * @return array
4862
+	 */
4863
+	public function _get_data_types()
4864
+	{
4865
+		$data_types = [];
4866
+		foreach ($this->field_settings() as $field_obj) {
4867
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4868
+			/** @var $field_obj EE_Model_Field_Base */
4869
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4870
+		}
4871
+		return $data_types;
4872
+	}
4873
+
4874
+
4875
+	/**
4876
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4877
+	 *
4878
+	 * @param string $model_name
4879
+	 * @return EEM_Base
4880
+	 * @throws EE_Error
4881
+	 */
4882
+	public function get_related_model_obj($model_name)
4883
+	{
4884
+		$model_classname = "EEM_" . $model_name;
4885
+		if (! class_exists($model_classname)) {
4886
+			throw new EE_Error(
4887
+				sprintf(
4888
+					esc_html__(
4889
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4890
+						'event_espresso'
4891
+					),
4892
+					$model_name,
4893
+					$model_classname
4894
+				)
4895
+			);
4896
+		}
4897
+		return call_user_func($model_classname . "::instance");
4898
+	}
4899
+
4900
+
4901
+	/**
4902
+	 * Returns the array of EE_ModelRelations for this model.
4903
+	 *
4904
+	 * @return EE_Model_Relation_Base[]
4905
+	 */
4906
+	public function relation_settings()
4907
+	{
4908
+		return $this->_model_relations;
4909
+	}
4910
+
4911
+
4912
+	/**
4913
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4914
+	 * because without THOSE models, this model probably doesn't have much purpose.
4915
+	 * (Eg, without an event, datetimes have little purpose.)
4916
+	 *
4917
+	 * @return EE_Belongs_To_Relation[]
4918
+	 */
4919
+	public function belongs_to_relations()
4920
+	{
4921
+		$belongs_to_relations = [];
4922
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4923
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4924
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4925
+			}
4926
+		}
4927
+		return $belongs_to_relations;
4928
+	}
4929
+
4930
+
4931
+	/**
4932
+	 * Returns the specified EE_Model_Relation, or throws an exception
4933
+	 *
4934
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4935
+	 * @return EE_Model_Relation_Base
4936
+	 * @throws EE_Error
4937
+	 */
4938
+	public function related_settings_for($relation_name)
4939
+	{
4940
+		$relatedModels = $this->relation_settings();
4941
+		if (! array_key_exists($relation_name, $relatedModels)) {
4942
+			throw new EE_Error(
4943
+				sprintf(
4944
+					esc_html__(
4945
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4946
+						'event_espresso'
4947
+					),
4948
+					$relation_name,
4949
+					$this->_get_class_name(),
4950
+					implode(', ', array_keys($relatedModels))
4951
+				)
4952
+			);
4953
+		}
4954
+		return $relatedModels[ $relation_name ];
4955
+	}
4956
+
4957
+
4958
+	/**
4959
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4960
+	 * fields
4961
+	 *
4962
+	 * @param string  $fieldName
4963
+	 * @param boolean $include_db_only_fields
4964
+	 * @return EE_Model_Field_Base
4965
+	 * @throws EE_Error
4966
+	 */
4967
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4968
+	{
4969
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4970
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4971
+			throw new EE_Error(
4972
+				sprintf(
4973
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4974
+					$fieldName,
4975
+					get_class($this)
4976
+				)
4977
+			);
4978
+		}
4979
+		return $fieldSettings[ $fieldName ];
4980
+	}
4981
+
4982
+
4983
+	/**
4984
+	 * Checks if this field exists on this model
4985
+	 *
4986
+	 * @param string $fieldName a key in the model's _field_settings array
4987
+	 * @return boolean
4988
+	 */
4989
+	public function has_field($fieldName)
4990
+	{
4991
+		$fieldSettings = $this->field_settings(true);
4992
+		if (isset($fieldSettings[ $fieldName ])) {
4993
+			return true;
4994
+		}
4995
+		return false;
4996
+	}
4997
+
4998
+
4999
+	/**
5000
+	 * Returns whether or not this model has a relation to the specified model
5001
+	 *
5002
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
5003
+	 * @return boolean
5004
+	 */
5005
+	public function has_relation($relation_name)
5006
+	{
5007
+		$relations = $this->relation_settings();
5008
+		if (isset($relations[ $relation_name ])) {
5009
+			return true;
5010
+		}
5011
+		return false;
5012
+	}
5013
+
5014
+
5015
+	/**
5016
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5017
+	 * Eg, on EE_Answer that would be ANS_ID field object
5018
+	 *
5019
+	 * @param $field_obj
5020
+	 * @return boolean
5021
+	 */
5022
+	public function is_primary_key_field($field_obj)
5023
+	{
5024
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
5025
+	}
5026
+
5027
+
5028
+	/**
5029
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5030
+	 * Eg, on EE_Answer that would be ANS_ID field object
5031
+	 *
5032
+	 * @return EE_Primary_Key_Field_Base
5033
+	 * @throws EE_Error
5034
+	 */
5035
+	public function get_primary_key_field()
5036
+	{
5037
+		if ($this->_primary_key_field === null) {
5038
+			foreach ($this->field_settings(true) as $field_obj) {
5039
+				if ($this->is_primary_key_field($field_obj)) {
5040
+					$this->_primary_key_field = $field_obj;
5041
+					break;
5042
+				}
5043
+			}
5044
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5045
+				throw new EE_Error(
5046
+					sprintf(
5047
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5048
+						get_class($this)
5049
+					)
5050
+				);
5051
+			}
5052
+		}
5053
+		return $this->_primary_key_field;
5054
+	}
5055
+
5056
+
5057
+	/**
5058
+	 * Returns whether or not not there is a primary key on this model.
5059
+	 * Internally does some caching.
5060
+	 *
5061
+	 * @return boolean
5062
+	 */
5063
+	public function has_primary_key_field()
5064
+	{
5065
+		if ($this->_has_primary_key_field === null) {
5066
+			try {
5067
+				$this->get_primary_key_field();
5068
+				$this->_has_primary_key_field = true;
5069
+			} catch (EE_Error $e) {
5070
+				$this->_has_primary_key_field = false;
5071
+			}
5072
+		}
5073
+		return $this->_has_primary_key_field;
5074
+	}
5075
+
5076
+
5077
+	/**
5078
+	 * Finds the first field of type $field_class_name.
5079
+	 *
5080
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5081
+	 *                                 EE_Foreign_Key_Field, etc
5082
+	 * @return EE_Model_Field_Base or null if none is found
5083
+	 */
5084
+	public function get_a_field_of_type($field_class_name)
5085
+	{
5086
+		foreach ($this->field_settings() as $field) {
5087
+			if ($field instanceof $field_class_name) {
5088
+				return $field;
5089
+			}
5090
+		}
5091
+		return null;
5092
+	}
5093
+
5094
+
5095
+	/**
5096
+	 * Gets a foreign key field pointing to model.
5097
+	 *
5098
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5099
+	 * @return EE_Foreign_Key_Field_Base
5100
+	 * @throws EE_Error
5101
+	 */
5102
+	public function get_foreign_key_to($model_name)
5103
+	{
5104
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5105
+			foreach ($this->field_settings() as $field) {
5106
+				if (
5107
+					$field instanceof EE_Foreign_Key_Field_Base
5108
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5109
+				) {
5110
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5111
+					break;
5112
+				}
5113
+			}
5114
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5115
+				throw new EE_Error(
5116
+					sprintf(
5117
+						esc_html__(
5118
+							"There is no foreign key field pointing to model %s on model %s",
5119
+							'event_espresso'
5120
+						),
5121
+						$model_name,
5122
+						get_class($this)
5123
+					)
5124
+				);
5125
+			}
5126
+		}
5127
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5128
+	}
5129
+
5130
+
5131
+	/**
5132
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5133
+	 *
5134
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5135
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5136
+	 *                            Either one works
5137
+	 * @return string
5138
+	 */
5139
+	public function get_table_for_alias($table_alias)
5140
+	{
5141
+		$table_alias_sans_model_relation_chain_prefix =
5142
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5143
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5144
+	}
5145
+
5146
+
5147
+	/**
5148
+	 * Returns a flat array of all field son this model, instead of organizing them
5149
+	 * by table_alias as they are in the constructor.
5150
+	 *
5151
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5152
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5153
+	 */
5154
+	public function field_settings($include_db_only_fields = false)
5155
+	{
5156
+		if ($include_db_only_fields) {
5157
+			if ($this->_cached_fields === null) {
5158
+				$this->_cached_fields = [];
5159
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5160
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5161
+						$this->_cached_fields[ $field_name ] = $field_obj;
5162
+					}
5163
+				}
5164
+			}
5165
+			return $this->_cached_fields;
5166
+		}
5167
+		if ($this->_cached_fields_non_db_only === null) {
5168
+			$this->_cached_fields_non_db_only = [];
5169
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5170
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5171
+					/** @var $field_obj EE_Model_Field_Base */
5172
+					if (! $field_obj->is_db_only_field()) {
5173
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5174
+					}
5175
+				}
5176
+			}
5177
+		}
5178
+		return $this->_cached_fields_non_db_only;
5179
+	}
5180
+
5181
+
5182
+	/**
5183
+	 *        cycle though array of attendees and create objects out of each item
5184
+	 *
5185
+	 * @access        private
5186
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5187
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5188
+	 *                           numerically indexed)
5189
+	 * @throws EE_Error
5190
+	 * @throws ReflectionException
5191
+	 */
5192
+	protected function _create_objects($rows = [])
5193
+	{
5194
+		$array_of_objects = [];
5195
+		if (empty($rows)) {
5196
+			return [];
5197
+		}
5198
+		$count_if_model_has_no_primary_key = 0;
5199
+		$has_primary_key                   = $this->has_primary_key_field();
5200
+		$primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5201
+		foreach ((array) $rows as $row) {
5202
+			if (empty($row)) {
5203
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5204
+				return [];
5205
+			}
5206
+			// check if we've already set this object in the results array,
5207
+			// in which case there's no need to process it further (again)
5208
+			if ($has_primary_key) {
5209
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5210
+					$row,
5211
+					$primary_key_field->get_qualified_column(),
5212
+					$primary_key_field->get_table_column()
5213
+				);
5214
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5215
+					continue;
5216
+				}
5217
+			}
5218
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5219
+			if (! $classInstance) {
5220
+				throw new EE_Error(
5221
+					sprintf(
5222
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5223
+						$this->get_this_model_name(),
5224
+						http_build_query($row)
5225
+					)
5226
+				);
5227
+			}
5228
+			// set the timezone on the instantiated objects
5229
+			$classInstance->set_timezone($this->_timezone);
5230
+			// make sure if there is any timezone setting present that we set the timezone for the object
5231
+			$key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5232
+			$array_of_objects[ $key ] = $classInstance;
5233
+			// also, for all the relations of type BelongsTo, see if we can cache
5234
+			// those related models
5235
+			// (we could do this for other relations too, but if there are conditions
5236
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5237
+			// so it requires a little more thought than just caching them immediately...)
5238
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5239
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5240
+					// check if this model's INFO is present. If so, cache it on the model
5241
+					$other_model           = $relation_obj->get_other_model();
5242
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5243
+					// if we managed to make a model object from the results, cache it on the main model object
5244
+					if ($other_model_obj_maybe) {
5245
+						// set timezone on these other model objects if they are present
5246
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5247
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5248
+					}
5249
+				}
5250
+			}
5251
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5252
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5253
+			// the field in the CustomSelects object
5254
+			if ($this->_custom_selections instanceof CustomSelects) {
5255
+				$classInstance->setCustomSelectsValues(
5256
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5257
+				);
5258
+			}
5259
+		}
5260
+		return $array_of_objects;
5261
+	}
5262
+
5263
+
5264
+	/**
5265
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5266
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5267
+	 *
5268
+	 * @param array $db_results_row
5269
+	 * @return array
5270
+	 */
5271
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5272
+	{
5273
+		$results = [];
5274
+		if ($this->_custom_selections instanceof CustomSelects) {
5275
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5276
+				if (isset($db_results_row[ $alias ])) {
5277
+					$results[ $alias ] = $this->convertValueToDataType(
5278
+						$db_results_row[ $alias ],
5279
+						$this->_custom_selections->getDataTypeForAlias($alias)
5280
+					);
5281
+				}
5282
+			}
5283
+		}
5284
+		return $results;
5285
+	}
5286
+
5287
+
5288
+	/**
5289
+	 * This will set the value for the given alias
5290
+	 *
5291
+	 * @param string $value
5292
+	 * @param string $datatype (one of %d, %s, %f)
5293
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5294
+	 */
5295
+	protected function convertValueToDataType($value, $datatype)
5296
+	{
5297
+		switch ($datatype) {
5298
+			case '%f':
5299
+				return (float) $value;
5300
+			case '%d':
5301
+				return (int) $value;
5302
+			default:
5303
+				return (string) $value;
5304
+		}
5305
+	}
5306
+
5307
+
5308
+	/**
5309
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5310
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5311
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5312
+	 * object (as set in the model_field!).
5313
+	 *
5314
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5315
+	 * @throws EE_Error
5316
+	 * @throws ReflectionException
5317
+	 */
5318
+	public function create_default_object()
5319
+	{
5320
+		$this_model_fields_and_values = [];
5321
+		// setup the row using default values;
5322
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5323
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5324
+		}
5325
+		$className     = $this->_get_class_name();
5326
+		return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5327
+	}
5328
+
5329
+
5330
+	/**
5331
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5332
+	 *                             or an stdClass where each property is the name of a column,
5333
+	 * @return EE_Base_Class
5334
+	 * @throws EE_Error
5335
+	 * @throws ReflectionException
5336
+	 */
5337
+	public function instantiate_class_from_array_or_object($cols_n_values)
5338
+	{
5339
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5340
+			$cols_n_values = get_object_vars($cols_n_values);
5341
+		}
5342
+		$primary_key = null;
5343
+		// make sure the array only has keys that are fields/columns on this model
5344
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5345
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5346
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5347
+		}
5348
+		$className = $this->_get_class_name();
5349
+		// check we actually found results that we can use to build our model object
5350
+		// if not, return null
5351
+		if ($this->has_primary_key_field()) {
5352
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5353
+				return null;
5354
+			}
5355
+		} elseif ($this->unique_indexes()) {
5356
+			$first_column = reset($this_model_fields_n_values);
5357
+			if (empty($first_column)) {
5358
+				return null;
5359
+			}
5360
+		}
5361
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5362
+		if ($primary_key) {
5363
+			$classInstance = $this->get_from_entity_map($primary_key);
5364
+			if (! $classInstance) {
5365
+				$classInstance = EE_Registry::instance()
5366
+											->load_class(
5367
+												$className,
5368
+												[$this_model_fields_n_values, $this->_timezone],
5369
+												true,
5370
+												false
5371
+											);
5372
+				// add this new object to the entity map
5373
+				$classInstance = $this->add_to_entity_map($classInstance);
5374
+			}
5375
+		} else {
5376
+			$classInstance = EE_Registry::instance()
5377
+										->load_class(
5378
+											$className,
5379
+											[$this_model_fields_n_values, $this->_timezone],
5380
+											true,
5381
+											false
5382
+										);
5383
+		}
5384
+		return $classInstance;
5385
+	}
5386
+
5387
+
5388
+	/**
5389
+	 * Gets the model object from the  entity map if it exists
5390
+	 *
5391
+	 * @param int|string $id the ID of the model object
5392
+	 * @return EE_Base_Class
5393
+	 */
5394
+	public function get_from_entity_map($id)
5395
+	{
5396
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5397
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5398
+	}
5399
+
5400
+
5401
+	/**
5402
+	 * add_to_entity_map
5403
+	 * Adds the object to the model's entity mappings
5404
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5405
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5406
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5407
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5408
+	 *        then this method should be called immediately after the update query
5409
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5410
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5411
+	 *
5412
+	 * @param EE_Base_Class $object
5413
+	 * @return EE_Base_Class
5414
+	 * @throws EE_Error
5415
+	 * @throws ReflectionException
5416
+	 */
5417
+	public function add_to_entity_map(EE_Base_Class $object)
5418
+	{
5419
+		$className = $this->_get_class_name();
5420
+		if (! $object instanceof $className) {
5421
+			throw new EE_Error(
5422
+				sprintf(
5423
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5424
+					is_object($object) ? get_class($object) : $object,
5425
+					$className
5426
+				)
5427
+			);
5428
+		}
5429
+		/** @var $object EE_Base_Class */
5430
+		if (! $object->ID()) {
5431
+			throw new EE_Error(
5432
+				sprintf(
5433
+					esc_html__(
5434
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5435
+						"event_espresso"
5436
+					),
5437
+					get_class($this)
5438
+				)
5439
+			);
5440
+		}
5441
+		// double check it's not already there
5442
+		$classInstance = $this->get_from_entity_map($object->ID());
5443
+		if ($classInstance) {
5444
+			return $classInstance;
5445
+		}
5446
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5447
+		return $object;
5448
+	}
5449
+
5450
+
5451
+	/**
5452
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5453
+	 * if no identifier is provided, then the entire entity map is emptied
5454
+	 *
5455
+	 * @param int|string $id the ID of the model object
5456
+	 * @return boolean
5457
+	 */
5458
+	public function clear_entity_map($id = null)
5459
+	{
5460
+		if (empty($id)) {
5461
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5462
+			return true;
5463
+		}
5464
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5465
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5466
+			return true;
5467
+		}
5468
+		return false;
5469
+	}
5470
+
5471
+
5472
+	/**
5473
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5474
+	 * Given an array where keys are column (or column alias) names and values,
5475
+	 * returns an array of their corresponding field names and database values
5476
+	 *
5477
+	 * @param array $cols_n_values
5478
+	 * @return array
5479
+	 * @throws EE_Error
5480
+	 * @throws ReflectionException
5481
+	 */
5482
+	public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5483
+	{
5484
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5485
+	}
5486
+
5487
+
5488
+	/**
5489
+	 * _deduce_fields_n_values_from_cols_n_values
5490
+	 * Given an array where keys are column (or column alias) names and values,
5491
+	 * returns an array of their corresponding field names and database values
5492
+	 *
5493
+	 * @param array|stdClass $cols_n_values
5494
+	 * @return array
5495
+	 * @throws EE_Error
5496
+	 * @throws ReflectionException
5497
+	 */
5498
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5499
+	{
5500
+		if ($cols_n_values instanceof stdClass) {
5501
+			$cols_n_values = get_object_vars($cols_n_values);
5502
+		}
5503
+		$this_model_fields_n_values = [];
5504
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5505
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5506
+				$cols_n_values,
5507
+				$table_obj->get_fully_qualified_pk_column(),
5508
+				$table_obj->get_pk_column()
5509
+			);
5510
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5511
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5512
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5513
+					if (! $field_obj->is_db_only_field()) {
5514
+						// prepare field as if its coming from db
5515
+						$prepared_value                            =
5516
+							$field_obj->prepare_for_set($field_obj->get_default_value());
5517
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5518
+					}
5519
+				}
5520
+			} else {
5521
+				// the table's rows existed. Use their values
5522
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5523
+					if (! $field_obj->is_db_only_field()) {
5524
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5525
+							$cols_n_values,
5526
+							$field_obj->get_qualified_column(),
5527
+							$field_obj->get_table_column()
5528
+						);
5529
+					}
5530
+				}
5531
+			}
5532
+		}
5533
+		return $this_model_fields_n_values;
5534
+	}
5535
+
5536
+
5537
+	/**
5538
+	 * @param $cols_n_values
5539
+	 * @param $qualified_column
5540
+	 * @param $regular_column
5541
+	 * @return null
5542
+	 * @throws EE_Error
5543
+	 * @throws ReflectionException
5544
+	 */
5545
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5546
+	{
5547
+		$value = null;
5548
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5549
+		// does the field on the model relate to this column retrieved from the db?
5550
+		// or is it a db-only field? (not relating to the model)
5551
+		if (isset($cols_n_values[ $qualified_column ])) {
5552
+			$value = $cols_n_values[ $qualified_column ];
5553
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5554
+			$value = $cols_n_values[ $regular_column ];
5555
+		} elseif (! empty($this->foreign_key_aliases)) {
5556
+			// no PK?  ok check if there is a foreign key alias set for this table
5557
+			// then check if that alias exists in the incoming data
5558
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5559
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5560
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5561
+					$value = $cols_n_values[ $FK_alias ];
5562
+					[$pk_class] = explode('.', $PK_column);
5563
+					$pk_model_name = "EEM_{$pk_class}";
5564
+					/** @var EEM_Base $pk_model */
5565
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5566
+					if ($pk_model instanceof EEM_Base) {
5567
+						// make sure object is pulled from db and added to entity map
5568
+						$pk_model->get_one_by_ID($value);
5569
+					}
5570
+					break;
5571
+				}
5572
+			}
5573
+		}
5574
+		return $value;
5575
+	}
5576
+
5577
+
5578
+	/**
5579
+	 * refresh_entity_map_from_db
5580
+	 * Makes sure the model object in the entity map at $id assumes the values
5581
+	 * of the database (opposite of EE_base_Class::save())
5582
+	 *
5583
+	 * @param int|string $id
5584
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5585
+	 * @throws EE_Error
5586
+	 * @throws ReflectionException
5587
+	 */
5588
+	public function refresh_entity_map_from_db($id)
5589
+	{
5590
+		$obj_in_map = $this->get_from_entity_map($id);
5591
+		if ($obj_in_map) {
5592
+			$wpdb_results = $this->_get_all_wpdb_results(
5593
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5594
+			);
5595
+			if ($wpdb_results && is_array($wpdb_results)) {
5596
+				$one_row = reset($wpdb_results);
5597
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5598
+					$obj_in_map->set_from_db($field_name, $db_value);
5599
+				}
5600
+				// clear the cache of related model objects
5601
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5602
+					$obj_in_map->clear_cache($relation_name, null, true);
5603
+				}
5604
+			}
5605
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5606
+			return $obj_in_map;
5607
+		}
5608
+		return $this->get_one_by_ID($id);
5609
+	}
5610
+
5611
+
5612
+	/**
5613
+	 * refresh_entity_map_with
5614
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5615
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5616
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5617
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5618
+	 *
5619
+	 * @param int|string    $id
5620
+	 * @param EE_Base_Class $replacing_model_obj
5621
+	 * @return EE_Base_Class
5622
+	 * @throws EE_Error
5623
+	 * @throws ReflectionException
5624
+	 */
5625
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5626
+	{
5627
+		$obj_in_map = $this->get_from_entity_map($id);
5628
+		if ($obj_in_map) {
5629
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5630
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5631
+					$obj_in_map->set($field_name, $value);
5632
+				}
5633
+				// make the model object in the entity map's cache match the $replacing_model_obj
5634
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5635
+					$obj_in_map->clear_cache($relation_name, null, true);
5636
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5637
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5638
+					}
5639
+				}
5640
+			}
5641
+			return $obj_in_map;
5642
+		}
5643
+		$this->add_to_entity_map($replacing_model_obj);
5644
+		return $replacing_model_obj;
5645
+	}
5646
+
5647
+
5648
+	/**
5649
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5650
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5651
+	 * require_once($this->_getClassName().".class.php");
5652
+	 *
5653
+	 * @return string
5654
+	 */
5655
+	private function _get_class_name()
5656
+	{
5657
+		return "EE_" . $this->get_this_model_name();
5658
+	}
5659
+
5660
+
5661
+	/**
5662
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5663
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5664
+	 * it would be 'Events'.
5665
+	 *
5666
+	 * @param int|float|null $quantity
5667
+	 * @return string
5668
+	 */
5669
+	public function item_name($quantity = 1): string
5670
+	{
5671
+		$quantity = floor($quantity);
5672
+		return apply_filters(
5673
+			'FHEE__EEM_Base__item_name__plural_or_singular',
5674
+			$quantity > 1 ? $this->plural_item : $this->singular_item,
5675
+			$quantity,
5676
+			$this->plural_item,
5677
+			$this->singular_item
5678
+		);
5679
+	}
5680
+
5681
+
5682
+	/**
5683
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5684
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5685
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5686
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5687
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5688
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5689
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5690
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5691
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5692
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5693
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5694
+	 *        return $previousReturnValue.$returnString;
5695
+	 * }
5696
+	 * require('EEM_Answer.model.php');
5697
+	 * echo EEM_Answer::instance()->my_callback('monkeys',100);
5698
+	 * // will output "you called my_callback! and passed args:monkeys,100"
5699
+	 *
5700
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5701
+	 * @param array  $args       array of original arguments passed to the function
5702
+	 * @return mixed whatever the plugin which calls add_filter decides
5703
+	 * @throws EE_Error
5704
+	 */
5705
+	public function __call($methodName, $args)
5706
+	{
5707
+		$className = get_class($this);
5708
+		$tagName   = "FHEE__{$className}__{$methodName}";
5709
+		if (! has_filter($tagName)) {
5710
+			throw new EE_Error(
5711
+				sprintf(
5712
+					esc_html__(
5713
+						'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 );',
5714
+						'event_espresso'
5715
+					),
5716
+					$methodName,
5717
+					$className,
5718
+					$tagName,
5719
+					'<br />'
5720
+				)
5721
+			);
5722
+		}
5723
+		return apply_filters($tagName, null, $this, $args);
5724
+	}
5725
+
5726
+
5727
+	/**
5728
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5729
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5730
+	 *
5731
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5732
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5733
+	 *                                                       the object's class name
5734
+	 *                                                       or object's ID
5735
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5736
+	 *                                                       exists in the database. If it does not, we add it
5737
+	 * @return EE_Base_Class
5738
+	 * @throws EE_Error
5739
+	 * @throws ReflectionException
5740
+	 */
5741
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5742
+	{
5743
+		$className = $this->_get_class_name();
5744
+		if ($base_class_obj_or_id instanceof $className) {
5745
+			$model_object = $base_class_obj_or_id;
5746
+		} else {
5747
+			$primary_key_field = $this->get_primary_key_field();
5748
+			if (
5749
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5750
+				&& (
5751
+					is_int($base_class_obj_or_id)
5752
+					|| is_string($base_class_obj_or_id)
5753
+				)
5754
+			) {
5755
+				// assume it's an ID.
5756
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5757
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5758
+			} elseif (
5759
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5760
+				&& is_string($base_class_obj_or_id)
5761
+			) {
5762
+				// assume its a string representation of the object
5763
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5764
+			} else {
5765
+				throw new EE_Error(
5766
+					sprintf(
5767
+						esc_html__(
5768
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5769
+							'event_espresso'
5770
+						),
5771
+						$base_class_obj_or_id,
5772
+						$this->_get_class_name(),
5773
+						print_r($base_class_obj_or_id, true)
5774
+					)
5775
+				);
5776
+			}
5777
+		}
5778
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5779
+			$model_object->save();
5780
+		}
5781
+		return $model_object;
5782
+	}
5783
+
5784
+
5785
+	/**
5786
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5787
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5788
+	 * returns it ID.
5789
+	 *
5790
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5791
+	 * @return int|string depending on the type of this model object's ID
5792
+	 * @throws EE_Error
5793
+	 * @throws ReflectionException
5794
+	 */
5795
+	public function ensure_is_ID($base_class_obj_or_id)
5796
+	{
5797
+		$className = $this->_get_class_name();
5798
+		if ($base_class_obj_or_id instanceof $className) {
5799
+			/** @var $base_class_obj_or_id EE_Base_Class */
5800
+			$id = $base_class_obj_or_id->ID();
5801
+		} elseif (is_int($base_class_obj_or_id)) {
5802
+			// assume it's an ID
5803
+			$id = $base_class_obj_or_id;
5804
+		} elseif (is_string($base_class_obj_or_id)) {
5805
+			// assume its a string representation of the object
5806
+			$id = $base_class_obj_or_id;
5807
+		} else {
5808
+			throw new EE_Error(
5809
+				sprintf(
5810
+					esc_html__(
5811
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5812
+						'event_espresso'
5813
+					),
5814
+					$base_class_obj_or_id,
5815
+					$this->_get_class_name(),
5816
+					print_r($base_class_obj_or_id, true)
5817
+				)
5818
+			);
5819
+		}
5820
+		return $id;
5821
+	}
5822
+
5823
+
5824
+	/**
5825
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5826
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5827
+	 * been sanitized and converted into the appropriate domain.
5828
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5829
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5830
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5831
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5832
+	 * $EVT = EEM_Event::instance(); $old_setting =
5833
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5834
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5835
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5836
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5837
+	 *
5838
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5839
+	 * @return void
5840
+	 */
5841
+	public function assume_values_already_prepared_by_model_object(
5842
+		$values_already_prepared = self::not_prepared_by_model_object
5843
+	) {
5844
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5845
+	}
5846
+
5847
+
5848
+	/**
5849
+	 * Read comments for assume_values_already_prepared_by_model_object()
5850
+	 *
5851
+	 * @return int
5852
+	 */
5853
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5854
+	{
5855
+		return $this->_values_already_prepared_by_model_object;
5856
+	}
5857
+
5858
+
5859
+	/**
5860
+	 * Gets all the indexes on this model
5861
+	 *
5862
+	 * @return EE_Index[]
5863
+	 */
5864
+	public function indexes()
5865
+	{
5866
+		return $this->_indexes;
5867
+	}
5868
+
5869
+
5870
+	/**
5871
+	 * Gets all the Unique Indexes on this model
5872
+	 *
5873
+	 * @return EE_Unique_Index[]
5874
+	 */
5875
+	public function unique_indexes()
5876
+	{
5877
+		$unique_indexes = [];
5878
+		foreach ($this->_indexes as $name => $index) {
5879
+			if ($index instanceof EE_Unique_Index) {
5880
+				$unique_indexes [ $name ] = $index;
5881
+			}
5882
+		}
5883
+		return $unique_indexes;
5884
+	}
5885
+
5886
+
5887
+	/**
5888
+	 * Gets all the fields which, when combined, make the primary key.
5889
+	 * This is usually just an array with 1 element (the primary key), but in cases
5890
+	 * where there is no primary key, it's a combination of fields as defined
5891
+	 * on a primary index
5892
+	 *
5893
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5894
+	 * @throws EE_Error
5895
+	 */
5896
+	public function get_combined_primary_key_fields()
5897
+	{
5898
+		foreach ($this->indexes() as $index) {
5899
+			if ($index instanceof EE_Primary_Key_Index) {
5900
+				return $index->fields();
5901
+			}
5902
+		}
5903
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5904
+	}
5905
+
5906
+
5907
+	/**
5908
+	 * Used to build a primary key string (when the model has no primary key),
5909
+	 * which can be used a unique string to identify this model object.
5910
+	 *
5911
+	 * @param array $fields_n_values keys are field names, values are their values.
5912
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5913
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5914
+	 *                               before passing it to this function (that will convert it from columns-n-values
5915
+	 *                               to field-names-n-values).
5916
+	 * @return string
5917
+	 * @throws EE_Error
5918
+	 */
5919
+	public function get_index_primary_key_string($fields_n_values)
5920
+	{
5921
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5922
+			$fields_n_values,
5923
+			$this->get_combined_primary_key_fields()
5924
+		);
5925
+		return http_build_query($cols_n_values_for_primary_key_index);
5926
+	}
5927
+
5928
+
5929
+	/**
5930
+	 * Gets the field values from the primary key string
5931
+	 *
5932
+	 * @param string $index_primary_key_string
5933
+	 * @return null|array
5934
+	 * @throws EE_Error
5935
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5936
+	 */
5937
+	public function parse_index_primary_key_string($index_primary_key_string)
5938
+	{
5939
+		$key_fields = $this->get_combined_primary_key_fields();
5940
+		// check all of them are in the $id
5941
+		$key_vals_in_combined_pk = [];
5942
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5943
+		foreach ($key_fields as $key_field_name => $field_obj) {
5944
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5945
+				return null;
5946
+			}
5947
+		}
5948
+		return $key_vals_in_combined_pk;
5949
+	}
5950
+
5951
+
5952
+	/**
5953
+	 * verifies that an array of key-value pairs for model fields has a key
5954
+	 * for each field comprising the primary key index
5955
+	 *
5956
+	 * @param array $key_vals
5957
+	 * @return boolean
5958
+	 * @throws EE_Error
5959
+	 */
5960
+	public function has_all_combined_primary_key_fields($key_vals)
5961
+	{
5962
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5963
+		foreach ($keys_it_should_have as $key) {
5964
+			if (! isset($key_vals[ $key ])) {
5965
+				return false;
5966
+			}
5967
+		}
5968
+		return true;
5969
+	}
5970
+
5971
+
5972
+	/**
5973
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5974
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5975
+	 *
5976
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5977
+	 * @param array               $query_params                     @see
5978
+	 *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5979
+	 * @throws EE_Error
5980
+	 * @throws ReflectionException
5981
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5982
+	 *                                                              indexed)
5983
+	 */
5984
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5985
+	{
5986
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5987
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5988
+		} elseif (is_array($model_object_or_attributes_array)) {
5989
+			$attributes_array = $model_object_or_attributes_array;
5990
+		} else {
5991
+			throw new EE_Error(
5992
+				sprintf(
5993
+					esc_html__(
5994
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5995
+						"event_espresso"
5996
+					),
5997
+					$model_object_or_attributes_array
5998
+				)
5999
+			);
6000
+		}
6001
+		// even copies obviously won't have the same ID, so remove the primary key
6002
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
6003
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6004
+			unset($attributes_array[ $this->primary_key_name() ]);
6005
+		}
6006
+		if (isset($query_params[0])) {
6007
+			$query_params[0] = array_merge($attributes_array, $query_params);
6008
+		} else {
6009
+			$query_params[0] = $attributes_array;
6010
+		}
6011
+		return $this->get_all($query_params);
6012
+	}
6013
+
6014
+
6015
+	/**
6016
+	 * Gets the first copy we find. See get_all_copies for more details
6017
+	 *
6018
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6019
+	 * @param array $query_params
6020
+	 * @return EE_Base_Class
6021
+	 * @throws EE_Error
6022
+	 * @throws ReflectionException
6023
+	 */
6024
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6025
+	{
6026
+		if (! is_array($query_params)) {
6027
+			EE_Error::doing_it_wrong(
6028
+				'EEM_Base::get_one_copy',
6029
+				sprintf(
6030
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6031
+					gettype($query_params)
6032
+				),
6033
+				'4.6.0'
6034
+			);
6035
+			$query_params = [];
6036
+		}
6037
+		$query_params['limit'] = 1;
6038
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6039
+		if (is_array($copies)) {
6040
+			return array_shift($copies);
6041
+		}
6042
+		return null;
6043
+	}
6044
+
6045
+
6046
+	/**
6047
+	 * Updates the item with the specified id. Ignores default query parameters because
6048
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6049
+	 *
6050
+	 * @param array      $fields_n_values keys are field names, values are their new values
6051
+	 * @param int|string $id              the value of the primary key to update
6052
+	 * @return int number of rows updated
6053
+	 * @throws EE_Error
6054
+	 * @throws ReflectionException
6055
+	 */
6056
+	public function update_by_ID($fields_n_values, $id)
6057
+	{
6058
+		$query_params = [
6059
+			0                          => [$this->get_primary_key_field()->get_name() => $id],
6060
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6061
+		];
6062
+		return $this->update($fields_n_values, $query_params);
6063
+	}
6064
+
6065
+
6066
+	/**
6067
+	 * Changes an operator which was supplied to the models into one usable in SQL
6068
+	 *
6069
+	 * @param string $operator_supplied
6070
+	 * @return string an operator which can be used in SQL
6071
+	 * @throws EE_Error
6072
+	 */
6073
+	private function _prepare_operator_for_sql($operator_supplied)
6074
+	{
6075
+		$sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6076
+		if ($sql_operator) {
6077
+			return $sql_operator;
6078
+		}
6079
+		throw new EE_Error(
6080
+			sprintf(
6081
+				esc_html__(
6082
+					"The operator '%s' is not in the list of valid operators: %s",
6083
+					"event_espresso"
6084
+				),
6085
+				$operator_supplied,
6086
+				implode(",", array_keys($this->_valid_operators))
6087
+			)
6088
+		);
6089
+	}
6090
+
6091
+
6092
+	/**
6093
+	 * Gets the valid operators
6094
+	 *
6095
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6096
+	 */
6097
+	public function valid_operators()
6098
+	{
6099
+		return $this->_valid_operators;
6100
+	}
6101
+
6102
+
6103
+	/**
6104
+	 * Gets the between-style operators (take 2 arguments).
6105
+	 *
6106
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6107
+	 */
6108
+	public function valid_between_style_operators()
6109
+	{
6110
+		return array_intersect(
6111
+			$this->valid_operators(),
6112
+			$this->_between_style_operators
6113
+		);
6114
+	}
6115
+
6116
+
6117
+	/**
6118
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6119
+	 *
6120
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6121
+	 */
6122
+	public function valid_like_style_operators()
6123
+	{
6124
+		return array_intersect(
6125
+			$this->valid_operators(),
6126
+			$this->_like_style_operators
6127
+		);
6128
+	}
6129
+
6130
+
6131
+	/**
6132
+	 * Gets the "in"-style operators
6133
+	 *
6134
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6135
+	 */
6136
+	public function valid_in_style_operators()
6137
+	{
6138
+		return array_intersect(
6139
+			$this->valid_operators(),
6140
+			$this->_in_style_operators
6141
+		);
6142
+	}
6143
+
6144
+
6145
+	/**
6146
+	 * Gets the "null"-style operators (accept no arguments)
6147
+	 *
6148
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6149
+	 */
6150
+	public function valid_null_style_operators()
6151
+	{
6152
+		return array_intersect(
6153
+			$this->valid_operators(),
6154
+			$this->_null_style_operators
6155
+		);
6156
+	}
6157
+
6158
+
6159
+	/**
6160
+	 * Gets an array where keys are the primary keys and values are their 'names'
6161
+	 * (as determined by the model object's name() function, which is often overridden)
6162
+	 *
6163
+	 * @param array $query_params like get_all's
6164
+	 * @return string[]
6165
+	 * @throws EE_Error
6166
+	 * @throws ReflectionException
6167
+	 */
6168
+	public function get_all_names($query_params = [])
6169
+	{
6170
+		$objs  = $this->get_all($query_params);
6171
+		$names = [];
6172
+		foreach ($objs as $obj) {
6173
+			$names[ $obj->ID() ] = $obj->name();
6174
+		}
6175
+		return $names;
6176
+	}
6177
+
6178
+
6179
+	/**
6180
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6181
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6182
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6183
+	 * array_keys() on $model_objects.
6184
+	 *
6185
+	 * @param \EE_Base_Class[] $model_objects
6186
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6187
+	 *                                               in the returned array
6188
+	 * @return array
6189
+	 * @throws EE_Error
6190
+	 * @throws ReflectionException
6191
+	 */
6192
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6193
+	{
6194
+		if (! $this->has_primary_key_field()) {
6195
+			if (WP_DEBUG) {
6196
+				EE_Error::add_error(
6197
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6198
+					__FILE__,
6199
+					__FUNCTION__,
6200
+					__LINE__
6201
+				);
6202
+			}
6203
+		}
6204
+		$IDs = [];
6205
+		foreach ($model_objects as $model_object) {
6206
+			$id = $model_object->ID();
6207
+			if (! $id) {
6208
+				if ($filter_out_empty_ids) {
6209
+					continue;
6210
+				}
6211
+				if (WP_DEBUG) {
6212
+					EE_Error::add_error(
6213
+						esc_html__(
6214
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6215
+							'event_espresso'
6216
+						),
6217
+						__FILE__,
6218
+						__FUNCTION__,
6219
+						__LINE__
6220
+					);
6221
+				}
6222
+			}
6223
+			$IDs[] = $id;
6224
+		}
6225
+		return $IDs;
6226
+	}
6227
+
6228
+
6229
+	/**
6230
+	 * Returns the string used in capabilities relating to this model. If there
6231
+	 * are no capabilities that relate to this model returns false
6232
+	 *
6233
+	 * @return string|false
6234
+	 */
6235
+	public function cap_slug()
6236
+	{
6237
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6238
+	}
6239
+
6240
+
6241
+	/**
6242
+	 * Returns the capability-restrictions array (@param string $context
6243
+	 *
6244
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6245
+	 * @throws EE_Error
6246
+	 * @see EEM_Base::_cap_restrictions).
6247
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6248
+	 *      only returns the cap restrictions array in that context (ie, the array
6249
+	 *      at that key)
6250
+	 *
6251
+	 */
6252
+	public function cap_restrictions($context = EEM_Base::caps_read)
6253
+	{
6254
+		EEM_Base::verify_is_valid_cap_context($context);
6255
+		// check if we ought to run the restriction generator first
6256
+		if (
6257
+			isset($this->_cap_restriction_generators[ $context ])
6258
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6259
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6260
+		) {
6261
+			$this->_cap_restrictions[ $context ] = array_merge(
6262
+				$this->_cap_restrictions[ $context ],
6263
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6264
+			);
6265
+		}
6266
+		// and make sure we've finalized the construction of each restriction
6267
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6268
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6269
+				$where_conditions_obj->_finalize_construct($this);
6270
+			}
6271
+		}
6272
+		return $this->_cap_restrictions[ $context ];
6273
+	}
6274
+
6275
+
6276
+	/**
6277
+	 * Indicating whether or not this model thinks its a wp core model
6278
+	 *
6279
+	 * @return boolean
6280
+	 */
6281
+	public function is_wp_core_model()
6282
+	{
6283
+		return $this->_wp_core_model;
6284
+	}
6285
+
6286
+
6287
+	/**
6288
+	 * Gets all the caps that are missing which impose a restriction on
6289
+	 * queries made in this context
6290
+	 *
6291
+	 * @param string $context one of EEM_Base::caps_ constants
6292
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6293
+	 * @throws EE_Error
6294
+	 */
6295
+	public function caps_missing($context = EEM_Base::caps_read)
6296
+	{
6297
+		$missing_caps     = [];
6298
+		$cap_restrictions = $this->cap_restrictions($context);
6299
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6300
+			if (
6301
+				! EE_Capabilities::instance()
6302
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6303
+			) {
6304
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6305
+			}
6306
+		}
6307
+		return $missing_caps;
6308
+	}
6309
+
6310
+
6311
+	/**
6312
+	 * Gets the mapping from capability contexts to action strings used in capability names
6313
+	 *
6314
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6315
+	 * one of 'read', 'edit', or 'delete'
6316
+	 */
6317
+	public function cap_contexts_to_cap_action_map()
6318
+	{
6319
+		return apply_filters(
6320
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6321
+			$this->_cap_contexts_to_cap_action_map,
6322
+			$this
6323
+		);
6324
+	}
6325
+
6326
+
6327
+	/**
6328
+	 * Gets the action string for the specified capability context
6329
+	 *
6330
+	 * @param string $context
6331
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6332
+	 * @throws EE_Error
6333
+	 */
6334
+	public function cap_action_for_context($context)
6335
+	{
6336
+		$mapping = $this->cap_contexts_to_cap_action_map();
6337
+		if (isset($mapping[ $context ])) {
6338
+			return $mapping[ $context ];
6339
+		}
6340
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6341
+			return $action;
6342
+		}
6343
+		throw new EE_Error(
6344
+			sprintf(
6345
+				esc_html__(
6346
+					'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6347
+					'event_espresso'
6348
+				),
6349
+				$context,
6350
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6351
+			)
6352
+		);
6353
+	}
6354
+
6355
+
6356
+	/**
6357
+	 * Returns all the capability contexts which are valid when querying models
6358
+	 *
6359
+	 * @return array
6360
+	 */
6361
+	public static function valid_cap_contexts()
6362
+	{
6363
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', [
6364
+			self::caps_read,
6365
+			self::caps_read_admin,
6366
+			self::caps_edit,
6367
+			self::caps_delete,
6368
+		]);
6369
+	}
6370
+
6371
+
6372
+	/**
6373
+	 * Returns all valid options for 'default_where_conditions'
6374
+	 *
6375
+	 * @return array
6376
+	 */
6377
+	public static function valid_default_where_conditions()
6378
+	{
6379
+		return [
6380
+			EEM_Base::default_where_conditions_all,
6381
+			EEM_Base::default_where_conditions_this_only,
6382
+			EEM_Base::default_where_conditions_others_only,
6383
+			EEM_Base::default_where_conditions_minimum_all,
6384
+			EEM_Base::default_where_conditions_minimum_others,
6385
+			EEM_Base::default_where_conditions_none,
6386
+		];
6387
+	}
6388
+
6389
+	// public static function default_where_conditions_full
6390
+
6391
+
6392
+	/**
6393
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6394
+	 *
6395
+	 * @param string $context
6396
+	 * @return bool
6397
+	 * @throws EE_Error
6398
+	 */
6399
+	public static function verify_is_valid_cap_context($context)
6400
+	{
6401
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6402
+		if (in_array($context, $valid_cap_contexts)) {
6403
+			return true;
6404
+		}
6405
+		throw new EE_Error(
6406
+			sprintf(
6407
+				esc_html__(
6408
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6409
+					'event_espresso'
6410
+				),
6411
+				$context,
6412
+				'EEM_Base',
6413
+				implode(',', $valid_cap_contexts)
6414
+			)
6415
+		);
6416
+	}
6417
+
6418
+
6419
+	/**
6420
+	 * Clears all the models field caches. This is only useful when a sub-class
6421
+	 * might have added a field or something and these caches might be invalidated
6422
+	 */
6423
+	protected function _invalidate_field_caches()
6424
+	{
6425
+		$this->_cache_foreign_key_to_fields = [];
6426
+		$this->_cached_fields               = null;
6427
+		$this->_cached_fields_non_db_only   = null;
6428
+	}
6429
+
6430
+
6431
+	/**
6432
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6433
+	 * (eg "and", "or", "not").
6434
+	 *
6435
+	 * @return array
6436
+	 */
6437
+	public function logic_query_param_keys()
6438
+	{
6439
+		return $this->_logic_query_param_keys;
6440
+	}
6441
+
6442
+
6443
+	/**
6444
+	 * Determines whether or not the where query param array key is for a logic query param.
6445
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6446
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6447
+	 *
6448
+	 * @param $query_param_key
6449
+	 * @return bool
6450
+	 */
6451
+	public function is_logic_query_param_key($query_param_key)
6452
+	{
6453
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6454
+			if (
6455
+				$query_param_key === $logic_query_param_key
6456
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6457
+			) {
6458
+				return true;
6459
+			}
6460
+		}
6461
+		return false;
6462
+	}
6463
+
6464
+
6465
+	/**
6466
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6467
+	 *
6468
+	 * @return boolean
6469
+	 * @since 4.9.74.p
6470
+	 */
6471
+	public function hasPassword()
6472
+	{
6473
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6474
+		if ($this->has_password_field === null) {
6475
+			$password_field           = $this->getPasswordField();
6476
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6477
+		}
6478
+		return $this->has_password_field;
6479
+	}
6480
+
6481
+
6482
+	/**
6483
+	 * Returns the password field on this model, if there is one
6484
+	 *
6485
+	 * @return EE_Password_Field|null
6486
+	 * @since 4.9.74.p
6487
+	 */
6488
+	public function getPasswordField()
6489
+	{
6490
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6491
+		// there's no need to search for it. If we don't know yet, then find out
6492
+		if ($this->has_password_field === null && $this->password_field === null) {
6493
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6494
+		}
6495
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6496
+		return $this->password_field;
6497
+	}
6498
+
6499
+
6500
+	/**
6501
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6502
+	 *
6503
+	 * @return EE_Model_Field_Base[]
6504
+	 * @throws EE_Error
6505
+	 * @since 4.9.74.p
6506
+	 */
6507
+	public function getPasswordProtectedFields()
6508
+	{
6509
+		$password_field = $this->getPasswordField();
6510
+		$fields         = [];
6511
+		if ($password_field instanceof EE_Password_Field) {
6512
+			$field_names = $password_field->protectedFields();
6513
+			foreach ($field_names as $field_name) {
6514
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6515
+			}
6516
+		}
6517
+		return $fields;
6518
+	}
6519
+
6520
+
6521
+	/**
6522
+	 * Checks if the current user can perform the requested action on this model
6523
+	 *
6524
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6525
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6526
+	 * @return bool
6527
+	 * @throws EE_Error
6528
+	 * @throws InvalidArgumentException
6529
+	 * @throws InvalidDataTypeException
6530
+	 * @throws InvalidInterfaceException
6531
+	 * @throws ReflectionException
6532
+	 * @throws UnexpectedEntityException
6533
+	 * @since 4.9.74.p
6534
+	 */
6535
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6536
+	{
6537
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6538
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6539
+		}
6540
+		if (! is_array($model_obj_or_fields_n_values)) {
6541
+			throw new UnexpectedEntityException(
6542
+				$model_obj_or_fields_n_values,
6543
+				'EE_Base_Class',
6544
+				sprintf(
6545
+					esc_html__(
6546
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6547
+						'event_espresso'
6548
+					),
6549
+					__FUNCTION__
6550
+				)
6551
+			);
6552
+		}
6553
+		return $this->exists(
6554
+			$this->alter_query_params_to_restrict_by_ID(
6555
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6556
+				[
6557
+					'default_where_conditions' => 'none',
6558
+					'caps'                     => $cap_to_check,
6559
+				]
6560
+			)
6561
+		);
6562
+	}
6563
+
6564
+
6565
+	/**
6566
+	 * Returns the query param where conditions key to the password affecting this model.
6567
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6568
+	 *
6569
+	 * @return null|string
6570
+	 * @throws EE_Error
6571
+	 * @throws InvalidArgumentException
6572
+	 * @throws InvalidDataTypeException
6573
+	 * @throws InvalidInterfaceException
6574
+	 * @throws ModelConfigurationException
6575
+	 * @throws ReflectionException
6576
+	 * @since 4.9.74.p
6577
+	 */
6578
+	public function modelChainAndPassword()
6579
+	{
6580
+		if ($this->model_chain_to_password === null) {
6581
+			throw new ModelConfigurationException(
6582
+				$this,
6583
+				esc_html_x(
6584
+				// @codingStandardsIgnoreStart
6585
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6586
+					// @codingStandardsIgnoreEnd
6587
+					'1: model name',
6588
+					'event_espresso'
6589
+				)
6590
+			);
6591
+		}
6592
+		if ($this->model_chain_to_password === '') {
6593
+			$model_with_password = $this;
6594
+		} else {
6595
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6596
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6597
+			} else {
6598
+				$last_model_in_chain = $this->model_chain_to_password;
6599
+			}
6600
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6601
+		}
6602
+
6603
+		$password_field = $model_with_password->getPasswordField();
6604
+		if ($password_field instanceof EE_Password_Field) {
6605
+			$password_field_name = $password_field->get_name();
6606
+		} else {
6607
+			throw new ModelConfigurationException(
6608
+				$this,
6609
+				sprintf(
6610
+					esc_html_x(
6611
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6612
+						'1: model name, 2: special string',
6613
+						'event_espresso'
6614
+					),
6615
+					$model_with_password->get_this_model_name(),
6616
+					$this->model_chain_to_password
6617
+				)
6618
+			);
6619
+		}
6620
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6621
+	}
6622
+
6623
+
6624
+	/**
6625
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6626
+	 * or if this model itself has a password affecting access to some of its other fields.
6627
+	 *
6628
+	 * @return boolean
6629
+	 * @since 4.9.74.p
6630
+	 */
6631
+	public function restrictedByRelatedModelPassword()
6632
+	{
6633
+		return $this->model_chain_to_password !== null;
6634
+	}
6635 6635
 }
Please login to merge, or discard this patch.
core/domain/entities/editor/CoreBlocksAssetManager.php 1 patch
Indentation   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -16,31 +16,31 @@
 block discarded – undo
16 16
  */
17 17
 class CoreBlocksAssetManager extends BlockAssetManager
18 18
 {
19
-    const DOMAIN = 'blocks';
20
-
21
-    const ASSET_HANDLE_EDITOR_BLOCKS = Domain::ASSET_NAMESPACE . '-' . CoreBlocksAssetManager::DOMAIN;
22
-    const ASSET_HANDLE_CORE_BLOCKS = '';
23
-
24
-
25
-    /**
26
-     * @since  $VID:$
27
-     * @throws DomainException
28
-     */
29
-    public function enqueueEventEditor()
30
-    {
31
-        if ($this->verifyAssetIsRegistered(CoreBlocksAssetManager::ASSET_HANDLE_EDITOR_BLOCKS)) {
32
-            wp_enqueue_script(CoreBlocksAssetManager::ASSET_HANDLE_EDITOR_BLOCKS);
33
-            wp_enqueue_style(CoreBlocksAssetManager::ASSET_HANDLE_EDITOR_BLOCKS);
34
-        }
35
-    }
36
-
37
-
38
-    /**
39
-     * @since 4.9.71.p
40
-     */
41
-    public function setAssetHandles()
42
-    {
43
-        $this->setEditorScriptHandle(CoreBlocksAssetManager::ASSET_HANDLE_EDITOR_BLOCKS);
44
-        $this->setScriptHandle(CoreBlocksAssetManager::ASSET_HANDLE_CORE_BLOCKS);
45
-    }
19
+	const DOMAIN = 'blocks';
20
+
21
+	const ASSET_HANDLE_EDITOR_BLOCKS = Domain::ASSET_NAMESPACE . '-' . CoreBlocksAssetManager::DOMAIN;
22
+	const ASSET_HANDLE_CORE_BLOCKS = '';
23
+
24
+
25
+	/**
26
+	 * @since  $VID:$
27
+	 * @throws DomainException
28
+	 */
29
+	public function enqueueEventEditor()
30
+	{
31
+		if ($this->verifyAssetIsRegistered(CoreBlocksAssetManager::ASSET_HANDLE_EDITOR_BLOCKS)) {
32
+			wp_enqueue_script(CoreBlocksAssetManager::ASSET_HANDLE_EDITOR_BLOCKS);
33
+			wp_enqueue_style(CoreBlocksAssetManager::ASSET_HANDLE_EDITOR_BLOCKS);
34
+		}
35
+	}
36
+
37
+
38
+	/**
39
+	 * @since 4.9.71.p
40
+	 */
41
+	public function setAssetHandles()
42
+	{
43
+		$this->setEditorScriptHandle(CoreBlocksAssetManager::ASSET_HANDLE_EDITOR_BLOCKS);
44
+		$this->setScriptHandle(CoreBlocksAssetManager::ASSET_HANDLE_CORE_BLOCKS);
45
+	}
46 46
 }
Please login to merge, or discard this patch.
core/db_classes/EE_CPT_Base.class.php 1 patch
Indentation   +440 added lines, -440 removed lines patch added patch discarded remove patch
@@ -13,444 +13,444 @@
 block discarded – undo
13 13
  */
14 14
 abstract class EE_CPT_Base extends EE_Soft_Delete_Base_Class
15 15
 {
16
-    /**
17
-     * @var stdClass
18
-     * @since $VID:$
19
-     */
20
-    public $labels;
21
-
22
-    /**
23
-     * @var string
24
-     * @since $VID:$
25
-     */
26
-    public $name;
27
-
28
-    /**
29
-     * This is a property for holding cached feature images on CPT objects.  Cache's are set on the first
30
-     * "feature_image()" method call.  Each key in the array corresponds to the requested size.
31
-     *
32
-     * @var array
33
-     */
34
-    protected $_feature_image = array();
35
-
36
-    /**
37
-     * @var WP_Post the WP_Post that corresponds with this CPT model object
38
-     */
39
-    protected $_wp_post;
40
-
41
-
42
-    abstract public function wp_user();
43
-
44
-
45
-    /**
46
-     * Returns the WP post associated with this CPT model object. If this CPT is saved, fetches it
47
-     * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
48
-     *
49
-     * @return WP_Post
50
-     */
51
-    public function wp_post()
52
-    {
53
-        global $wpdb;
54
-        if (! $this->_wp_post instanceof WP_Post) {
55
-            if ($this->ID()) {
56
-                $this->_wp_post = get_post($this->ID());
57
-            } else {
58
-                $simulated_db_result = new stdClass();
59
-                foreach ($this->get_model()->field_settings(true) as $field_name => $field_obj) {
60
-                    if (
61
-                        $this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name()
62
-                        === $wpdb->posts
63
-                    ) {
64
-                        $column = $field_obj->get_table_column();
65
-
66
-                        if ($field_obj instanceof EE_Datetime_Field) {
67
-                            $value_on_model_obj = $this->get_DateTime_object($field_name);
68
-                        } elseif ($field_obj->is_db_only_field()) {
69
-                            $value_on_model_obj = $field_obj->get_default_value();
70
-                        } else {
71
-                            $value_on_model_obj = $this->get_raw($field_name);
72
-                        }
73
-                        $simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
74
-                    }
75
-                }
76
-                $this->_wp_post = new WP_Post($simulated_db_result);
77
-            }
78
-            // and let's make retrieving the EE CPT object easy too
79
-            $classname = get_class($this);
80
-            if (! isset($this->_wp_post->{$classname})) {
81
-                $this->_wp_post->{$classname} = $this;
82
-            }
83
-        }
84
-        return $this->_wp_post;
85
-    }
86
-
87
-    /**
88
-     * When fetching a new value for a post field that uses the global $post for rendering,
89
-     * set the global $post temporarily to be this model object; and afterwards restore it
90
-     *
91
-     * @param string $fieldname
92
-     * @param bool   $pretty
93
-     * @param string $extra_cache_ref
94
-     * @return mixed
95
-     */
96
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
97
-    {
98
-        global $post;
99
-
100
-        if (
101
-            $pretty
102
-            && (
103
-                ! (
104
-                    $post instanceof WP_Post
105
-                    && $post->ID
106
-                )
107
-                || (int) $post->ID !== $this->ID()
108
-            )
109
-            && $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field
110
-        ) {
111
-            $old_post = $post;
112
-            $post = $this->wp_post();
113
-            $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
114
-            $post = $old_post;
115
-        } else {
116
-            $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
117
-        }
118
-        return $return_value;
119
-    }
120
-
121
-    /**
122
-     * Adds to the specified event category. If it category doesn't exist, creates it.
123
-     *
124
-     * @param string $category_name
125
-     * @param string $category_description    optional
126
-     * @param int    $parent_term_taxonomy_id optional
127
-     * @return EE_Term_Taxonomy
128
-     */
129
-    public function add_event_category($category_name, $category_description = null, $parent_term_taxonomy_id = null)
130
-    {
131
-        return $this->get_model()->add_event_category(
132
-            $this,
133
-            $category_name,
134
-            $category_description,
135
-            $parent_term_taxonomy_id
136
-        );
137
-    }
138
-
139
-
140
-    /**
141
-     * Removes the event category by specified name from being related ot this event
142
-     *
143
-     * @param string $category_name
144
-     * @return bool
145
-     */
146
-    public function remove_event_category($category_name)
147
-    {
148
-        return $this->get_model()->remove_event_category($this, $category_name);
149
-    }
150
-
151
-
152
-    /**
153
-     * Removes the relation to the specified term taxonomy, and maintains the
154
-     * data integrity of the term taxonomy provided
155
-     *
156
-     * @param EE_Term_Taxonomy $term_taxonomy
157
-     * @return EE_Base_Class the relation was removed from
158
-     */
159
-    public function remove_relation_to_term_taxonomy($term_taxonomy)
160
-    {
161
-        if (! $term_taxonomy) {
162
-            EE_Error::add_error(
163
-                sprintf(
164
-                    esc_html__(
165
-                        "No Term_Taxonomy provided which to remove from model object of type %s and id %d",
166
-                        "event_espresso"
167
-                    ),
168
-                    get_class($this),
169
-                    $this->ID()
170
-                ),
171
-                __FILE__,
172
-                __FUNCTION__,
173
-                __LINE__
174
-            );
175
-            return null;
176
-        }
177
-        $term_taxonomy->set_count($term_taxonomy->count() - 1);
178
-        $term_taxonomy->save();
179
-        return $this->_remove_relation_to($term_taxonomy, 'Term_Taxonomy');
180
-    }
181
-
182
-
183
-    /**
184
-     * The main purpose of this method is to return the post type for the model object
185
-     *
186
-     * @access public
187
-     * @return string
188
-     */
189
-    public function post_type()
190
-    {
191
-        return $this->get_model()->post_type();
192
-    }
193
-
194
-
195
-    /**
196
-     * The main purpose of this method is to return the parent for the model object
197
-     *
198
-     * @access public
199
-     * @return int
200
-     */
201
-    public function parent()
202
-    {
203
-        return $this->get('parent');
204
-    }
205
-
206
-
207
-    /**
208
-     * return the _status property
209
-     *
210
-     * @return string
211
-     */
212
-    public function status()
213
-    {
214
-        return $this->get('status');
215
-    }
216
-
217
-
218
-    /**
219
-     * @param string $status
220
-     */
221
-    public function set_status($status)
222
-    {
223
-        $this->set('status', $status);
224
-    }
225
-
226
-
227
-    /**
228
-     * This calls the equivalent model method for retrieving the feature image which in turn is a wrapper for
229
-     * WordPress' get_the_post_thumbnail() function.
230
-     *
231
-     * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
232
-     * @access protected
233
-     * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
234
-     *                           representing width and height in pixels (i.e. array(32,32) ).
235
-     * @param string|array $attr Optional. Query string or array of attributes.
236
-     * @return string HTML image element
237
-     */
238
-    protected function _get_feature_image($size, $attr)
239
-    {
240
-        // first let's see if we already have the _feature_image property set AND if it has a cached element on it FOR the given size
241
-        $attr_key = is_array($attr) ? implode('_', $attr) : $attr;
242
-        $cache_key = is_array($size) ? implode('_', $size) . $attr_key : $size . $attr_key;
243
-        $this->_feature_image[ $cache_key ] = isset($this->_feature_image[ $cache_key ])
244
-            ? $this->_feature_image[ $cache_key ] : $this->get_model()->get_feature_image($this->ID(), $size, $attr);
245
-        return $this->_feature_image[ $cache_key ];
246
-    }
247
-
248
-
249
-    /**
250
-     * See _get_feature_image. Returns the HTML to display a featured image
251
-     *
252
-     * @param string       $size
253
-     * @param string|array $attr
254
-     * @return string of html
255
-     */
256
-    public function feature_image($size = 'thumbnail', $attr = '')
257
-    {
258
-        return $this->_get_feature_image($size, $attr);
259
-    }
260
-
261
-
262
-    /**
263
-     * This uses the wp "wp_get_attachment_image_src()" function to return the feature image for the current class
264
-     * using the given size params.
265
-     *
266
-     * @param  string|array $size can either be a string: 'thumbnail', 'medium', 'large', 'full' OR 2-item array
267
-     *                            representing width and height in pixels eg. array(32,32).
268
-     * @return string|boolean          the url of the image or false if not found
269
-     */
270
-    public function feature_image_url($size = 'thumbnail')
271
-    {
272
-        $attachment = wp_get_attachment_image_src(get_post_thumbnail_id($this->ID()), $size);
273
-        return ! empty($attachment) ? $attachment[0] : false;
274
-    }
275
-
276
-
277
-    /**
278
-     * This is a method for restoring this_obj using details from the given $revision_id
279
-     *
280
-     * @param int   $revision_id       ID of the revision we're getting data from
281
-     * @param array $related_obj_names if included this will be used to restore for related obj
282
-     *                                 if not included then we just do restore on the meta.
283
-     *                                 We will accept an array of related_obj_names for restoration here.
284
-     * @param array $where_query       You can optionally include an array of key=>value pairs
285
-     *                                 that allow you to further constrict the relation to being added.
286
-     *                                 However, keep in mind that the columns (keys) given
287
-     *                                 must match a column on the JOIN table and currently
288
-     *                                 only the HABTM models accept these additional conditions.
289
-     *                                 Also remember that if an exact match isn't found for these extra cols/val pairs,
290
-     *                                 then a NEW row is created in the join table.
291
-     *                                 This array is INDEXED by RELATED OBJ NAME (so it corresponds with the obj_names
292
-     *                                 sent);
293
-     * @return void
294
-     */
295
-    public function restore_revision($revision_id, $related_obj_names = array(), $where_query = array())
296
-    {
297
-        // get revision object
298
-        $revision_obj = $this->get_model()->get_one_by_ID($revision_id);
299
-        if ($revision_obj instanceof EE_CPT_Base) {
300
-            // no related_obj_name so we assume we're saving a revision on this object.
301
-            if (empty($related_obj_names)) {
302
-                $fields = $this->get_model()->get_meta_table_fields();
303
-                foreach ($fields as $field) {
304
-                    $this->set($field, $revision_obj->get($field));
305
-                }
306
-                $this->save();
307
-            }
308
-            $related_obj_names = (array) $related_obj_names;
309
-            foreach ($related_obj_names as $related_name) {
310
-                // related_obj_name so we're saving a revision on an object related to this object
311
-                // do we have $where_query params for this related object?  If we do then we include that.
312
-                $cols_n_values = isset($where_query[ $related_name ]) ? $where_query[ $related_name ] : array();
313
-                $where_params = ! empty($cols_n_values) ? array($cols_n_values) : array();
314
-                $related_objs = $this->get_many_related($related_name, $where_params);
315
-                $revision_related_objs = $revision_obj->get_many_related($related_name, $where_params);
316
-                // load helper
317
-                // remove related objs from this object that are not in revision
318
-                // array_diff *should* work cause I think objects are indexed by ID?
319
-                $related_to_remove = EEH_Array::object_array_diff($related_objs, $revision_related_objs);
320
-                foreach ($related_to_remove as $rr) {
321
-                    $this->_remove_relation_to($rr, $related_name, $cols_n_values);
322
-                }
323
-                // add all related objs attached to revision to this object
324
-                foreach ($revision_related_objs as $r_obj) {
325
-                    $this->_add_relation_to($r_obj, $related_name, $cols_n_values);
326
-                }
327
-            }
328
-        }
329
-    }
330
-
331
-
332
-    /**
333
-     * Wrapper for get_post_meta, http://codex.wordpress.org/Function_Reference/get_post_meta
334
-     *
335
-     * @param string  $meta_key
336
-     * @param boolean $single
337
-     * @return mixed <ul><li>If only $id is set it will return all meta values in an associative array.</li>
338
-     * <li>If $single is set to false, or left blank, the function returns an array containing all values of the
339
-     * specified key.</li>
340
-     * <li>If $single is set to true, the function returns the first value of the specified key (not in an
341
-     * array</li></ul>
342
-     */
343
-    public function get_post_meta($meta_key = null, $single = false)
344
-    {
345
-        return get_post_meta($this->ID(), $meta_key, $single);
346
-    }
347
-
348
-
349
-    /**
350
-     * Wrapper for update_post_meta, http://codex.wordpress.org/Function_Reference/update_post_meta
351
-     *
352
-     * @param string $meta_key
353
-     * @param mixed  $meta_value
354
-     * @param mixed  $prev_value
355
-     * @return mixed Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure.
356
-     *               NOTE: If the meta_value passed to this function is the same as the value that is already in the
357
-     *               database, this function returns false.
358
-     */
359
-    public function update_post_meta($meta_key, $meta_value, $prev_value = null)
360
-    {
361
-        if (! $this->ID()) {
362
-            $this->save();
363
-        }
364
-        return update_post_meta($this->ID(), $meta_key, $meta_value, $prev_value);
365
-    }
366
-
367
-
368
-    /**
369
-     * Wrapper for add_post_meta, http://codex.wordpress.org/Function_Reference/add_post_meta
370
-     *
371
-     * @param mixed $meta_key
372
-     * @param mixed $meta_value
373
-     * @param bool  $unique . If postmeta for this $meta_key already exists, whether to add an additional item or not
374
-     * @return boolean Boolean true, except if the $unique argument was set to true and a custom field with the given
375
-     *                 key already exists, in which case false is returned.
376
-     */
377
-    public function add_post_meta($meta_key, $meta_value, $unique = false)
378
-    {
379
-        if ($this->ID()) {
380
-            $this->save();
381
-        }
382
-        return add_post_meta($this->ID(), $meta_key, $meta_value, $unique);
383
-    }
384
-
385
-
386
-    /**
387
-     * Wrapper for delete_post_meta, http://codex.wordpress.org/Function_Reference/delete_post_meta
388
-     *
389
-     * @param mixed $meta_key
390
-     * @param mixed $meta_value
391
-     * @return boolean False for failure. True for success.
392
-     */
393
-    public function delete_post_meta($meta_key, $meta_value = '')
394
-    {
395
-        if (! $this->ID()) {
396
-            // there are obviously no postmetas for this if it's not saved
397
-            // so let's just report this as a success
398
-            return true;
399
-        }
400
-        return delete_post_meta($this->ID(), $meta_key, $meta_value);
401
-    }
402
-
403
-
404
-    /**
405
-     * Gets the URL for viewing this event on the front-end
406
-     *
407
-     * @return string
408
-     */
409
-    public function get_permalink()
410
-    {
411
-        return get_permalink($this->ID());
412
-    }
413
-
414
-
415
-    /**
416
-     * Gets all the term-taxonomies for this CPT
417
-     *
418
-     * @param array $query_params
419
-     * @return EE_Term_Taxonomy
420
-     */
421
-    public function term_taxonomies($query_params = array())
422
-    {
423
-        return $this->get_many_related('Term_Taxonomy', $query_params);
424
-    }
425
-
426
-
427
-    /**
428
-     * @return mixed
429
-     */
430
-    public function get_custom_post_statuses()
431
-    {
432
-        return $this->get_model()->get_custom_post_statuses();
433
-    }
434
-
435
-
436
-    /**
437
-     * @return mixed
438
-     */
439
-    public function get_all_post_statuses()
440
-    {
441
-        return $this->get_model()->get_status_array();
442
-    }
443
-
444
-
445
-    /**
446
-     * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
447
-     *
448
-     * @return array
449
-     */
450
-    public function __sleep()
451
-    {
452
-        $properties_to_serialize = parent::__sleep();
453
-        $properties_to_serialize = array_diff($properties_to_serialize, array('_wp_post'));
454
-        return $properties_to_serialize;
455
-    }
16
+	/**
17
+	 * @var stdClass
18
+	 * @since $VID:$
19
+	 */
20
+	public $labels;
21
+
22
+	/**
23
+	 * @var string
24
+	 * @since $VID:$
25
+	 */
26
+	public $name;
27
+
28
+	/**
29
+	 * This is a property for holding cached feature images on CPT objects.  Cache's are set on the first
30
+	 * "feature_image()" method call.  Each key in the array corresponds to the requested size.
31
+	 *
32
+	 * @var array
33
+	 */
34
+	protected $_feature_image = array();
35
+
36
+	/**
37
+	 * @var WP_Post the WP_Post that corresponds with this CPT model object
38
+	 */
39
+	protected $_wp_post;
40
+
41
+
42
+	abstract public function wp_user();
43
+
44
+
45
+	/**
46
+	 * Returns the WP post associated with this CPT model object. If this CPT is saved, fetches it
47
+	 * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
48
+	 *
49
+	 * @return WP_Post
50
+	 */
51
+	public function wp_post()
52
+	{
53
+		global $wpdb;
54
+		if (! $this->_wp_post instanceof WP_Post) {
55
+			if ($this->ID()) {
56
+				$this->_wp_post = get_post($this->ID());
57
+			} else {
58
+				$simulated_db_result = new stdClass();
59
+				foreach ($this->get_model()->field_settings(true) as $field_name => $field_obj) {
60
+					if (
61
+						$this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name()
62
+						=== $wpdb->posts
63
+					) {
64
+						$column = $field_obj->get_table_column();
65
+
66
+						if ($field_obj instanceof EE_Datetime_Field) {
67
+							$value_on_model_obj = $this->get_DateTime_object($field_name);
68
+						} elseif ($field_obj->is_db_only_field()) {
69
+							$value_on_model_obj = $field_obj->get_default_value();
70
+						} else {
71
+							$value_on_model_obj = $this->get_raw($field_name);
72
+						}
73
+						$simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
74
+					}
75
+				}
76
+				$this->_wp_post = new WP_Post($simulated_db_result);
77
+			}
78
+			// and let's make retrieving the EE CPT object easy too
79
+			$classname = get_class($this);
80
+			if (! isset($this->_wp_post->{$classname})) {
81
+				$this->_wp_post->{$classname} = $this;
82
+			}
83
+		}
84
+		return $this->_wp_post;
85
+	}
86
+
87
+	/**
88
+	 * When fetching a new value for a post field that uses the global $post for rendering,
89
+	 * set the global $post temporarily to be this model object; and afterwards restore it
90
+	 *
91
+	 * @param string $fieldname
92
+	 * @param bool   $pretty
93
+	 * @param string $extra_cache_ref
94
+	 * @return mixed
95
+	 */
96
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
97
+	{
98
+		global $post;
99
+
100
+		if (
101
+			$pretty
102
+			&& (
103
+				! (
104
+					$post instanceof WP_Post
105
+					&& $post->ID
106
+				)
107
+				|| (int) $post->ID !== $this->ID()
108
+			)
109
+			&& $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field
110
+		) {
111
+			$old_post = $post;
112
+			$post = $this->wp_post();
113
+			$return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
114
+			$post = $old_post;
115
+		} else {
116
+			$return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
117
+		}
118
+		return $return_value;
119
+	}
120
+
121
+	/**
122
+	 * Adds to the specified event category. If it category doesn't exist, creates it.
123
+	 *
124
+	 * @param string $category_name
125
+	 * @param string $category_description    optional
126
+	 * @param int    $parent_term_taxonomy_id optional
127
+	 * @return EE_Term_Taxonomy
128
+	 */
129
+	public function add_event_category($category_name, $category_description = null, $parent_term_taxonomy_id = null)
130
+	{
131
+		return $this->get_model()->add_event_category(
132
+			$this,
133
+			$category_name,
134
+			$category_description,
135
+			$parent_term_taxonomy_id
136
+		);
137
+	}
138
+
139
+
140
+	/**
141
+	 * Removes the event category by specified name from being related ot this event
142
+	 *
143
+	 * @param string $category_name
144
+	 * @return bool
145
+	 */
146
+	public function remove_event_category($category_name)
147
+	{
148
+		return $this->get_model()->remove_event_category($this, $category_name);
149
+	}
150
+
151
+
152
+	/**
153
+	 * Removes the relation to the specified term taxonomy, and maintains the
154
+	 * data integrity of the term taxonomy provided
155
+	 *
156
+	 * @param EE_Term_Taxonomy $term_taxonomy
157
+	 * @return EE_Base_Class the relation was removed from
158
+	 */
159
+	public function remove_relation_to_term_taxonomy($term_taxonomy)
160
+	{
161
+		if (! $term_taxonomy) {
162
+			EE_Error::add_error(
163
+				sprintf(
164
+					esc_html__(
165
+						"No Term_Taxonomy provided which to remove from model object of type %s and id %d",
166
+						"event_espresso"
167
+					),
168
+					get_class($this),
169
+					$this->ID()
170
+				),
171
+				__FILE__,
172
+				__FUNCTION__,
173
+				__LINE__
174
+			);
175
+			return null;
176
+		}
177
+		$term_taxonomy->set_count($term_taxonomy->count() - 1);
178
+		$term_taxonomy->save();
179
+		return $this->_remove_relation_to($term_taxonomy, 'Term_Taxonomy');
180
+	}
181
+
182
+
183
+	/**
184
+	 * The main purpose of this method is to return the post type for the model object
185
+	 *
186
+	 * @access public
187
+	 * @return string
188
+	 */
189
+	public function post_type()
190
+	{
191
+		return $this->get_model()->post_type();
192
+	}
193
+
194
+
195
+	/**
196
+	 * The main purpose of this method is to return the parent for the model object
197
+	 *
198
+	 * @access public
199
+	 * @return int
200
+	 */
201
+	public function parent()
202
+	{
203
+		return $this->get('parent');
204
+	}
205
+
206
+
207
+	/**
208
+	 * return the _status property
209
+	 *
210
+	 * @return string
211
+	 */
212
+	public function status()
213
+	{
214
+		return $this->get('status');
215
+	}
216
+
217
+
218
+	/**
219
+	 * @param string $status
220
+	 */
221
+	public function set_status($status)
222
+	{
223
+		$this->set('status', $status);
224
+	}
225
+
226
+
227
+	/**
228
+	 * This calls the equivalent model method for retrieving the feature image which in turn is a wrapper for
229
+	 * WordPress' get_the_post_thumbnail() function.
230
+	 *
231
+	 * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
232
+	 * @access protected
233
+	 * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
234
+	 *                           representing width and height in pixels (i.e. array(32,32) ).
235
+	 * @param string|array $attr Optional. Query string or array of attributes.
236
+	 * @return string HTML image element
237
+	 */
238
+	protected function _get_feature_image($size, $attr)
239
+	{
240
+		// first let's see if we already have the _feature_image property set AND if it has a cached element on it FOR the given size
241
+		$attr_key = is_array($attr) ? implode('_', $attr) : $attr;
242
+		$cache_key = is_array($size) ? implode('_', $size) . $attr_key : $size . $attr_key;
243
+		$this->_feature_image[ $cache_key ] = isset($this->_feature_image[ $cache_key ])
244
+			? $this->_feature_image[ $cache_key ] : $this->get_model()->get_feature_image($this->ID(), $size, $attr);
245
+		return $this->_feature_image[ $cache_key ];
246
+	}
247
+
248
+
249
+	/**
250
+	 * See _get_feature_image. Returns the HTML to display a featured image
251
+	 *
252
+	 * @param string       $size
253
+	 * @param string|array $attr
254
+	 * @return string of html
255
+	 */
256
+	public function feature_image($size = 'thumbnail', $attr = '')
257
+	{
258
+		return $this->_get_feature_image($size, $attr);
259
+	}
260
+
261
+
262
+	/**
263
+	 * This uses the wp "wp_get_attachment_image_src()" function to return the feature image for the current class
264
+	 * using the given size params.
265
+	 *
266
+	 * @param  string|array $size can either be a string: 'thumbnail', 'medium', 'large', 'full' OR 2-item array
267
+	 *                            representing width and height in pixels eg. array(32,32).
268
+	 * @return string|boolean          the url of the image or false if not found
269
+	 */
270
+	public function feature_image_url($size = 'thumbnail')
271
+	{
272
+		$attachment = wp_get_attachment_image_src(get_post_thumbnail_id($this->ID()), $size);
273
+		return ! empty($attachment) ? $attachment[0] : false;
274
+	}
275
+
276
+
277
+	/**
278
+	 * This is a method for restoring this_obj using details from the given $revision_id
279
+	 *
280
+	 * @param int   $revision_id       ID of the revision we're getting data from
281
+	 * @param array $related_obj_names if included this will be used to restore for related obj
282
+	 *                                 if not included then we just do restore on the meta.
283
+	 *                                 We will accept an array of related_obj_names for restoration here.
284
+	 * @param array $where_query       You can optionally include an array of key=>value pairs
285
+	 *                                 that allow you to further constrict the relation to being added.
286
+	 *                                 However, keep in mind that the columns (keys) given
287
+	 *                                 must match a column on the JOIN table and currently
288
+	 *                                 only the HABTM models accept these additional conditions.
289
+	 *                                 Also remember that if an exact match isn't found for these extra cols/val pairs,
290
+	 *                                 then a NEW row is created in the join table.
291
+	 *                                 This array is INDEXED by RELATED OBJ NAME (so it corresponds with the obj_names
292
+	 *                                 sent);
293
+	 * @return void
294
+	 */
295
+	public function restore_revision($revision_id, $related_obj_names = array(), $where_query = array())
296
+	{
297
+		// get revision object
298
+		$revision_obj = $this->get_model()->get_one_by_ID($revision_id);
299
+		if ($revision_obj instanceof EE_CPT_Base) {
300
+			// no related_obj_name so we assume we're saving a revision on this object.
301
+			if (empty($related_obj_names)) {
302
+				$fields = $this->get_model()->get_meta_table_fields();
303
+				foreach ($fields as $field) {
304
+					$this->set($field, $revision_obj->get($field));
305
+				}
306
+				$this->save();
307
+			}
308
+			$related_obj_names = (array) $related_obj_names;
309
+			foreach ($related_obj_names as $related_name) {
310
+				// related_obj_name so we're saving a revision on an object related to this object
311
+				// do we have $where_query params for this related object?  If we do then we include that.
312
+				$cols_n_values = isset($where_query[ $related_name ]) ? $where_query[ $related_name ] : array();
313
+				$where_params = ! empty($cols_n_values) ? array($cols_n_values) : array();
314
+				$related_objs = $this->get_many_related($related_name, $where_params);
315
+				$revision_related_objs = $revision_obj->get_many_related($related_name, $where_params);
316
+				// load helper
317
+				// remove related objs from this object that are not in revision
318
+				// array_diff *should* work cause I think objects are indexed by ID?
319
+				$related_to_remove = EEH_Array::object_array_diff($related_objs, $revision_related_objs);
320
+				foreach ($related_to_remove as $rr) {
321
+					$this->_remove_relation_to($rr, $related_name, $cols_n_values);
322
+				}
323
+				// add all related objs attached to revision to this object
324
+				foreach ($revision_related_objs as $r_obj) {
325
+					$this->_add_relation_to($r_obj, $related_name, $cols_n_values);
326
+				}
327
+			}
328
+		}
329
+	}
330
+
331
+
332
+	/**
333
+	 * Wrapper for get_post_meta, http://codex.wordpress.org/Function_Reference/get_post_meta
334
+	 *
335
+	 * @param string  $meta_key
336
+	 * @param boolean $single
337
+	 * @return mixed <ul><li>If only $id is set it will return all meta values in an associative array.</li>
338
+	 * <li>If $single is set to false, or left blank, the function returns an array containing all values of the
339
+	 * specified key.</li>
340
+	 * <li>If $single is set to true, the function returns the first value of the specified key (not in an
341
+	 * array</li></ul>
342
+	 */
343
+	public function get_post_meta($meta_key = null, $single = false)
344
+	{
345
+		return get_post_meta($this->ID(), $meta_key, $single);
346
+	}
347
+
348
+
349
+	/**
350
+	 * Wrapper for update_post_meta, http://codex.wordpress.org/Function_Reference/update_post_meta
351
+	 *
352
+	 * @param string $meta_key
353
+	 * @param mixed  $meta_value
354
+	 * @param mixed  $prev_value
355
+	 * @return mixed Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure.
356
+	 *               NOTE: If the meta_value passed to this function is the same as the value that is already in the
357
+	 *               database, this function returns false.
358
+	 */
359
+	public function update_post_meta($meta_key, $meta_value, $prev_value = null)
360
+	{
361
+		if (! $this->ID()) {
362
+			$this->save();
363
+		}
364
+		return update_post_meta($this->ID(), $meta_key, $meta_value, $prev_value);
365
+	}
366
+
367
+
368
+	/**
369
+	 * Wrapper for add_post_meta, http://codex.wordpress.org/Function_Reference/add_post_meta
370
+	 *
371
+	 * @param mixed $meta_key
372
+	 * @param mixed $meta_value
373
+	 * @param bool  $unique . If postmeta for this $meta_key already exists, whether to add an additional item or not
374
+	 * @return boolean Boolean true, except if the $unique argument was set to true and a custom field with the given
375
+	 *                 key already exists, in which case false is returned.
376
+	 */
377
+	public function add_post_meta($meta_key, $meta_value, $unique = false)
378
+	{
379
+		if ($this->ID()) {
380
+			$this->save();
381
+		}
382
+		return add_post_meta($this->ID(), $meta_key, $meta_value, $unique);
383
+	}
384
+
385
+
386
+	/**
387
+	 * Wrapper for delete_post_meta, http://codex.wordpress.org/Function_Reference/delete_post_meta
388
+	 *
389
+	 * @param mixed $meta_key
390
+	 * @param mixed $meta_value
391
+	 * @return boolean False for failure. True for success.
392
+	 */
393
+	public function delete_post_meta($meta_key, $meta_value = '')
394
+	{
395
+		if (! $this->ID()) {
396
+			// there are obviously no postmetas for this if it's not saved
397
+			// so let's just report this as a success
398
+			return true;
399
+		}
400
+		return delete_post_meta($this->ID(), $meta_key, $meta_value);
401
+	}
402
+
403
+
404
+	/**
405
+	 * Gets the URL for viewing this event on the front-end
406
+	 *
407
+	 * @return string
408
+	 */
409
+	public function get_permalink()
410
+	{
411
+		return get_permalink($this->ID());
412
+	}
413
+
414
+
415
+	/**
416
+	 * Gets all the term-taxonomies for this CPT
417
+	 *
418
+	 * @param array $query_params
419
+	 * @return EE_Term_Taxonomy
420
+	 */
421
+	public function term_taxonomies($query_params = array())
422
+	{
423
+		return $this->get_many_related('Term_Taxonomy', $query_params);
424
+	}
425
+
426
+
427
+	/**
428
+	 * @return mixed
429
+	 */
430
+	public function get_custom_post_statuses()
431
+	{
432
+		return $this->get_model()->get_custom_post_statuses();
433
+	}
434
+
435
+
436
+	/**
437
+	 * @return mixed
438
+	 */
439
+	public function get_all_post_statuses()
440
+	{
441
+		return $this->get_model()->get_status_array();
442
+	}
443
+
444
+
445
+	/**
446
+	 * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
447
+	 *
448
+	 * @return array
449
+	 */
450
+	public function __sleep()
451
+	{
452
+		$properties_to_serialize = parent::__sleep();
453
+		$properties_to_serialize = array_diff($properties_to_serialize, array('_wp_post'));
454
+		return $properties_to_serialize;
455
+	}
456 456
 }
Please login to merge, or discard this patch.
caffeinated/core/domain/entities/routing/handlers/admin/PueRequests.php 1 patch
Indentation   +110 added lines, -110 removed lines patch added patch discarded remove patch
@@ -20,125 +20,125 @@
 block discarded – undo
20 20
  */
21 21
 class PueRequests extends Route
22 22
 {
23
-    /**
24
-     * @var   bool
25
-     * @since $VID:$
26
-     */
27
-    private $load_pue = true;
23
+	/**
24
+	 * @var   bool
25
+	 * @since $VID:$
26
+	 */
27
+	private $load_pue = true;
28 28
 
29 29
 
30
-    /**
31
-     * returns true if the current request matches this route
32
-     *
33
-     * @return bool
34
-     * @since   $VID:$
35
-     */
36
-    public function matchesCurrentRequest(): bool
37
-    {
38
-        // route may match, but PUE loading is still conditional based on this filter
39
-        $this->load_pue = apply_filters('FHEE__EE_System__brew_espresso__load_pue', true);
40
-        return $this->request->isAdmin() || $this->request->isAdminAjax() || $this->request->isActivation();
41
-    }
30
+	/**
31
+	 * returns true if the current request matches this route
32
+	 *
33
+	 * @return bool
34
+	 * @since   $VID:$
35
+	 */
36
+	public function matchesCurrentRequest(): bool
37
+	{
38
+		// route may match, but PUE loading is still conditional based on this filter
39
+		$this->load_pue = apply_filters('FHEE__EE_System__brew_espresso__load_pue', true);
40
+		return $this->request->isAdmin() || $this->request->isAdminAjax() || $this->request->isActivation();
41
+	}
42 42
 
43 43
 
44
-    /**
45
-     * @since $VID:$
46
-     */
47
-    protected function registerDependencies()
48
-    {
49
-        if ($this->load_pue) {
50
-            $this->dependency_map->registerDependencies(
51
-                'EventEspresso\caffeinated\core\services\licensing\LicenseService',
52
-                [
53
-                    'EventEspresso\caffeinated\core\domain\services\pue\Stats'  => EE_Dependency_Map::load_from_cache,
54
-                    'EventEspresso\caffeinated\core\domain\services\pue\Config' => EE_Dependency_Map::load_from_cache,
55
-                ]
56
-            );
57
-            $this->dependency_map->registerDependencies(
58
-                'EventEspresso\caffeinated\core\domain\services\pue\Stats',
59
-                [
60
-                    'EventEspresso\caffeinated\core\domain\services\pue\Config'        => EE_Dependency_Map::load_from_cache,
61
-                    'EE_Maintenance_Mode'                                              => EE_Dependency_Map::load_from_cache,
62
-                    'EventEspresso\caffeinated\core\domain\services\pue\StatsGatherer' => EE_Dependency_Map::load_from_cache,
63
-                ]
64
-            );
65
-            $this->dependency_map->registerDependencies(
66
-                'EventEspresso\caffeinated\core\domain\services\pue\Config',
67
-                [
68
-                    'EE_Network_Config' => EE_Dependency_Map::load_from_cache,
69
-                    'EE_Config'         => EE_Dependency_Map::load_from_cache,
70
-                ]
71
-            );
72
-            $this->dependency_map->registerDependencies(
73
-                'EventEspresso\caffeinated\core\domain\services\pue\StatsGatherer',
74
-                [
75
-                    'EEM_Payment_Method' => EE_Dependency_Map::load_from_cache,
76
-                    'EEM_Event'          => EE_Dependency_Map::load_from_cache,
77
-                    'EEM_Datetime'       => EE_Dependency_Map::load_from_cache,
78
-                    'EEM_Ticket'         => EE_Dependency_Map::load_from_cache,
79
-                    'EEM_Registration'   => EE_Dependency_Map::load_from_cache,
80
-                    'EEM_Transaction'    => EE_Dependency_Map::load_from_cache,
81
-                    'EE_Config'          => EE_Dependency_Map::load_from_cache,
82
-                ]
83
-            );
84
-            $this->dependency_map->registerDependencies(
85
-                'EventEspresso\caffeinated\core\services\licensing\UserExperienceForm',
86
-                [
87
-                    'EE_Core_Config'         => EE_Dependency_Map::load_from_cache,
88
-                    'EE_Network_Core_Config' => EE_Dependency_Map::load_from_cache,
89
-                ]
90
-            );
91
-        }
92
-    }
44
+	/**
45
+	 * @since $VID:$
46
+	 */
47
+	protected function registerDependencies()
48
+	{
49
+		if ($this->load_pue) {
50
+			$this->dependency_map->registerDependencies(
51
+				'EventEspresso\caffeinated\core\services\licensing\LicenseService',
52
+				[
53
+					'EventEspresso\caffeinated\core\domain\services\pue\Stats'  => EE_Dependency_Map::load_from_cache,
54
+					'EventEspresso\caffeinated\core\domain\services\pue\Config' => EE_Dependency_Map::load_from_cache,
55
+				]
56
+			);
57
+			$this->dependency_map->registerDependencies(
58
+				'EventEspresso\caffeinated\core\domain\services\pue\Stats',
59
+				[
60
+					'EventEspresso\caffeinated\core\domain\services\pue\Config'        => EE_Dependency_Map::load_from_cache,
61
+					'EE_Maintenance_Mode'                                              => EE_Dependency_Map::load_from_cache,
62
+					'EventEspresso\caffeinated\core\domain\services\pue\StatsGatherer' => EE_Dependency_Map::load_from_cache,
63
+				]
64
+			);
65
+			$this->dependency_map->registerDependencies(
66
+				'EventEspresso\caffeinated\core\domain\services\pue\Config',
67
+				[
68
+					'EE_Network_Config' => EE_Dependency_Map::load_from_cache,
69
+					'EE_Config'         => EE_Dependency_Map::load_from_cache,
70
+				]
71
+			);
72
+			$this->dependency_map->registerDependencies(
73
+				'EventEspresso\caffeinated\core\domain\services\pue\StatsGatherer',
74
+				[
75
+					'EEM_Payment_Method' => EE_Dependency_Map::load_from_cache,
76
+					'EEM_Event'          => EE_Dependency_Map::load_from_cache,
77
+					'EEM_Datetime'       => EE_Dependency_Map::load_from_cache,
78
+					'EEM_Ticket'         => EE_Dependency_Map::load_from_cache,
79
+					'EEM_Registration'   => EE_Dependency_Map::load_from_cache,
80
+					'EEM_Transaction'    => EE_Dependency_Map::load_from_cache,
81
+					'EE_Config'          => EE_Dependency_Map::load_from_cache,
82
+				]
83
+			);
84
+			$this->dependency_map->registerDependencies(
85
+				'EventEspresso\caffeinated\core\services\licensing\UserExperienceForm',
86
+				[
87
+					'EE_Core_Config'         => EE_Dependency_Map::load_from_cache,
88
+					'EE_Network_Core_Config' => EE_Dependency_Map::load_from_cache,
89
+				]
90
+			);
91
+		}
92
+	}
93 93
 
94 94
 
95
-    /**
96
-     * implements logic required to run during request
97
-     *
98
-     * @return bool
99
-     * @since   $VID:$
100
-     */
101
-    protected function requestHandler(): bool
102
-    {
103
-        add_filter(
104
-            'FHEE__EE_Register_Addon__register',
105
-            [RegisterAddonPUE::class, 'registerPUE'],
106
-            10,
107
-            4
108
-        );
109
-        add_action(
110
-            'AHEE__EE_Register_Addon___load_and_init_addon_class',
111
-            [RegisterAddonPUE::class, 'setAddonPueSlug'],
112
-            10,
113
-            2
114
-        );
115
-        if ($this->load_pue) {
116
-            add_action('AHEE__EE_System__brew_espresso__complete', [$this, 'loadLicenseService']);
117
-            add_filter(
118
-                'FHEE__EventEspresso_admin_pages_general_settings_OrganizationSettings__generate__form',
119
-                [$this, 'loadUserExperienceForm']
120
-            );
121
-        }
95
+	/**
96
+	 * implements logic required to run during request
97
+	 *
98
+	 * @return bool
99
+	 * @since   $VID:$
100
+	 */
101
+	protected function requestHandler(): bool
102
+	{
103
+		add_filter(
104
+			'FHEE__EE_Register_Addon__register',
105
+			[RegisterAddonPUE::class, 'registerPUE'],
106
+			10,
107
+			4
108
+		);
109
+		add_action(
110
+			'AHEE__EE_Register_Addon___load_and_init_addon_class',
111
+			[RegisterAddonPUE::class, 'setAddonPueSlug'],
112
+			10,
113
+			2
114
+		);
115
+		if ($this->load_pue) {
116
+			add_action('AHEE__EE_System__brew_espresso__complete', [$this, 'loadLicenseService']);
117
+			add_filter(
118
+				'FHEE__EventEspresso_admin_pages_general_settings_OrganizationSettings__generate__form',
119
+				[$this, 'loadUserExperienceForm']
120
+			);
121
+		}
122 122
 
123
-        return true;
124
-    }
123
+		return true;
124
+	}
125 125
 
126 126
 
127
-    public function loadLicenseService()
128
-    {
129
-        /** @var LicenseService $license_service */
130
-        $license_service = $this->loader->getShared(LicenseService::class);
131
-        $license_service->loadPueClient();
132
-    }
127
+	public function loadLicenseService()
128
+	{
129
+		/** @var LicenseService $license_service */
130
+		$license_service = $this->loader->getShared(LicenseService::class);
131
+		$license_service->loadPueClient();
132
+	}
133 133
 
134 134
 
135
-    /**
136
-     * @throws EE_Error
137
-     */
138
-    public function loadUserExperienceForm(EE_Form_Section_Proper $org_settings_form): EE_Form_Section_Proper
139
-    {
140
-        /** @var UserExperienceForm $uxip_form */
141
-        $uxip_form = $this->loader->getShared(UserExperienceForm::class);
142
-        return $uxip_form->uxipFormSections($org_settings_form);
143
-    }
135
+	/**
136
+	 * @throws EE_Error
137
+	 */
138
+	public function loadUserExperienceForm(EE_Form_Section_Proper $org_settings_form): EE_Form_Section_Proper
139
+	{
140
+		/** @var UserExperienceForm $uxip_form */
141
+		$uxip_form = $this->loader->getShared(UserExperienceForm::class);
142
+		return $uxip_form->uxipFormSections($org_settings_form);
143
+	}
144 144
 }
Please login to merge, or discard this patch.