Completed
Branch fix-dummy-related-question-qst... (e5efcf)
by
unknown
07:49 queued 03:45
created
core/db_classes/EE_Datetime.class.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
             $date_or_time,
534 534
             $echo
535 535
         );
536
-        if (! $echo) {
536
+        if ( ! $echo) {
537 537
             return $dtt;
538 538
         }
539 539
         return '';
@@ -635,7 +635,7 @@  discard block
 block discarded – undo
635 635
             ' ',
636 636
             $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
637 637
         );
638
-        return $start !== $end ? $start . $conjunction . $end : $start;
638
+        return $start !== $end ? $start.$conjunction.$end : $start;
639 639
     }
640 640
 
641 641
 
@@ -743,7 +743,7 @@  discard block
 block discarded – undo
743 743
             ' ',
744 744
             $this->get_i18n_datetime('DTT_EVT_end', $tm_format)
745 745
         );
746
-        return $start !== $end ? $start . $conjunction . $end : $start;
746
+        return $start !== $end ? $start.$conjunction.$end : $start;
747 747
     }
748 748
 
749 749
 
@@ -788,7 +788,7 @@  discard block
 block discarded – undo
788 788
     ) {
789 789
         $dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
790 790
         $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
791
-        $full_format = $dt_format . $separator . $tm_format;
791
+        $full_format = $dt_format.$separator.$tm_format;
792 792
         // the range output depends on various conditions
793 793
         switch (true) {
794 794
             // start date timestamp and end date timestamp are the same.
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
         // tickets remaining available for purchase
1030 1030
         // no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1031 1031
         $dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1032
-        if (! $consider_tickets) {
1032
+        if ( ! $consider_tickets) {
1033 1033
             return $dtt_remaining;
1034 1034
         }
1035 1035
         $tickets_remaining = $this->tickets_remaining();
@@ -1053,7 +1053,7 @@  discard block
 block discarded – undo
1053 1053
     {
1054 1054
         $sum = 0;
1055 1055
         $tickets = $this->tickets($query_params);
1056
-        if (! empty($tickets)) {
1056
+        if ( ! empty($tickets)) {
1057 1057
             foreach ($tickets as $ticket) {
1058 1058
                 if ($ticket instanceof EE_Ticket) {
1059 1059
                     // get the actual amount of tickets that can be sold
@@ -1204,7 +1204,7 @@  discard block
 block discarded – undo
1204 1204
     {
1205 1205
         if ($use_dtt_name) {
1206 1206
             $dtt_name = $this->name();
1207
-            if (! empty($dtt_name)) {
1207
+            if ( ! empty($dtt_name)) {
1208 1208
                 return $dtt_name;
1209 1209
             }
1210 1210
         }
@@ -1212,14 +1212,14 @@  discard block
 block discarded – undo
1212 1212
         if (
1213 1213
             date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1214 1214
         ) {
1215
-            $display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
+            $display_date = $this->start_date('M j\, Y g:i a').' - '.$this->end_date('M j\, Y g:i a');
1216 1216
             // next condition is if its the same month but different day
1217 1217
         } else {
1218 1218
             if (
1219 1219
                 date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1220 1220
                 && date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1221 1221
             ) {
1222
-                $display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1222
+                $display_date = $this->start_date('M j\, g:i a').' - '.$this->end_date('M j\, g:i a Y');
1223 1223
             } else {
1224 1224
                 $display_date = $this->start_date('F j\, Y')
1225 1225
                                 . ' @ '
Please login to merge, or discard this patch.
Indentation   +1404 added lines, -1404 removed lines patch added patch discarded remove patch
@@ -12,1412 +12,1412 @@
 block discarded – undo
12 12
  */
13 13
 class EE_Datetime extends EE_Soft_Delete_Base_Class
14 14
 {
15
-    /**
16
-     * constant used by get_active_status, indicates datetime has no more available spaces
17
-     */
18
-    const sold_out = 'DTS';
19
-
20
-    /**
21
-     * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
22
-     */
23
-    const active = 'DTA';
24
-
25
-    /**
26
-     * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
27
-     * expired
28
-     */
29
-    const upcoming = 'DTU';
30
-
31
-    /**
32
-     * Datetime is postponed
33
-     */
34
-    const postponed = 'DTP';
35
-
36
-    /**
37
-     * Datetime is cancelled
38
-     */
39
-    const cancelled = 'DTC';
40
-
41
-    /**
42
-     * constant used by get_active_status, indicates datetime has expired (event is over)
43
-     */
44
-    const expired = 'DTE';
45
-
46
-    /**
47
-     * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
48
-     */
49
-    const inactive = 'DTI';
50
-
51
-
52
-    /**
53
-     * @param array  $props_n_values    incoming values
54
-     * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
55
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
56
-     *                                  and the second value is the time format
57
-     * @return EE_Datetime
58
-     * @throws ReflectionException
59
-     * @throws InvalidArgumentException
60
-     * @throws InvalidInterfaceException
61
-     * @throws InvalidDataTypeException
62
-     * @throws EE_Error
63
-     */
64
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
65
-    {
66
-        $has_object = parent::_check_for_object(
67
-            $props_n_values,
68
-            __CLASS__,
69
-            $timezone,
70
-            $date_formats
71
-        );
72
-        return $has_object
73
-            ? $has_object
74
-            : new self($props_n_values, false, $timezone, $date_formats);
75
-    }
76
-
77
-
78
-    /**
79
-     * @param array  $props_n_values  incoming values from the database
80
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
-     *                                the website will be used.
82
-     * @return EE_Datetime
83
-     * @throws ReflectionException
84
-     * @throws InvalidArgumentException
85
-     * @throws InvalidInterfaceException
86
-     * @throws InvalidDataTypeException
87
-     * @throws EE_Error
88
-     */
89
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
90
-    {
91
-        return new self($props_n_values, true, $timezone);
92
-    }
93
-
94
-
95
-    /**
96
-     * @param $name
97
-     * @throws ReflectionException
98
-     * @throws InvalidArgumentException
99
-     * @throws InvalidInterfaceException
100
-     * @throws InvalidDataTypeException
101
-     * @throws EE_Error
102
-     */
103
-    public function set_name($name)
104
-    {
105
-        $this->set('DTT_name', $name);
106
-    }
107
-
108
-
109
-    /**
110
-     * @param $description
111
-     * @throws ReflectionException
112
-     * @throws InvalidArgumentException
113
-     * @throws InvalidInterfaceException
114
-     * @throws InvalidDataTypeException
115
-     * @throws EE_Error
116
-     */
117
-    public function set_description($description)
118
-    {
119
-        $this->set('DTT_description', $description);
120
-    }
121
-
122
-
123
-    /**
124
-     * Set event start date
125
-     * set the start date for an event
126
-     *
127
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
128
-     * @throws ReflectionException
129
-     * @throws InvalidArgumentException
130
-     * @throws InvalidInterfaceException
131
-     * @throws InvalidDataTypeException
132
-     * @throws EE_Error
133
-     */
134
-    public function set_start_date($date)
135
-    {
136
-        $this->_set_date_for($date, 'DTT_EVT_start');
137
-    }
138
-
139
-
140
-    /**
141
-     * Set event start time
142
-     * set the start time for an event
143
-     *
144
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
145
-     * @throws ReflectionException
146
-     * @throws InvalidArgumentException
147
-     * @throws InvalidInterfaceException
148
-     * @throws InvalidDataTypeException
149
-     * @throws EE_Error
150
-     */
151
-    public function set_start_time($time)
152
-    {
153
-        $this->_set_time_for($time, 'DTT_EVT_start');
154
-    }
155
-
156
-
157
-    /**
158
-     * Set event end date
159
-     * set the end date for an event
160
-     *
161
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
162
-     * @throws ReflectionException
163
-     * @throws InvalidArgumentException
164
-     * @throws InvalidInterfaceException
165
-     * @throws InvalidDataTypeException
166
-     * @throws EE_Error
167
-     */
168
-    public function set_end_date($date)
169
-    {
170
-        $this->_set_date_for($date, 'DTT_EVT_end');
171
-    }
172
-
173
-
174
-    /**
175
-     * Set event end time
176
-     * set the end time for an event
177
-     *
178
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
179
-     * @throws ReflectionException
180
-     * @throws InvalidArgumentException
181
-     * @throws InvalidInterfaceException
182
-     * @throws InvalidDataTypeException
183
-     * @throws EE_Error
184
-     */
185
-    public function set_end_time($time)
186
-    {
187
-        $this->_set_time_for($time, 'DTT_EVT_end');
188
-    }
189
-
190
-
191
-    /**
192
-     * Set registration limit
193
-     * set the maximum number of attendees that can be registered for this datetime slot
194
-     *
195
-     * @param int $reg_limit
196
-     * @throws ReflectionException
197
-     * @throws InvalidArgumentException
198
-     * @throws InvalidInterfaceException
199
-     * @throws InvalidDataTypeException
200
-     * @throws EE_Error
201
-     */
202
-    public function set_reg_limit($reg_limit)
203
-    {
204
-        $this->set('DTT_reg_limit', $reg_limit);
205
-    }
206
-
207
-
208
-    /**
209
-     * get the number of tickets sold for this datetime slot
210
-     *
211
-     * @return mixed int on success, FALSE on fail
212
-     * @throws ReflectionException
213
-     * @throws InvalidArgumentException
214
-     * @throws InvalidInterfaceException
215
-     * @throws InvalidDataTypeException
216
-     * @throws EE_Error
217
-     */
218
-    public function sold()
219
-    {
220
-        return $this->get_raw('DTT_sold');
221
-    }
222
-
223
-
224
-    /**
225
-     * @param int $sold
226
-     * @throws ReflectionException
227
-     * @throws InvalidArgumentException
228
-     * @throws InvalidInterfaceException
229
-     * @throws InvalidDataTypeException
230
-     * @throws EE_Error
231
-     */
232
-    public function set_sold($sold)
233
-    {
234
-        // sold can not go below zero
235
-        $sold = max(0, $sold);
236
-        $this->set('DTT_sold', $sold);
237
-    }
238
-
239
-
240
-    /**
241
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
242
-     * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
243
-     *
244
-     * @param int $qty
245
-     * @param boolean $also_decrease_reserved
246
-     * @return boolean indicating success
247
-     * @throws ReflectionException
248
-     * @throws InvalidArgumentException
249
-     * @throws InvalidInterfaceException
250
-     * @throws InvalidDataTypeException
251
-     * @throws EE_Error
252
-     */
253
-    public function increaseSold($qty = 1, $also_decrease_reserved = true)
254
-    {
255
-        $qty = absint($qty);
256
-        if ($also_decrease_reserved) {
257
-            $success = $this->adjustNumericFieldsInDb(
258
-                [
259
-                    'DTT_reserved' => $qty * -1,
260
-                    'DTT_sold' => $qty
261
-                ]
262
-            );
263
-        } else {
264
-            $success = $this->adjustNumericFieldsInDb(
265
-                [
266
-                    'DTT_sold' => $qty
267
-                ]
268
-            );
269
-        }
270
-
271
-        do_action(
272
-            'AHEE__EE_Datetime__increase_sold',
273
-            $this,
274
-            $qty,
275
-            $this->sold(),
276
-            $success
277
-        );
278
-        return $success;
279
-    }
280
-
281
-
282
-    /**
283
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
284
-     * to save afterwards.)
285
-     *
286
-     * @param int $qty
287
-     * @return boolean indicating success
288
-     * @throws ReflectionException
289
-     * @throws InvalidArgumentException
290
-     * @throws InvalidInterfaceException
291
-     * @throws InvalidDataTypeException
292
-     * @throws EE_Error
293
-     */
294
-    public function decreaseSold($qty = 1)
295
-    {
296
-        $qty = absint($qty);
297
-        $success = $this->adjustNumericFieldsInDb(
298
-            [
299
-                'DTT_sold' => $qty * -1
300
-            ]
301
-        );
302
-        do_action(
303
-            'AHEE__EE_Datetime__decrease_sold',
304
-            $this,
305
-            $qty,
306
-            $this->sold(),
307
-            $success
308
-        );
309
-        return $success;
310
-    }
311
-
312
-
313
-    /**
314
-     * Gets qty of reserved tickets for this datetime
315
-     *
316
-     * @return int
317
-     * @throws ReflectionException
318
-     * @throws InvalidArgumentException
319
-     * @throws InvalidInterfaceException
320
-     * @throws InvalidDataTypeException
321
-     * @throws EE_Error
322
-     */
323
-    public function reserved()
324
-    {
325
-        return $this->get_raw('DTT_reserved');
326
-    }
327
-
328
-
329
-    /**
330
-     * Sets qty of reserved tickets for this datetime
331
-     *
332
-     * @param int $reserved
333
-     * @throws ReflectionException
334
-     * @throws InvalidArgumentException
335
-     * @throws InvalidInterfaceException
336
-     * @throws InvalidDataTypeException
337
-     * @throws EE_Error
338
-     */
339
-    public function set_reserved($reserved)
340
-    {
341
-        // reserved can not go below zero
342
-        $reserved = max(0, (int) $reserved);
343
-        $this->set('DTT_reserved', $reserved);
344
-    }
345
-
346
-
347
-    /**
348
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
349
-     *
350
-     * @param int $qty
351
-     * @return boolean indicating success
352
-     * @throws ReflectionException
353
-     * @throws InvalidArgumentException
354
-     * @throws InvalidInterfaceException
355
-     * @throws InvalidDataTypeException
356
-     * @throws EE_Error
357
-     */
358
-    public function increaseReserved($qty = 1)
359
-    {
360
-        $qty = absint($qty);
361
-        $success = $this->incrementFieldConditionallyInDb(
362
-            'DTT_reserved',
363
-            'DTT_sold',
364
-            'DTT_reg_limit',
365
-            $qty
366
-        );
367
-        do_action(
368
-            'AHEE__EE_Datetime__increase_reserved',
369
-            $this,
370
-            $qty,
371
-            $this->reserved(),
372
-            $success
373
-        );
374
-        return $success;
375
-    }
376
-
377
-
378
-    /**
379
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
380
-     *
381
-     * @param int $qty
382
-     * @return boolean indicating success
383
-     * @throws ReflectionException
384
-     * @throws InvalidArgumentException
385
-     * @throws InvalidInterfaceException
386
-     * @throws InvalidDataTypeException
387
-     * @throws EE_Error
388
-     */
389
-    public function decreaseReserved($qty = 1)
390
-    {
391
-        $qty = absint($qty);
392
-        $success = $this->adjustNumericFieldsInDb(
393
-            [
394
-                'DTT_reserved' => $qty * -1
395
-            ]
396
-        );
397
-        do_action(
398
-            'AHEE__EE_Datetime__decrease_reserved',
399
-            $this,
400
-            $qty,
401
-            $this->reserved(),
402
-            $success
403
-        );
404
-        return $success;
405
-    }
406
-
407
-
408
-    /**
409
-     * total sold and reserved tickets
410
-     *
411
-     * @return int
412
-     * @throws ReflectionException
413
-     * @throws InvalidArgumentException
414
-     * @throws InvalidInterfaceException
415
-     * @throws InvalidDataTypeException
416
-     * @throws EE_Error
417
-     */
418
-    public function sold_and_reserved()
419
-    {
420
-        return $this->sold() + $this->reserved();
421
-    }
422
-
423
-
424
-    /**
425
-     * returns the datetime name
426
-     *
427
-     * @return string
428
-     * @throws ReflectionException
429
-     * @throws InvalidArgumentException
430
-     * @throws InvalidInterfaceException
431
-     * @throws InvalidDataTypeException
432
-     * @throws EE_Error
433
-     */
434
-    public function name()
435
-    {
436
-        return $this->get('DTT_name');
437
-    }
438
-
439
-
440
-    /**
441
-     * returns the datetime description
442
-     *
443
-     * @return string
444
-     * @throws ReflectionException
445
-     * @throws InvalidArgumentException
446
-     * @throws InvalidInterfaceException
447
-     * @throws InvalidDataTypeException
448
-     * @throws EE_Error
449
-     */
450
-    public function description()
451
-    {
452
-        return $this->get('DTT_description');
453
-    }
454
-
455
-
456
-    /**
457
-     * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
458
-     *
459
-     * @return boolean  TRUE if is primary, FALSE if not.
460
-     * @throws ReflectionException
461
-     * @throws InvalidArgumentException
462
-     * @throws InvalidInterfaceException
463
-     * @throws InvalidDataTypeException
464
-     * @throws EE_Error
465
-     */
466
-    public function is_primary()
467
-    {
468
-        return $this->get('DTT_is_primary');
469
-    }
470
-
471
-
472
-    /**
473
-     * This helper simply returns the order for the datetime
474
-     *
475
-     * @return int  The order of the datetime for this event.
476
-     * @throws ReflectionException
477
-     * @throws InvalidArgumentException
478
-     * @throws InvalidInterfaceException
479
-     * @throws InvalidDataTypeException
480
-     * @throws EE_Error
481
-     */
482
-    public function order()
483
-    {
484
-        return $this->get('DTT_order');
485
-    }
486
-
487
-
488
-    /**
489
-     * This helper simply returns the parent id for the datetime
490
-     *
491
-     * @return int
492
-     * @throws ReflectionException
493
-     * @throws InvalidArgumentException
494
-     * @throws InvalidInterfaceException
495
-     * @throws InvalidDataTypeException
496
-     * @throws EE_Error
497
-     */
498
-    public function parent()
499
-    {
500
-        return $this->get('DTT_parent');
501
-    }
502
-
503
-
504
-    /**
505
-     * show date and/or time
506
-     *
507
-     * @param string $date_or_time    whether to display a date or time or both
508
-     * @param string $start_or_end    whether to display start or end datetimes
509
-     * @param string $dt_frmt
510
-     * @param string $tm_frmt
511
-     * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
512
-     *                                otherwise we use the standard formats)
513
-     * @return string|bool  string on success, FALSE on fail
514
-     * @throws ReflectionException
515
-     * @throws InvalidArgumentException
516
-     * @throws InvalidInterfaceException
517
-     * @throws InvalidDataTypeException
518
-     * @throws EE_Error
519
-     */
520
-    private function _show_datetime(
521
-        $date_or_time = null,
522
-        $start_or_end = 'start',
523
-        $dt_frmt = '',
524
-        $tm_frmt = '',
525
-        $echo = false
526
-    ) {
527
-        $field_name = "DTT_EVT_{$start_or_end}";
528
-        $dtt = $this->_get_datetime(
529
-            $field_name,
530
-            $dt_frmt,
531
-            $tm_frmt,
532
-            $date_or_time,
533
-            $echo
534
-        );
535
-        if (! $echo) {
536
-            return $dtt;
537
-        }
538
-        return '';
539
-    }
540
-
541
-
542
-    /**
543
-     * get event start date.  Provide either the date format, or NULL to re-use the
544
-     * last-used format, or '' to use the default date format
545
-     *
546
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
547
-     * @return mixed            string on success, FALSE on fail
548
-     * @throws ReflectionException
549
-     * @throws InvalidArgumentException
550
-     * @throws InvalidInterfaceException
551
-     * @throws InvalidDataTypeException
552
-     * @throws EE_Error
553
-     */
554
-    public function start_date($dt_frmt = '')
555
-    {
556
-        return $this->_show_datetime('D', 'start', $dt_frmt);
557
-    }
558
-
559
-
560
-    /**
561
-     * Echoes start_date()
562
-     *
563
-     * @param string $dt_frmt
564
-     * @throws ReflectionException
565
-     * @throws InvalidArgumentException
566
-     * @throws InvalidInterfaceException
567
-     * @throws InvalidDataTypeException
568
-     * @throws EE_Error
569
-     */
570
-    public function e_start_date($dt_frmt = '')
571
-    {
572
-        $this->_show_datetime('D', 'start', $dt_frmt, null, true);
573
-    }
574
-
575
-
576
-    /**
577
-     * get end date. Provide either the date format, or NULL to re-use the
578
-     * last-used format, or '' to use the default date format
579
-     *
580
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
581
-     * @return mixed            string on success, FALSE on fail
582
-     * @throws ReflectionException
583
-     * @throws InvalidArgumentException
584
-     * @throws InvalidInterfaceException
585
-     * @throws InvalidDataTypeException
586
-     * @throws EE_Error
587
-     */
588
-    public function end_date($dt_frmt = '')
589
-    {
590
-        return $this->_show_datetime('D', 'end', $dt_frmt);
591
-    }
592
-
593
-
594
-    /**
595
-     * Echoes the end date. See end_date()
596
-     *
597
-     * @param string $dt_frmt
598
-     * @throws ReflectionException
599
-     * @throws InvalidArgumentException
600
-     * @throws InvalidInterfaceException
601
-     * @throws InvalidDataTypeException
602
-     * @throws EE_Error
603
-     */
604
-    public function e_end_date($dt_frmt = '')
605
-    {
606
-        $this->_show_datetime('D', 'end', $dt_frmt, null, true);
607
-    }
608
-
609
-
610
-    /**
611
-     * get date_range - meaning the start AND end date
612
-     *
613
-     * @access public
614
-     * @param string $dt_frmt     string representation of date format defaults to WP settings
615
-     * @param string $conjunction conjunction junction what's your function ?
616
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
617
-     * @return mixed              string on success, FALSE on fail
618
-     * @throws ReflectionException
619
-     * @throws InvalidArgumentException
620
-     * @throws InvalidInterfaceException
621
-     * @throws InvalidDataTypeException
622
-     * @throws EE_Error
623
-     */
624
-    public function date_range($dt_frmt = '', $conjunction = ' - ')
625
-    {
626
-        $dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
627
-        $start = str_replace(
628
-            ' ',
629
-            ' ',
630
-            $this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
631
-        );
632
-        $end = str_replace(
633
-            ' ',
634
-            ' ',
635
-            $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
636
-        );
637
-        return $start !== $end ? $start . $conjunction . $end : $start;
638
-    }
639
-
640
-
641
-    /**
642
-     * @param string $dt_frmt
643
-     * @param string $conjunction
644
-     * @throws ReflectionException
645
-     * @throws InvalidArgumentException
646
-     * @throws InvalidInterfaceException
647
-     * @throws InvalidDataTypeException
648
-     * @throws EE_Error
649
-     */
650
-    public function e_date_range($dt_frmt = '', $conjunction = ' - ')
651
-    {
652
-        echo esc_html($this->date_range($dt_frmt, $conjunction));
653
-    }
654
-
655
-
656
-    /**
657
-     * get start time
658
-     *
659
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
660
-     * @return mixed        string on success, FALSE on fail
661
-     * @throws ReflectionException
662
-     * @throws InvalidArgumentException
663
-     * @throws InvalidInterfaceException
664
-     * @throws InvalidDataTypeException
665
-     * @throws EE_Error
666
-     */
667
-    public function start_time($tm_format = '')
668
-    {
669
-        return $this->_show_datetime('T', 'start', null, $tm_format);
670
-    }
671
-
672
-
673
-    /**
674
-     * @param string $tm_format
675
-     * @throws ReflectionException
676
-     * @throws InvalidArgumentException
677
-     * @throws InvalidInterfaceException
678
-     * @throws InvalidDataTypeException
679
-     * @throws EE_Error
680
-     */
681
-    public function e_start_time($tm_format = '')
682
-    {
683
-        $this->_show_datetime('T', 'start', null, $tm_format, true);
684
-    }
685
-
686
-
687
-    /**
688
-     * get end time
689
-     *
690
-     * @param string $tm_format string representation of time format defaults to 'g:i a'
691
-     * @return mixed                string on success, FALSE on fail
692
-     * @throws ReflectionException
693
-     * @throws InvalidArgumentException
694
-     * @throws InvalidInterfaceException
695
-     * @throws InvalidDataTypeException
696
-     * @throws EE_Error
697
-     */
698
-    public function end_time($tm_format = '')
699
-    {
700
-        return $this->_show_datetime('T', 'end', null, $tm_format);
701
-    }
702
-
703
-
704
-    /**
705
-     * @param string $tm_format
706
-     * @throws ReflectionException
707
-     * @throws InvalidArgumentException
708
-     * @throws InvalidInterfaceException
709
-     * @throws InvalidDataTypeException
710
-     * @throws EE_Error
711
-     */
712
-    public function e_end_time($tm_format = '')
713
-    {
714
-        $this->_show_datetime('T', 'end', null, $tm_format, true);
715
-    }
716
-
717
-
718
-    /**
719
-     * get time_range
720
-     *
721
-     * @access public
722
-     * @param string $tm_format   string representation of time format defaults to 'g:i a'
723
-     * @param string $conjunction conjunction junction what's your function ?
724
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
725
-     * @return mixed              string on success, FALSE on fail
726
-     * @throws ReflectionException
727
-     * @throws InvalidArgumentException
728
-     * @throws InvalidInterfaceException
729
-     * @throws InvalidDataTypeException
730
-     * @throws EE_Error
731
-     */
732
-    public function time_range($tm_format = '', $conjunction = ' - ')
733
-    {
734
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
735
-        $start = str_replace(
736
-            ' ',
737
-            ' ',
738
-            $this->get_i18n_datetime('DTT_EVT_start', $tm_format)
739
-        );
740
-        $end = str_replace(
741
-            ' ',
742
-            ' ',
743
-            $this->get_i18n_datetime('DTT_EVT_end', $tm_format)
744
-        );
745
-        return $start !== $end ? $start . $conjunction . $end : $start;
746
-    }
747
-
748
-
749
-    /**
750
-     * @param string $tm_format
751
-     * @param string $conjunction
752
-     * @throws ReflectionException
753
-     * @throws InvalidArgumentException
754
-     * @throws InvalidInterfaceException
755
-     * @throws InvalidDataTypeException
756
-     * @throws EE_Error
757
-     */
758
-    public function e_time_range($tm_format = '', $conjunction = ' - ')
759
-    {
760
-        echo esc_html($this->time_range($tm_format, $conjunction));
761
-    }
762
-
763
-
764
-    /**
765
-     * This returns a range representation of the date and times.
766
-     * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
767
-     * Also, the return value is localized.
768
-     *
769
-     * @param string $dt_format
770
-     * @param string $tm_format
771
-     * @param string $conjunction used between two different dates or times.
772
-     *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
773
-     * @param string $separator   used between the date and time formats.
774
-     *                            ex: Dec 1, 2016{$separator}2pm
775
-     * @return string
776
-     * @throws ReflectionException
777
-     * @throws InvalidArgumentException
778
-     * @throws InvalidInterfaceException
779
-     * @throws InvalidDataTypeException
780
-     * @throws EE_Error
781
-     */
782
-    public function date_and_time_range(
783
-        $dt_format = '',
784
-        $tm_format = '',
785
-        $conjunction = ' - ',
786
-        $separator = ' '
787
-    ) {
788
-        $dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
789
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
790
-        $full_format = $dt_format . $separator . $tm_format;
791
-        // the range output depends on various conditions
792
-        switch (true) {
793
-            // start date timestamp and end date timestamp are the same.
794
-            case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
795
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
796
-                break;
797
-            // start and end date are the same but times are different
798
-            case ($this->start_date() === $this->end_date()):
799
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
800
-                          . $conjunction
801
-                          . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
802
-                break;
803
-            // all other conditions
804
-            default:
805
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
806
-                          . $conjunction
807
-                          . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
808
-                break;
809
-        }
810
-        return $output;
811
-    }
812
-
813
-
814
-    /**
815
-     * This echos the results of date and time range.
816
-     *
817
-     * @see date_and_time_range() for more details on purpose.
818
-     * @param string $dt_format
819
-     * @param string $tm_format
820
-     * @param string $conjunction
821
-     * @return void
822
-     * @throws ReflectionException
823
-     * @throws InvalidArgumentException
824
-     * @throws InvalidInterfaceException
825
-     * @throws InvalidDataTypeException
826
-     * @throws EE_Error
827
-     */
828
-    public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
829
-    {
830
-        echo esc_html($this->date_and_time_range($dt_format, $tm_format, $conjunction));
831
-    }
832
-
833
-
834
-    /**
835
-     * get start date and start time
836
-     *
837
-     * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
838
-     * @param    string $tm_format - string representation of time format defaults to 'g:i a'
839
-     * @return    mixed    string on success, FALSE on fail
840
-     * @throws ReflectionException
841
-     * @throws InvalidArgumentException
842
-     * @throws InvalidInterfaceException
843
-     * @throws InvalidDataTypeException
844
-     * @throws EE_Error
845
-     */
846
-    public function start_date_and_time($dt_format = '', $tm_format = '')
847
-    {
848
-        return $this->_show_datetime('', 'start', $dt_format, $tm_format);
849
-    }
850
-
851
-
852
-    /**
853
-     * @param string $dt_frmt
854
-     * @param string $tm_format
855
-     * @throws ReflectionException
856
-     * @throws InvalidArgumentException
857
-     * @throws InvalidInterfaceException
858
-     * @throws InvalidDataTypeException
859
-     * @throws EE_Error
860
-     */
861
-    public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
862
-    {
863
-        $this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
864
-    }
865
-
866
-
867
-    /**
868
-     * Shows the length of the event (start to end time).
869
-     * Can be shown in 'seconds','minutes','hours', or 'days'.
870
-     * By default, rounds up. (So if you use 'days', and then event
871
-     * only occurs for 1 hour, it will return 1 day).
872
-     *
873
-     * @param string $units 'seconds','minutes','hours','days'
874
-     * @param bool   $round_up
875
-     * @return float|int|mixed
876
-     * @throws ReflectionException
877
-     * @throws InvalidArgumentException
878
-     * @throws InvalidInterfaceException
879
-     * @throws InvalidDataTypeException
880
-     * @throws EE_Error
881
-     */
882
-    public function length($units = 'seconds', $round_up = false)
883
-    {
884
-        $start = $this->get_raw('DTT_EVT_start');
885
-        $end = $this->get_raw('DTT_EVT_end');
886
-        $length_in_units = $end - $start;
887
-        switch ($units) {
888
-            // NOTE: We purposefully don't use "break;" in order to chain the divisions
889
-            /** @noinspection PhpMissingBreakStatementInspection */
890
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
891
-            case 'days':
892
-                $length_in_units /= 24;
893
-            /** @noinspection PhpMissingBreakStatementInspection */
894
-            case 'hours':
895
-                // fall through is intentional
896
-                $length_in_units /= 60;
897
-            /** @noinspection PhpMissingBreakStatementInspection */
898
-            case 'minutes':
899
-                // fall through is intentional
900
-                $length_in_units /= 60;
901
-            case 'seconds':
902
-            default:
903
-                $length_in_units = ceil($length_in_units);
904
-        }
905
-        // phpcs:enable
906
-        if ($round_up) {
907
-            $length_in_units = max($length_in_units, 1);
908
-        }
909
-        return $length_in_units;
910
-    }
911
-
912
-
913
-    /**
914
-     *        get end date and time
915
-     *
916
-     * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
917
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
918
-     * @return    mixed                string on success, FALSE on fail
919
-     * @throws ReflectionException
920
-     * @throws InvalidArgumentException
921
-     * @throws InvalidInterfaceException
922
-     * @throws InvalidDataTypeException
923
-     * @throws EE_Error
924
-     */
925
-    public function end_date_and_time($dt_frmt = '', $tm_format = '')
926
-    {
927
-        return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
928
-    }
929
-
930
-
931
-    /**
932
-     * @param string $dt_frmt
933
-     * @param string $tm_format
934
-     * @throws ReflectionException
935
-     * @throws InvalidArgumentException
936
-     * @throws InvalidInterfaceException
937
-     * @throws InvalidDataTypeException
938
-     * @throws EE_Error
939
-     */
940
-    public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
941
-    {
942
-        $this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
943
-    }
944
-
945
-
946
-    /**
947
-     *        get start timestamp
948
-     *
949
-     * @return        int
950
-     * @throws ReflectionException
951
-     * @throws InvalidArgumentException
952
-     * @throws InvalidInterfaceException
953
-     * @throws InvalidDataTypeException
954
-     * @throws EE_Error
955
-     */
956
-    public function start()
957
-    {
958
-        return $this->get_raw('DTT_EVT_start');
959
-    }
960
-
961
-
962
-    /**
963
-     *        get end timestamp
964
-     *
965
-     * @return        int
966
-     * @throws ReflectionException
967
-     * @throws InvalidArgumentException
968
-     * @throws InvalidInterfaceException
969
-     * @throws InvalidDataTypeException
970
-     * @throws EE_Error
971
-     */
972
-    public function end()
973
-    {
974
-        return $this->get_raw('DTT_EVT_end');
975
-    }
976
-
977
-
978
-    /**
979
-     *    get the registration limit for this datetime slot
980
-     *
981
-     * @return        mixed        int on success, FALSE on fail
982
-     * @throws ReflectionException
983
-     * @throws InvalidArgumentException
984
-     * @throws InvalidInterfaceException
985
-     * @throws InvalidDataTypeException
986
-     * @throws EE_Error
987
-     */
988
-    public function reg_limit()
989
-    {
990
-        return $this->get_raw('DTT_reg_limit');
991
-    }
992
-
993
-
994
-    /**
995
-     *    have the tickets sold for this datetime, met or exceed the registration limit ?
996
-     *
997
-     * @return        boolean
998
-     * @throws ReflectionException
999
-     * @throws InvalidArgumentException
1000
-     * @throws InvalidInterfaceException
1001
-     * @throws InvalidDataTypeException
1002
-     * @throws EE_Error
1003
-     */
1004
-    public function sold_out()
1005
-    {
1006
-        return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1007
-    }
1008
-
1009
-
1010
-    /**
1011
-     * return the total number of spaces remaining at this venue.
1012
-     * This only takes the venue's capacity into account, NOT the tickets available for sale
1013
-     *
1014
-     * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1015
-     *                               Because if all tickets attached to this datetime have no spaces left,
1016
-     *                               then this datetime IS effectively sold out.
1017
-     *                               However, there are cases where we just want to know the spaces
1018
-     *                               remaining for this particular datetime, hence the flag.
1019
-     * @return int
1020
-     * @throws ReflectionException
1021
-     * @throws InvalidArgumentException
1022
-     * @throws InvalidInterfaceException
1023
-     * @throws InvalidDataTypeException
1024
-     * @throws EE_Error
1025
-     */
1026
-    public function spaces_remaining($consider_tickets = false)
1027
-    {
1028
-        // tickets remaining available for purchase
1029
-        // no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1030
-        $dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1031
-        if (! $consider_tickets) {
1032
-            return $dtt_remaining;
1033
-        }
1034
-        $tickets_remaining = $this->tickets_remaining();
1035
-        return min($dtt_remaining, $tickets_remaining);
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * Counts the total tickets available
1041
-     * (from all the different types of tickets which are available for this datetime).
1042
-     *
1043
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1044
-     * @return int
1045
-     * @throws ReflectionException
1046
-     * @throws InvalidArgumentException
1047
-     * @throws InvalidInterfaceException
1048
-     * @throws InvalidDataTypeException
1049
-     * @throws EE_Error
1050
-     */
1051
-    public function tickets_remaining($query_params = array())
1052
-    {
1053
-        $sum = 0;
1054
-        $tickets = $this->tickets($query_params);
1055
-        if (! empty($tickets)) {
1056
-            foreach ($tickets as $ticket) {
1057
-                if ($ticket instanceof EE_Ticket) {
1058
-                    // get the actual amount of tickets that can be sold
1059
-                    $qty = $ticket->qty('saleable');
1060
-                    if ($qty === EE_INF) {
1061
-                        return EE_INF;
1062
-                    }
1063
-                    // no negative ticket quantities plz
1064
-                    if ($qty > 0) {
1065
-                        $sum += $qty;
1066
-                    }
1067
-                }
1068
-            }
1069
-        }
1070
-        return $sum;
1071
-    }
1072
-
1073
-
1074
-    /**
1075
-     * Gets the count of all the tickets available at this datetime (not ticket types)
1076
-     * before any were sold
1077
-     *
1078
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1079
-     * @return int
1080
-     * @throws ReflectionException
1081
-     * @throws InvalidArgumentException
1082
-     * @throws InvalidInterfaceException
1083
-     * @throws InvalidDataTypeException
1084
-     * @throws EE_Error
1085
-     */
1086
-    public function sum_tickets_initially_available($query_params = array())
1087
-    {
1088
-        return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1089
-    }
1090
-
1091
-
1092
-    /**
1093
-     * Returns the lesser-of-the two: spaces remaining at this datetime, or
1094
-     * the total tickets remaining (a sum of the tickets remaining for each ticket type
1095
-     * that is available for this datetime).
1096
-     *
1097
-     * @return int
1098
-     * @throws ReflectionException
1099
-     * @throws InvalidArgumentException
1100
-     * @throws InvalidInterfaceException
1101
-     * @throws InvalidDataTypeException
1102
-     * @throws EE_Error
1103
-     */
1104
-    public function total_tickets_available_at_this_datetime()
1105
-    {
1106
-        return $this->spaces_remaining(true);
1107
-    }
1108
-
1109
-
1110
-    /**
1111
-     * This simply compares the internal dtt for the given string with NOW
1112
-     * and determines if the date is upcoming or not.
1113
-     *
1114
-     * @access public
1115
-     * @return boolean
1116
-     * @throws ReflectionException
1117
-     * @throws InvalidArgumentException
1118
-     * @throws InvalidInterfaceException
1119
-     * @throws InvalidDataTypeException
1120
-     * @throws EE_Error
1121
-     */
1122
-    public function is_upcoming()
1123
-    {
1124
-        return ($this->get_raw('DTT_EVT_start') > time());
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * This simply compares the internal datetime for the given string with NOW
1130
-     * and returns if the date is active (i.e. start and end time)
1131
-     *
1132
-     * @return boolean
1133
-     * @throws ReflectionException
1134
-     * @throws InvalidArgumentException
1135
-     * @throws InvalidInterfaceException
1136
-     * @throws InvalidDataTypeException
1137
-     * @throws EE_Error
1138
-     */
1139
-    public function is_active()
1140
-    {
1141
-        return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1142
-    }
1143
-
1144
-
1145
-    /**
1146
-     * This simply compares the internal dtt for the given string with NOW
1147
-     * and determines if the date is expired or not.
1148
-     *
1149
-     * @return boolean
1150
-     * @throws ReflectionException
1151
-     * @throws InvalidArgumentException
1152
-     * @throws InvalidInterfaceException
1153
-     * @throws InvalidDataTypeException
1154
-     * @throws EE_Error
1155
-     */
1156
-    public function is_expired()
1157
-    {
1158
-        return ($this->get_raw('DTT_EVT_end') < time());
1159
-    }
1160
-
1161
-
1162
-    /**
1163
-     * This returns the active status for whether an event is active, upcoming, or expired
1164
-     *
1165
-     * @return int return value will be one of the EE_Datetime status constants.
1166
-     * @throws ReflectionException
1167
-     * @throws InvalidArgumentException
1168
-     * @throws InvalidInterfaceException
1169
-     * @throws InvalidDataTypeException
1170
-     * @throws EE_Error
1171
-     */
1172
-    public function get_active_status()
1173
-    {
1174
-        $total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1175
-        if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1176
-            return EE_Datetime::sold_out;
1177
-        }
1178
-        if ($this->is_expired()) {
1179
-            return EE_Datetime::expired;
1180
-        }
1181
-        if ($this->is_upcoming()) {
1182
-            return EE_Datetime::upcoming;
1183
-        }
1184
-        if ($this->is_active()) {
1185
-            return EE_Datetime::active;
1186
-        }
1187
-        return null;
1188
-    }
1189
-
1190
-
1191
-    /**
1192
-     * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1193
-     *
1194
-     * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1195
-     * @return string
1196
-     * @throws ReflectionException
1197
-     * @throws InvalidArgumentException
1198
-     * @throws InvalidInterfaceException
1199
-     * @throws InvalidDataTypeException
1200
-     * @throws EE_Error
1201
-     */
1202
-    public function get_dtt_display_name($use_dtt_name = false)
1203
-    {
1204
-        if ($use_dtt_name) {
1205
-            $dtt_name = $this->name();
1206
-            if (! empty($dtt_name)) {
1207
-                return $dtt_name;
1208
-            }
1209
-        }
1210
-        // first condition is to see if the months are different
1211
-        if (
1212
-            date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1213
-        ) {
1214
-            $display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
-            // next condition is if its the same month but different day
1216
-        } else {
1217
-            if (
1218
-                date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1219
-                && date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1220
-            ) {
1221
-                $display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1222
-            } else {
1223
-                $display_date = $this->start_date('F j\, Y')
1224
-                                . ' @ '
1225
-                                . $this->start_date('g:i a')
1226
-                                . ' - '
1227
-                                . $this->end_date('g:i a');
1228
-            }
1229
-        }
1230
-        return $display_date;
1231
-    }
1232
-
1233
-
1234
-    /**
1235
-     * Gets all the tickets for this datetime
1236
-     *
1237
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1238
-     * @return EE_Base_Class[]|EE_Ticket[]
1239
-     * @throws ReflectionException
1240
-     * @throws InvalidArgumentException
1241
-     * @throws InvalidInterfaceException
1242
-     * @throws InvalidDataTypeException
1243
-     * @throws EE_Error
1244
-     */
1245
-    public function tickets($query_params = array())
1246
-    {
1247
-        return $this->get_many_related('Ticket', $query_params);
1248
-    }
1249
-
1250
-
1251
-    /**
1252
-     * Gets all the ticket types currently available for purchase
1253
-     *
1254
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1255
-     * @return EE_Ticket[]
1256
-     * @throws ReflectionException
1257
-     * @throws InvalidArgumentException
1258
-     * @throws InvalidInterfaceException
1259
-     * @throws InvalidDataTypeException
1260
-     * @throws EE_Error
1261
-     */
1262
-    public function ticket_types_available_for_purchase($query_params = array())
1263
-    {
1264
-        // first check if datetime is valid
1265
-        if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1266
-            return array();
1267
-        }
1268
-        if (empty($query_params)) {
1269
-            $query_params = array(
1270
-                array(
1271
-                    'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1272
-                    'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1273
-                    'TKT_deleted'    => false,
1274
-                ),
1275
-            );
1276
-        }
1277
-        return $this->tickets($query_params);
1278
-    }
1279
-
1280
-
1281
-    /**
1282
-     * @return EE_Base_Class|EE_Event
1283
-     * @throws ReflectionException
1284
-     * @throws InvalidArgumentException
1285
-     * @throws InvalidInterfaceException
1286
-     * @throws InvalidDataTypeException
1287
-     * @throws EE_Error
1288
-     */
1289
-    public function event()
1290
-    {
1291
-        return $this->get_first_related('Event');
1292
-    }
1293
-
1294
-
1295
-    /**
1296
-     * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1297
-     * (via the tickets).
1298
-     *
1299
-     * @return int
1300
-     * @throws ReflectionException
1301
-     * @throws InvalidArgumentException
1302
-     * @throws InvalidInterfaceException
1303
-     * @throws InvalidDataTypeException
1304
-     * @throws EE_Error
1305
-     */
1306
-    public function update_sold()
1307
-    {
1308
-        $count_regs_for_this_datetime = EEM_Registration::instance()->count(
1309
-            array(
1310
-                array(
1311
-                    'STS_ID'                 => EEM_Registration::status_id_approved,
1312
-                    'REG_deleted'            => 0,
1313
-                    'Ticket.Datetime.DTT_ID' => $this->ID(),
1314
-                ),
1315
-            )
1316
-        );
1317
-        $this->set_sold($count_regs_for_this_datetime);
1318
-        $this->save();
1319
-        return $count_regs_for_this_datetime;
1320
-    }
1321
-
1322
-
1323
-    /*******************************************************************
15
+	/**
16
+	 * constant used by get_active_status, indicates datetime has no more available spaces
17
+	 */
18
+	const sold_out = 'DTS';
19
+
20
+	/**
21
+	 * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
22
+	 */
23
+	const active = 'DTA';
24
+
25
+	/**
26
+	 * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
27
+	 * expired
28
+	 */
29
+	const upcoming = 'DTU';
30
+
31
+	/**
32
+	 * Datetime is postponed
33
+	 */
34
+	const postponed = 'DTP';
35
+
36
+	/**
37
+	 * Datetime is cancelled
38
+	 */
39
+	const cancelled = 'DTC';
40
+
41
+	/**
42
+	 * constant used by get_active_status, indicates datetime has expired (event is over)
43
+	 */
44
+	const expired = 'DTE';
45
+
46
+	/**
47
+	 * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
48
+	 */
49
+	const inactive = 'DTI';
50
+
51
+
52
+	/**
53
+	 * @param array  $props_n_values    incoming values
54
+	 * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
55
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
56
+	 *                                  and the second value is the time format
57
+	 * @return EE_Datetime
58
+	 * @throws ReflectionException
59
+	 * @throws InvalidArgumentException
60
+	 * @throws InvalidInterfaceException
61
+	 * @throws InvalidDataTypeException
62
+	 * @throws EE_Error
63
+	 */
64
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
65
+	{
66
+		$has_object = parent::_check_for_object(
67
+			$props_n_values,
68
+			__CLASS__,
69
+			$timezone,
70
+			$date_formats
71
+		);
72
+		return $has_object
73
+			? $has_object
74
+			: new self($props_n_values, false, $timezone, $date_formats);
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param array  $props_n_values  incoming values from the database
80
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
+	 *                                the website will be used.
82
+	 * @return EE_Datetime
83
+	 * @throws ReflectionException
84
+	 * @throws InvalidArgumentException
85
+	 * @throws InvalidInterfaceException
86
+	 * @throws InvalidDataTypeException
87
+	 * @throws EE_Error
88
+	 */
89
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
90
+	{
91
+		return new self($props_n_values, true, $timezone);
92
+	}
93
+
94
+
95
+	/**
96
+	 * @param $name
97
+	 * @throws ReflectionException
98
+	 * @throws InvalidArgumentException
99
+	 * @throws InvalidInterfaceException
100
+	 * @throws InvalidDataTypeException
101
+	 * @throws EE_Error
102
+	 */
103
+	public function set_name($name)
104
+	{
105
+		$this->set('DTT_name', $name);
106
+	}
107
+
108
+
109
+	/**
110
+	 * @param $description
111
+	 * @throws ReflectionException
112
+	 * @throws InvalidArgumentException
113
+	 * @throws InvalidInterfaceException
114
+	 * @throws InvalidDataTypeException
115
+	 * @throws EE_Error
116
+	 */
117
+	public function set_description($description)
118
+	{
119
+		$this->set('DTT_description', $description);
120
+	}
121
+
122
+
123
+	/**
124
+	 * Set event start date
125
+	 * set the start date for an event
126
+	 *
127
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
128
+	 * @throws ReflectionException
129
+	 * @throws InvalidArgumentException
130
+	 * @throws InvalidInterfaceException
131
+	 * @throws InvalidDataTypeException
132
+	 * @throws EE_Error
133
+	 */
134
+	public function set_start_date($date)
135
+	{
136
+		$this->_set_date_for($date, 'DTT_EVT_start');
137
+	}
138
+
139
+
140
+	/**
141
+	 * Set event start time
142
+	 * set the start time for an event
143
+	 *
144
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
145
+	 * @throws ReflectionException
146
+	 * @throws InvalidArgumentException
147
+	 * @throws InvalidInterfaceException
148
+	 * @throws InvalidDataTypeException
149
+	 * @throws EE_Error
150
+	 */
151
+	public function set_start_time($time)
152
+	{
153
+		$this->_set_time_for($time, 'DTT_EVT_start');
154
+	}
155
+
156
+
157
+	/**
158
+	 * Set event end date
159
+	 * set the end date for an event
160
+	 *
161
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
162
+	 * @throws ReflectionException
163
+	 * @throws InvalidArgumentException
164
+	 * @throws InvalidInterfaceException
165
+	 * @throws InvalidDataTypeException
166
+	 * @throws EE_Error
167
+	 */
168
+	public function set_end_date($date)
169
+	{
170
+		$this->_set_date_for($date, 'DTT_EVT_end');
171
+	}
172
+
173
+
174
+	/**
175
+	 * Set event end time
176
+	 * set the end time for an event
177
+	 *
178
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
179
+	 * @throws ReflectionException
180
+	 * @throws InvalidArgumentException
181
+	 * @throws InvalidInterfaceException
182
+	 * @throws InvalidDataTypeException
183
+	 * @throws EE_Error
184
+	 */
185
+	public function set_end_time($time)
186
+	{
187
+		$this->_set_time_for($time, 'DTT_EVT_end');
188
+	}
189
+
190
+
191
+	/**
192
+	 * Set registration limit
193
+	 * set the maximum number of attendees that can be registered for this datetime slot
194
+	 *
195
+	 * @param int $reg_limit
196
+	 * @throws ReflectionException
197
+	 * @throws InvalidArgumentException
198
+	 * @throws InvalidInterfaceException
199
+	 * @throws InvalidDataTypeException
200
+	 * @throws EE_Error
201
+	 */
202
+	public function set_reg_limit($reg_limit)
203
+	{
204
+		$this->set('DTT_reg_limit', $reg_limit);
205
+	}
206
+
207
+
208
+	/**
209
+	 * get the number of tickets sold for this datetime slot
210
+	 *
211
+	 * @return mixed int on success, FALSE on fail
212
+	 * @throws ReflectionException
213
+	 * @throws InvalidArgumentException
214
+	 * @throws InvalidInterfaceException
215
+	 * @throws InvalidDataTypeException
216
+	 * @throws EE_Error
217
+	 */
218
+	public function sold()
219
+	{
220
+		return $this->get_raw('DTT_sold');
221
+	}
222
+
223
+
224
+	/**
225
+	 * @param int $sold
226
+	 * @throws ReflectionException
227
+	 * @throws InvalidArgumentException
228
+	 * @throws InvalidInterfaceException
229
+	 * @throws InvalidDataTypeException
230
+	 * @throws EE_Error
231
+	 */
232
+	public function set_sold($sold)
233
+	{
234
+		// sold can not go below zero
235
+		$sold = max(0, $sold);
236
+		$this->set('DTT_sold', $sold);
237
+	}
238
+
239
+
240
+	/**
241
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
242
+	 * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
243
+	 *
244
+	 * @param int $qty
245
+	 * @param boolean $also_decrease_reserved
246
+	 * @return boolean indicating success
247
+	 * @throws ReflectionException
248
+	 * @throws InvalidArgumentException
249
+	 * @throws InvalidInterfaceException
250
+	 * @throws InvalidDataTypeException
251
+	 * @throws EE_Error
252
+	 */
253
+	public function increaseSold($qty = 1, $also_decrease_reserved = true)
254
+	{
255
+		$qty = absint($qty);
256
+		if ($also_decrease_reserved) {
257
+			$success = $this->adjustNumericFieldsInDb(
258
+				[
259
+					'DTT_reserved' => $qty * -1,
260
+					'DTT_sold' => $qty
261
+				]
262
+			);
263
+		} else {
264
+			$success = $this->adjustNumericFieldsInDb(
265
+				[
266
+					'DTT_sold' => $qty
267
+				]
268
+			);
269
+		}
270
+
271
+		do_action(
272
+			'AHEE__EE_Datetime__increase_sold',
273
+			$this,
274
+			$qty,
275
+			$this->sold(),
276
+			$success
277
+		);
278
+		return $success;
279
+	}
280
+
281
+
282
+	/**
283
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
284
+	 * to save afterwards.)
285
+	 *
286
+	 * @param int $qty
287
+	 * @return boolean indicating success
288
+	 * @throws ReflectionException
289
+	 * @throws InvalidArgumentException
290
+	 * @throws InvalidInterfaceException
291
+	 * @throws InvalidDataTypeException
292
+	 * @throws EE_Error
293
+	 */
294
+	public function decreaseSold($qty = 1)
295
+	{
296
+		$qty = absint($qty);
297
+		$success = $this->adjustNumericFieldsInDb(
298
+			[
299
+				'DTT_sold' => $qty * -1
300
+			]
301
+		);
302
+		do_action(
303
+			'AHEE__EE_Datetime__decrease_sold',
304
+			$this,
305
+			$qty,
306
+			$this->sold(),
307
+			$success
308
+		);
309
+		return $success;
310
+	}
311
+
312
+
313
+	/**
314
+	 * Gets qty of reserved tickets for this datetime
315
+	 *
316
+	 * @return int
317
+	 * @throws ReflectionException
318
+	 * @throws InvalidArgumentException
319
+	 * @throws InvalidInterfaceException
320
+	 * @throws InvalidDataTypeException
321
+	 * @throws EE_Error
322
+	 */
323
+	public function reserved()
324
+	{
325
+		return $this->get_raw('DTT_reserved');
326
+	}
327
+
328
+
329
+	/**
330
+	 * Sets qty of reserved tickets for this datetime
331
+	 *
332
+	 * @param int $reserved
333
+	 * @throws ReflectionException
334
+	 * @throws InvalidArgumentException
335
+	 * @throws InvalidInterfaceException
336
+	 * @throws InvalidDataTypeException
337
+	 * @throws EE_Error
338
+	 */
339
+	public function set_reserved($reserved)
340
+	{
341
+		// reserved can not go below zero
342
+		$reserved = max(0, (int) $reserved);
343
+		$this->set('DTT_reserved', $reserved);
344
+	}
345
+
346
+
347
+	/**
348
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
349
+	 *
350
+	 * @param int $qty
351
+	 * @return boolean indicating success
352
+	 * @throws ReflectionException
353
+	 * @throws InvalidArgumentException
354
+	 * @throws InvalidInterfaceException
355
+	 * @throws InvalidDataTypeException
356
+	 * @throws EE_Error
357
+	 */
358
+	public function increaseReserved($qty = 1)
359
+	{
360
+		$qty = absint($qty);
361
+		$success = $this->incrementFieldConditionallyInDb(
362
+			'DTT_reserved',
363
+			'DTT_sold',
364
+			'DTT_reg_limit',
365
+			$qty
366
+		);
367
+		do_action(
368
+			'AHEE__EE_Datetime__increase_reserved',
369
+			$this,
370
+			$qty,
371
+			$this->reserved(),
372
+			$success
373
+		);
374
+		return $success;
375
+	}
376
+
377
+
378
+	/**
379
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
380
+	 *
381
+	 * @param int $qty
382
+	 * @return boolean indicating success
383
+	 * @throws ReflectionException
384
+	 * @throws InvalidArgumentException
385
+	 * @throws InvalidInterfaceException
386
+	 * @throws InvalidDataTypeException
387
+	 * @throws EE_Error
388
+	 */
389
+	public function decreaseReserved($qty = 1)
390
+	{
391
+		$qty = absint($qty);
392
+		$success = $this->adjustNumericFieldsInDb(
393
+			[
394
+				'DTT_reserved' => $qty * -1
395
+			]
396
+		);
397
+		do_action(
398
+			'AHEE__EE_Datetime__decrease_reserved',
399
+			$this,
400
+			$qty,
401
+			$this->reserved(),
402
+			$success
403
+		);
404
+		return $success;
405
+	}
406
+
407
+
408
+	/**
409
+	 * total sold and reserved tickets
410
+	 *
411
+	 * @return int
412
+	 * @throws ReflectionException
413
+	 * @throws InvalidArgumentException
414
+	 * @throws InvalidInterfaceException
415
+	 * @throws InvalidDataTypeException
416
+	 * @throws EE_Error
417
+	 */
418
+	public function sold_and_reserved()
419
+	{
420
+		return $this->sold() + $this->reserved();
421
+	}
422
+
423
+
424
+	/**
425
+	 * returns the datetime name
426
+	 *
427
+	 * @return string
428
+	 * @throws ReflectionException
429
+	 * @throws InvalidArgumentException
430
+	 * @throws InvalidInterfaceException
431
+	 * @throws InvalidDataTypeException
432
+	 * @throws EE_Error
433
+	 */
434
+	public function name()
435
+	{
436
+		return $this->get('DTT_name');
437
+	}
438
+
439
+
440
+	/**
441
+	 * returns the datetime description
442
+	 *
443
+	 * @return string
444
+	 * @throws ReflectionException
445
+	 * @throws InvalidArgumentException
446
+	 * @throws InvalidInterfaceException
447
+	 * @throws InvalidDataTypeException
448
+	 * @throws EE_Error
449
+	 */
450
+	public function description()
451
+	{
452
+		return $this->get('DTT_description');
453
+	}
454
+
455
+
456
+	/**
457
+	 * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
458
+	 *
459
+	 * @return boolean  TRUE if is primary, FALSE if not.
460
+	 * @throws ReflectionException
461
+	 * @throws InvalidArgumentException
462
+	 * @throws InvalidInterfaceException
463
+	 * @throws InvalidDataTypeException
464
+	 * @throws EE_Error
465
+	 */
466
+	public function is_primary()
467
+	{
468
+		return $this->get('DTT_is_primary');
469
+	}
470
+
471
+
472
+	/**
473
+	 * This helper simply returns the order for the datetime
474
+	 *
475
+	 * @return int  The order of the datetime for this event.
476
+	 * @throws ReflectionException
477
+	 * @throws InvalidArgumentException
478
+	 * @throws InvalidInterfaceException
479
+	 * @throws InvalidDataTypeException
480
+	 * @throws EE_Error
481
+	 */
482
+	public function order()
483
+	{
484
+		return $this->get('DTT_order');
485
+	}
486
+
487
+
488
+	/**
489
+	 * This helper simply returns the parent id for the datetime
490
+	 *
491
+	 * @return int
492
+	 * @throws ReflectionException
493
+	 * @throws InvalidArgumentException
494
+	 * @throws InvalidInterfaceException
495
+	 * @throws InvalidDataTypeException
496
+	 * @throws EE_Error
497
+	 */
498
+	public function parent()
499
+	{
500
+		return $this->get('DTT_parent');
501
+	}
502
+
503
+
504
+	/**
505
+	 * show date and/or time
506
+	 *
507
+	 * @param string $date_or_time    whether to display a date or time or both
508
+	 * @param string $start_or_end    whether to display start or end datetimes
509
+	 * @param string $dt_frmt
510
+	 * @param string $tm_frmt
511
+	 * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
512
+	 *                                otherwise we use the standard formats)
513
+	 * @return string|bool  string on success, FALSE on fail
514
+	 * @throws ReflectionException
515
+	 * @throws InvalidArgumentException
516
+	 * @throws InvalidInterfaceException
517
+	 * @throws InvalidDataTypeException
518
+	 * @throws EE_Error
519
+	 */
520
+	private function _show_datetime(
521
+		$date_or_time = null,
522
+		$start_or_end = 'start',
523
+		$dt_frmt = '',
524
+		$tm_frmt = '',
525
+		$echo = false
526
+	) {
527
+		$field_name = "DTT_EVT_{$start_or_end}";
528
+		$dtt = $this->_get_datetime(
529
+			$field_name,
530
+			$dt_frmt,
531
+			$tm_frmt,
532
+			$date_or_time,
533
+			$echo
534
+		);
535
+		if (! $echo) {
536
+			return $dtt;
537
+		}
538
+		return '';
539
+	}
540
+
541
+
542
+	/**
543
+	 * get event start date.  Provide either the date format, or NULL to re-use the
544
+	 * last-used format, or '' to use the default date format
545
+	 *
546
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
547
+	 * @return mixed            string on success, FALSE on fail
548
+	 * @throws ReflectionException
549
+	 * @throws InvalidArgumentException
550
+	 * @throws InvalidInterfaceException
551
+	 * @throws InvalidDataTypeException
552
+	 * @throws EE_Error
553
+	 */
554
+	public function start_date($dt_frmt = '')
555
+	{
556
+		return $this->_show_datetime('D', 'start', $dt_frmt);
557
+	}
558
+
559
+
560
+	/**
561
+	 * Echoes start_date()
562
+	 *
563
+	 * @param string $dt_frmt
564
+	 * @throws ReflectionException
565
+	 * @throws InvalidArgumentException
566
+	 * @throws InvalidInterfaceException
567
+	 * @throws InvalidDataTypeException
568
+	 * @throws EE_Error
569
+	 */
570
+	public function e_start_date($dt_frmt = '')
571
+	{
572
+		$this->_show_datetime('D', 'start', $dt_frmt, null, true);
573
+	}
574
+
575
+
576
+	/**
577
+	 * get end date. Provide either the date format, or NULL to re-use the
578
+	 * last-used format, or '' to use the default date format
579
+	 *
580
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
581
+	 * @return mixed            string on success, FALSE on fail
582
+	 * @throws ReflectionException
583
+	 * @throws InvalidArgumentException
584
+	 * @throws InvalidInterfaceException
585
+	 * @throws InvalidDataTypeException
586
+	 * @throws EE_Error
587
+	 */
588
+	public function end_date($dt_frmt = '')
589
+	{
590
+		return $this->_show_datetime('D', 'end', $dt_frmt);
591
+	}
592
+
593
+
594
+	/**
595
+	 * Echoes the end date. See end_date()
596
+	 *
597
+	 * @param string $dt_frmt
598
+	 * @throws ReflectionException
599
+	 * @throws InvalidArgumentException
600
+	 * @throws InvalidInterfaceException
601
+	 * @throws InvalidDataTypeException
602
+	 * @throws EE_Error
603
+	 */
604
+	public function e_end_date($dt_frmt = '')
605
+	{
606
+		$this->_show_datetime('D', 'end', $dt_frmt, null, true);
607
+	}
608
+
609
+
610
+	/**
611
+	 * get date_range - meaning the start AND end date
612
+	 *
613
+	 * @access public
614
+	 * @param string $dt_frmt     string representation of date format defaults to WP settings
615
+	 * @param string $conjunction conjunction junction what's your function ?
616
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
617
+	 * @return mixed              string on success, FALSE on fail
618
+	 * @throws ReflectionException
619
+	 * @throws InvalidArgumentException
620
+	 * @throws InvalidInterfaceException
621
+	 * @throws InvalidDataTypeException
622
+	 * @throws EE_Error
623
+	 */
624
+	public function date_range($dt_frmt = '', $conjunction = ' - ')
625
+	{
626
+		$dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
627
+		$start = str_replace(
628
+			' ',
629
+			'&nbsp;',
630
+			$this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
631
+		);
632
+		$end = str_replace(
633
+			' ',
634
+			'&nbsp;',
635
+			$this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
636
+		);
637
+		return $start !== $end ? $start . $conjunction . $end : $start;
638
+	}
639
+
640
+
641
+	/**
642
+	 * @param string $dt_frmt
643
+	 * @param string $conjunction
644
+	 * @throws ReflectionException
645
+	 * @throws InvalidArgumentException
646
+	 * @throws InvalidInterfaceException
647
+	 * @throws InvalidDataTypeException
648
+	 * @throws EE_Error
649
+	 */
650
+	public function e_date_range($dt_frmt = '', $conjunction = ' - ')
651
+	{
652
+		echo esc_html($this->date_range($dt_frmt, $conjunction));
653
+	}
654
+
655
+
656
+	/**
657
+	 * get start time
658
+	 *
659
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
660
+	 * @return mixed        string on success, FALSE on fail
661
+	 * @throws ReflectionException
662
+	 * @throws InvalidArgumentException
663
+	 * @throws InvalidInterfaceException
664
+	 * @throws InvalidDataTypeException
665
+	 * @throws EE_Error
666
+	 */
667
+	public function start_time($tm_format = '')
668
+	{
669
+		return $this->_show_datetime('T', 'start', null, $tm_format);
670
+	}
671
+
672
+
673
+	/**
674
+	 * @param string $tm_format
675
+	 * @throws ReflectionException
676
+	 * @throws InvalidArgumentException
677
+	 * @throws InvalidInterfaceException
678
+	 * @throws InvalidDataTypeException
679
+	 * @throws EE_Error
680
+	 */
681
+	public function e_start_time($tm_format = '')
682
+	{
683
+		$this->_show_datetime('T', 'start', null, $tm_format, true);
684
+	}
685
+
686
+
687
+	/**
688
+	 * get end time
689
+	 *
690
+	 * @param string $tm_format string representation of time format defaults to 'g:i a'
691
+	 * @return mixed                string on success, FALSE on fail
692
+	 * @throws ReflectionException
693
+	 * @throws InvalidArgumentException
694
+	 * @throws InvalidInterfaceException
695
+	 * @throws InvalidDataTypeException
696
+	 * @throws EE_Error
697
+	 */
698
+	public function end_time($tm_format = '')
699
+	{
700
+		return $this->_show_datetime('T', 'end', null, $tm_format);
701
+	}
702
+
703
+
704
+	/**
705
+	 * @param string $tm_format
706
+	 * @throws ReflectionException
707
+	 * @throws InvalidArgumentException
708
+	 * @throws InvalidInterfaceException
709
+	 * @throws InvalidDataTypeException
710
+	 * @throws EE_Error
711
+	 */
712
+	public function e_end_time($tm_format = '')
713
+	{
714
+		$this->_show_datetime('T', 'end', null, $tm_format, true);
715
+	}
716
+
717
+
718
+	/**
719
+	 * get time_range
720
+	 *
721
+	 * @access public
722
+	 * @param string $tm_format   string representation of time format defaults to 'g:i a'
723
+	 * @param string $conjunction conjunction junction what's your function ?
724
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
725
+	 * @return mixed              string on success, FALSE on fail
726
+	 * @throws ReflectionException
727
+	 * @throws InvalidArgumentException
728
+	 * @throws InvalidInterfaceException
729
+	 * @throws InvalidDataTypeException
730
+	 * @throws EE_Error
731
+	 */
732
+	public function time_range($tm_format = '', $conjunction = ' - ')
733
+	{
734
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
735
+		$start = str_replace(
736
+			' ',
737
+			'&nbsp;',
738
+			$this->get_i18n_datetime('DTT_EVT_start', $tm_format)
739
+		);
740
+		$end = str_replace(
741
+			' ',
742
+			'&nbsp;',
743
+			$this->get_i18n_datetime('DTT_EVT_end', $tm_format)
744
+		);
745
+		return $start !== $end ? $start . $conjunction . $end : $start;
746
+	}
747
+
748
+
749
+	/**
750
+	 * @param string $tm_format
751
+	 * @param string $conjunction
752
+	 * @throws ReflectionException
753
+	 * @throws InvalidArgumentException
754
+	 * @throws InvalidInterfaceException
755
+	 * @throws InvalidDataTypeException
756
+	 * @throws EE_Error
757
+	 */
758
+	public function e_time_range($tm_format = '', $conjunction = ' - ')
759
+	{
760
+		echo esc_html($this->time_range($tm_format, $conjunction));
761
+	}
762
+
763
+
764
+	/**
765
+	 * This returns a range representation of the date and times.
766
+	 * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
767
+	 * Also, the return value is localized.
768
+	 *
769
+	 * @param string $dt_format
770
+	 * @param string $tm_format
771
+	 * @param string $conjunction used between two different dates or times.
772
+	 *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
773
+	 * @param string $separator   used between the date and time formats.
774
+	 *                            ex: Dec 1, 2016{$separator}2pm
775
+	 * @return string
776
+	 * @throws ReflectionException
777
+	 * @throws InvalidArgumentException
778
+	 * @throws InvalidInterfaceException
779
+	 * @throws InvalidDataTypeException
780
+	 * @throws EE_Error
781
+	 */
782
+	public function date_and_time_range(
783
+		$dt_format = '',
784
+		$tm_format = '',
785
+		$conjunction = ' - ',
786
+		$separator = ' '
787
+	) {
788
+		$dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
789
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
790
+		$full_format = $dt_format . $separator . $tm_format;
791
+		// the range output depends on various conditions
792
+		switch (true) {
793
+			// start date timestamp and end date timestamp are the same.
794
+			case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
795
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
796
+				break;
797
+			// start and end date are the same but times are different
798
+			case ($this->start_date() === $this->end_date()):
799
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
800
+						  . $conjunction
801
+						  . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
802
+				break;
803
+			// all other conditions
804
+			default:
805
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
806
+						  . $conjunction
807
+						  . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
808
+				break;
809
+		}
810
+		return $output;
811
+	}
812
+
813
+
814
+	/**
815
+	 * This echos the results of date and time range.
816
+	 *
817
+	 * @see date_and_time_range() for more details on purpose.
818
+	 * @param string $dt_format
819
+	 * @param string $tm_format
820
+	 * @param string $conjunction
821
+	 * @return void
822
+	 * @throws ReflectionException
823
+	 * @throws InvalidArgumentException
824
+	 * @throws InvalidInterfaceException
825
+	 * @throws InvalidDataTypeException
826
+	 * @throws EE_Error
827
+	 */
828
+	public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
829
+	{
830
+		echo esc_html($this->date_and_time_range($dt_format, $tm_format, $conjunction));
831
+	}
832
+
833
+
834
+	/**
835
+	 * get start date and start time
836
+	 *
837
+	 * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
838
+	 * @param    string $tm_format - string representation of time format defaults to 'g:i a'
839
+	 * @return    mixed    string on success, FALSE on fail
840
+	 * @throws ReflectionException
841
+	 * @throws InvalidArgumentException
842
+	 * @throws InvalidInterfaceException
843
+	 * @throws InvalidDataTypeException
844
+	 * @throws EE_Error
845
+	 */
846
+	public function start_date_and_time($dt_format = '', $tm_format = '')
847
+	{
848
+		return $this->_show_datetime('', 'start', $dt_format, $tm_format);
849
+	}
850
+
851
+
852
+	/**
853
+	 * @param string $dt_frmt
854
+	 * @param string $tm_format
855
+	 * @throws ReflectionException
856
+	 * @throws InvalidArgumentException
857
+	 * @throws InvalidInterfaceException
858
+	 * @throws InvalidDataTypeException
859
+	 * @throws EE_Error
860
+	 */
861
+	public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
862
+	{
863
+		$this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
864
+	}
865
+
866
+
867
+	/**
868
+	 * Shows the length of the event (start to end time).
869
+	 * Can be shown in 'seconds','minutes','hours', or 'days'.
870
+	 * By default, rounds up. (So if you use 'days', and then event
871
+	 * only occurs for 1 hour, it will return 1 day).
872
+	 *
873
+	 * @param string $units 'seconds','minutes','hours','days'
874
+	 * @param bool   $round_up
875
+	 * @return float|int|mixed
876
+	 * @throws ReflectionException
877
+	 * @throws InvalidArgumentException
878
+	 * @throws InvalidInterfaceException
879
+	 * @throws InvalidDataTypeException
880
+	 * @throws EE_Error
881
+	 */
882
+	public function length($units = 'seconds', $round_up = false)
883
+	{
884
+		$start = $this->get_raw('DTT_EVT_start');
885
+		$end = $this->get_raw('DTT_EVT_end');
886
+		$length_in_units = $end - $start;
887
+		switch ($units) {
888
+			// NOTE: We purposefully don't use "break;" in order to chain the divisions
889
+			/** @noinspection PhpMissingBreakStatementInspection */
890
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
891
+			case 'days':
892
+				$length_in_units /= 24;
893
+			/** @noinspection PhpMissingBreakStatementInspection */
894
+			case 'hours':
895
+				// fall through is intentional
896
+				$length_in_units /= 60;
897
+			/** @noinspection PhpMissingBreakStatementInspection */
898
+			case 'minutes':
899
+				// fall through is intentional
900
+				$length_in_units /= 60;
901
+			case 'seconds':
902
+			default:
903
+				$length_in_units = ceil($length_in_units);
904
+		}
905
+		// phpcs:enable
906
+		if ($round_up) {
907
+			$length_in_units = max($length_in_units, 1);
908
+		}
909
+		return $length_in_units;
910
+	}
911
+
912
+
913
+	/**
914
+	 *        get end date and time
915
+	 *
916
+	 * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
917
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
918
+	 * @return    mixed                string on success, FALSE on fail
919
+	 * @throws ReflectionException
920
+	 * @throws InvalidArgumentException
921
+	 * @throws InvalidInterfaceException
922
+	 * @throws InvalidDataTypeException
923
+	 * @throws EE_Error
924
+	 */
925
+	public function end_date_and_time($dt_frmt = '', $tm_format = '')
926
+	{
927
+		return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
928
+	}
929
+
930
+
931
+	/**
932
+	 * @param string $dt_frmt
933
+	 * @param string $tm_format
934
+	 * @throws ReflectionException
935
+	 * @throws InvalidArgumentException
936
+	 * @throws InvalidInterfaceException
937
+	 * @throws InvalidDataTypeException
938
+	 * @throws EE_Error
939
+	 */
940
+	public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
941
+	{
942
+		$this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
943
+	}
944
+
945
+
946
+	/**
947
+	 *        get start timestamp
948
+	 *
949
+	 * @return        int
950
+	 * @throws ReflectionException
951
+	 * @throws InvalidArgumentException
952
+	 * @throws InvalidInterfaceException
953
+	 * @throws InvalidDataTypeException
954
+	 * @throws EE_Error
955
+	 */
956
+	public function start()
957
+	{
958
+		return $this->get_raw('DTT_EVT_start');
959
+	}
960
+
961
+
962
+	/**
963
+	 *        get end timestamp
964
+	 *
965
+	 * @return        int
966
+	 * @throws ReflectionException
967
+	 * @throws InvalidArgumentException
968
+	 * @throws InvalidInterfaceException
969
+	 * @throws InvalidDataTypeException
970
+	 * @throws EE_Error
971
+	 */
972
+	public function end()
973
+	{
974
+		return $this->get_raw('DTT_EVT_end');
975
+	}
976
+
977
+
978
+	/**
979
+	 *    get the registration limit for this datetime slot
980
+	 *
981
+	 * @return        mixed        int on success, FALSE on fail
982
+	 * @throws ReflectionException
983
+	 * @throws InvalidArgumentException
984
+	 * @throws InvalidInterfaceException
985
+	 * @throws InvalidDataTypeException
986
+	 * @throws EE_Error
987
+	 */
988
+	public function reg_limit()
989
+	{
990
+		return $this->get_raw('DTT_reg_limit');
991
+	}
992
+
993
+
994
+	/**
995
+	 *    have the tickets sold for this datetime, met or exceed the registration limit ?
996
+	 *
997
+	 * @return        boolean
998
+	 * @throws ReflectionException
999
+	 * @throws InvalidArgumentException
1000
+	 * @throws InvalidInterfaceException
1001
+	 * @throws InvalidDataTypeException
1002
+	 * @throws EE_Error
1003
+	 */
1004
+	public function sold_out()
1005
+	{
1006
+		return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1007
+	}
1008
+
1009
+
1010
+	/**
1011
+	 * return the total number of spaces remaining at this venue.
1012
+	 * This only takes the venue's capacity into account, NOT the tickets available for sale
1013
+	 *
1014
+	 * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1015
+	 *                               Because if all tickets attached to this datetime have no spaces left,
1016
+	 *                               then this datetime IS effectively sold out.
1017
+	 *                               However, there are cases where we just want to know the spaces
1018
+	 *                               remaining for this particular datetime, hence the flag.
1019
+	 * @return int
1020
+	 * @throws ReflectionException
1021
+	 * @throws InvalidArgumentException
1022
+	 * @throws InvalidInterfaceException
1023
+	 * @throws InvalidDataTypeException
1024
+	 * @throws EE_Error
1025
+	 */
1026
+	public function spaces_remaining($consider_tickets = false)
1027
+	{
1028
+		// tickets remaining available for purchase
1029
+		// no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1030
+		$dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1031
+		if (! $consider_tickets) {
1032
+			return $dtt_remaining;
1033
+		}
1034
+		$tickets_remaining = $this->tickets_remaining();
1035
+		return min($dtt_remaining, $tickets_remaining);
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * Counts the total tickets available
1041
+	 * (from all the different types of tickets which are available for this datetime).
1042
+	 *
1043
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1044
+	 * @return int
1045
+	 * @throws ReflectionException
1046
+	 * @throws InvalidArgumentException
1047
+	 * @throws InvalidInterfaceException
1048
+	 * @throws InvalidDataTypeException
1049
+	 * @throws EE_Error
1050
+	 */
1051
+	public function tickets_remaining($query_params = array())
1052
+	{
1053
+		$sum = 0;
1054
+		$tickets = $this->tickets($query_params);
1055
+		if (! empty($tickets)) {
1056
+			foreach ($tickets as $ticket) {
1057
+				if ($ticket instanceof EE_Ticket) {
1058
+					// get the actual amount of tickets that can be sold
1059
+					$qty = $ticket->qty('saleable');
1060
+					if ($qty === EE_INF) {
1061
+						return EE_INF;
1062
+					}
1063
+					// no negative ticket quantities plz
1064
+					if ($qty > 0) {
1065
+						$sum += $qty;
1066
+					}
1067
+				}
1068
+			}
1069
+		}
1070
+		return $sum;
1071
+	}
1072
+
1073
+
1074
+	/**
1075
+	 * Gets the count of all the tickets available at this datetime (not ticket types)
1076
+	 * before any were sold
1077
+	 *
1078
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1079
+	 * @return int
1080
+	 * @throws ReflectionException
1081
+	 * @throws InvalidArgumentException
1082
+	 * @throws InvalidInterfaceException
1083
+	 * @throws InvalidDataTypeException
1084
+	 * @throws EE_Error
1085
+	 */
1086
+	public function sum_tickets_initially_available($query_params = array())
1087
+	{
1088
+		return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1089
+	}
1090
+
1091
+
1092
+	/**
1093
+	 * Returns the lesser-of-the two: spaces remaining at this datetime, or
1094
+	 * the total tickets remaining (a sum of the tickets remaining for each ticket type
1095
+	 * that is available for this datetime).
1096
+	 *
1097
+	 * @return int
1098
+	 * @throws ReflectionException
1099
+	 * @throws InvalidArgumentException
1100
+	 * @throws InvalidInterfaceException
1101
+	 * @throws InvalidDataTypeException
1102
+	 * @throws EE_Error
1103
+	 */
1104
+	public function total_tickets_available_at_this_datetime()
1105
+	{
1106
+		return $this->spaces_remaining(true);
1107
+	}
1108
+
1109
+
1110
+	/**
1111
+	 * This simply compares the internal dtt for the given string with NOW
1112
+	 * and determines if the date is upcoming or not.
1113
+	 *
1114
+	 * @access public
1115
+	 * @return boolean
1116
+	 * @throws ReflectionException
1117
+	 * @throws InvalidArgumentException
1118
+	 * @throws InvalidInterfaceException
1119
+	 * @throws InvalidDataTypeException
1120
+	 * @throws EE_Error
1121
+	 */
1122
+	public function is_upcoming()
1123
+	{
1124
+		return ($this->get_raw('DTT_EVT_start') > time());
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * This simply compares the internal datetime for the given string with NOW
1130
+	 * and returns if the date is active (i.e. start and end time)
1131
+	 *
1132
+	 * @return boolean
1133
+	 * @throws ReflectionException
1134
+	 * @throws InvalidArgumentException
1135
+	 * @throws InvalidInterfaceException
1136
+	 * @throws InvalidDataTypeException
1137
+	 * @throws EE_Error
1138
+	 */
1139
+	public function is_active()
1140
+	{
1141
+		return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1142
+	}
1143
+
1144
+
1145
+	/**
1146
+	 * This simply compares the internal dtt for the given string with NOW
1147
+	 * and determines if the date is expired or not.
1148
+	 *
1149
+	 * @return boolean
1150
+	 * @throws ReflectionException
1151
+	 * @throws InvalidArgumentException
1152
+	 * @throws InvalidInterfaceException
1153
+	 * @throws InvalidDataTypeException
1154
+	 * @throws EE_Error
1155
+	 */
1156
+	public function is_expired()
1157
+	{
1158
+		return ($this->get_raw('DTT_EVT_end') < time());
1159
+	}
1160
+
1161
+
1162
+	/**
1163
+	 * This returns the active status for whether an event is active, upcoming, or expired
1164
+	 *
1165
+	 * @return int return value will be one of the EE_Datetime status constants.
1166
+	 * @throws ReflectionException
1167
+	 * @throws InvalidArgumentException
1168
+	 * @throws InvalidInterfaceException
1169
+	 * @throws InvalidDataTypeException
1170
+	 * @throws EE_Error
1171
+	 */
1172
+	public function get_active_status()
1173
+	{
1174
+		$total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1175
+		if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1176
+			return EE_Datetime::sold_out;
1177
+		}
1178
+		if ($this->is_expired()) {
1179
+			return EE_Datetime::expired;
1180
+		}
1181
+		if ($this->is_upcoming()) {
1182
+			return EE_Datetime::upcoming;
1183
+		}
1184
+		if ($this->is_active()) {
1185
+			return EE_Datetime::active;
1186
+		}
1187
+		return null;
1188
+	}
1189
+
1190
+
1191
+	/**
1192
+	 * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1193
+	 *
1194
+	 * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1195
+	 * @return string
1196
+	 * @throws ReflectionException
1197
+	 * @throws InvalidArgumentException
1198
+	 * @throws InvalidInterfaceException
1199
+	 * @throws InvalidDataTypeException
1200
+	 * @throws EE_Error
1201
+	 */
1202
+	public function get_dtt_display_name($use_dtt_name = false)
1203
+	{
1204
+		if ($use_dtt_name) {
1205
+			$dtt_name = $this->name();
1206
+			if (! empty($dtt_name)) {
1207
+				return $dtt_name;
1208
+			}
1209
+		}
1210
+		// first condition is to see if the months are different
1211
+		if (
1212
+			date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1213
+		) {
1214
+			$display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
+			// next condition is if its the same month but different day
1216
+		} else {
1217
+			if (
1218
+				date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1219
+				&& date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1220
+			) {
1221
+				$display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1222
+			} else {
1223
+				$display_date = $this->start_date('F j\, Y')
1224
+								. ' @ '
1225
+								. $this->start_date('g:i a')
1226
+								. ' - '
1227
+								. $this->end_date('g:i a');
1228
+			}
1229
+		}
1230
+		return $display_date;
1231
+	}
1232
+
1233
+
1234
+	/**
1235
+	 * Gets all the tickets for this datetime
1236
+	 *
1237
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1238
+	 * @return EE_Base_Class[]|EE_Ticket[]
1239
+	 * @throws ReflectionException
1240
+	 * @throws InvalidArgumentException
1241
+	 * @throws InvalidInterfaceException
1242
+	 * @throws InvalidDataTypeException
1243
+	 * @throws EE_Error
1244
+	 */
1245
+	public function tickets($query_params = array())
1246
+	{
1247
+		return $this->get_many_related('Ticket', $query_params);
1248
+	}
1249
+
1250
+
1251
+	/**
1252
+	 * Gets all the ticket types currently available for purchase
1253
+	 *
1254
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1255
+	 * @return EE_Ticket[]
1256
+	 * @throws ReflectionException
1257
+	 * @throws InvalidArgumentException
1258
+	 * @throws InvalidInterfaceException
1259
+	 * @throws InvalidDataTypeException
1260
+	 * @throws EE_Error
1261
+	 */
1262
+	public function ticket_types_available_for_purchase($query_params = array())
1263
+	{
1264
+		// first check if datetime is valid
1265
+		if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1266
+			return array();
1267
+		}
1268
+		if (empty($query_params)) {
1269
+			$query_params = array(
1270
+				array(
1271
+					'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1272
+					'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1273
+					'TKT_deleted'    => false,
1274
+				),
1275
+			);
1276
+		}
1277
+		return $this->tickets($query_params);
1278
+	}
1279
+
1280
+
1281
+	/**
1282
+	 * @return EE_Base_Class|EE_Event
1283
+	 * @throws ReflectionException
1284
+	 * @throws InvalidArgumentException
1285
+	 * @throws InvalidInterfaceException
1286
+	 * @throws InvalidDataTypeException
1287
+	 * @throws EE_Error
1288
+	 */
1289
+	public function event()
1290
+	{
1291
+		return $this->get_first_related('Event');
1292
+	}
1293
+
1294
+
1295
+	/**
1296
+	 * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1297
+	 * (via the tickets).
1298
+	 *
1299
+	 * @return int
1300
+	 * @throws ReflectionException
1301
+	 * @throws InvalidArgumentException
1302
+	 * @throws InvalidInterfaceException
1303
+	 * @throws InvalidDataTypeException
1304
+	 * @throws EE_Error
1305
+	 */
1306
+	public function update_sold()
1307
+	{
1308
+		$count_regs_for_this_datetime = EEM_Registration::instance()->count(
1309
+			array(
1310
+				array(
1311
+					'STS_ID'                 => EEM_Registration::status_id_approved,
1312
+					'REG_deleted'            => 0,
1313
+					'Ticket.Datetime.DTT_ID' => $this->ID(),
1314
+				),
1315
+			)
1316
+		);
1317
+		$this->set_sold($count_regs_for_this_datetime);
1318
+		$this->save();
1319
+		return $count_regs_for_this_datetime;
1320
+	}
1321
+
1322
+
1323
+	/*******************************************************************
1324 1324
      ***********************  DEPRECATED METHODS  **********************
1325 1325
      *******************************************************************/
1326 1326
 
1327 1327
 
1328
-    /**
1329
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
1330
-     *
1331
-     * @deprecated 4.9.80.p
1332
-     * @param int $qty
1333
-     * @return boolean
1334
-     * @throws ReflectionException
1335
-     * @throws InvalidArgumentException
1336
-     * @throws InvalidInterfaceException
1337
-     * @throws InvalidDataTypeException
1338
-     * @throws EE_Error
1339
-     */
1340
-    public function increase_sold($qty = 1)
1341
-    {
1342
-        EE_Error::doing_it_wrong(
1343
-            __FUNCTION__,
1344
-            esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1345
-            '4.9.80.p',
1346
-            '5.0.0.p'
1347
-        );
1348
-        return $this->increaseSold($qty);
1349
-    }
1350
-
1351
-
1352
-    /**
1353
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1354
-     * to save afterwards.)
1355
-     *
1356
-     * @deprecated 4.9.80.p
1357
-     * @param int $qty
1358
-     * @return boolean
1359
-     * @throws ReflectionException
1360
-     * @throws InvalidArgumentException
1361
-     * @throws InvalidInterfaceException
1362
-     * @throws InvalidDataTypeException
1363
-     * @throws EE_Error
1364
-     */
1365
-    public function decrease_sold($qty = 1)
1366
-    {
1367
-        EE_Error::doing_it_wrong(
1368
-            __FUNCTION__,
1369
-            esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1370
-            '4.9.80.p',
1371
-            '5.0.0.p'
1372
-        );
1373
-        return $this->decreaseSold($qty);
1374
-    }
1375
-
1376
-
1377
-    /**
1378
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1379
-     *
1380
-     * @deprecated 4.9.80.p
1381
-     * @param int $qty
1382
-     * @return boolean indicating success
1383
-     * @throws ReflectionException
1384
-     * @throws InvalidArgumentException
1385
-     * @throws InvalidInterfaceException
1386
-     * @throws InvalidDataTypeException
1387
-     * @throws EE_Error
1388
-     */
1389
-    public function increase_reserved($qty = 1)
1390
-    {
1391
-        EE_Error::doing_it_wrong(
1392
-            __FUNCTION__,
1393
-            esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1394
-            '4.9.80.p',
1395
-            '5.0.0.p'
1396
-        );
1397
-        return $this->increaseReserved($qty);
1398
-    }
1399
-
1400
-
1401
-    /**
1402
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1403
-     *
1404
-     * @deprecated 4.9.80.p
1405
-     * @param int $qty
1406
-     * @return boolean
1407
-     * @throws ReflectionException
1408
-     * @throws InvalidArgumentException
1409
-     * @throws InvalidInterfaceException
1410
-     * @throws InvalidDataTypeException
1411
-     * @throws EE_Error
1412
-     */
1413
-    public function decrease_reserved($qty = 1)
1414
-    {
1415
-        EE_Error::doing_it_wrong(
1416
-            __FUNCTION__,
1417
-            esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1418
-            '4.9.80.p',
1419
-            '5.0.0.p'
1420
-        );
1421
-        return $this->decreaseReserved($qty);
1422
-    }
1328
+	/**
1329
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
1330
+	 *
1331
+	 * @deprecated 4.9.80.p
1332
+	 * @param int $qty
1333
+	 * @return boolean
1334
+	 * @throws ReflectionException
1335
+	 * @throws InvalidArgumentException
1336
+	 * @throws InvalidInterfaceException
1337
+	 * @throws InvalidDataTypeException
1338
+	 * @throws EE_Error
1339
+	 */
1340
+	public function increase_sold($qty = 1)
1341
+	{
1342
+		EE_Error::doing_it_wrong(
1343
+			__FUNCTION__,
1344
+			esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1345
+			'4.9.80.p',
1346
+			'5.0.0.p'
1347
+		);
1348
+		return $this->increaseSold($qty);
1349
+	}
1350
+
1351
+
1352
+	/**
1353
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1354
+	 * to save afterwards.)
1355
+	 *
1356
+	 * @deprecated 4.9.80.p
1357
+	 * @param int $qty
1358
+	 * @return boolean
1359
+	 * @throws ReflectionException
1360
+	 * @throws InvalidArgumentException
1361
+	 * @throws InvalidInterfaceException
1362
+	 * @throws InvalidDataTypeException
1363
+	 * @throws EE_Error
1364
+	 */
1365
+	public function decrease_sold($qty = 1)
1366
+	{
1367
+		EE_Error::doing_it_wrong(
1368
+			__FUNCTION__,
1369
+			esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1370
+			'4.9.80.p',
1371
+			'5.0.0.p'
1372
+		);
1373
+		return $this->decreaseSold($qty);
1374
+	}
1375
+
1376
+
1377
+	/**
1378
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1379
+	 *
1380
+	 * @deprecated 4.9.80.p
1381
+	 * @param int $qty
1382
+	 * @return boolean indicating success
1383
+	 * @throws ReflectionException
1384
+	 * @throws InvalidArgumentException
1385
+	 * @throws InvalidInterfaceException
1386
+	 * @throws InvalidDataTypeException
1387
+	 * @throws EE_Error
1388
+	 */
1389
+	public function increase_reserved($qty = 1)
1390
+	{
1391
+		EE_Error::doing_it_wrong(
1392
+			__FUNCTION__,
1393
+			esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1394
+			'4.9.80.p',
1395
+			'5.0.0.p'
1396
+		);
1397
+		return $this->increaseReserved($qty);
1398
+	}
1399
+
1400
+
1401
+	/**
1402
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1403
+	 *
1404
+	 * @deprecated 4.9.80.p
1405
+	 * @param int $qty
1406
+	 * @return boolean
1407
+	 * @throws ReflectionException
1408
+	 * @throws InvalidArgumentException
1409
+	 * @throws InvalidInterfaceException
1410
+	 * @throws InvalidDataTypeException
1411
+	 * @throws EE_Error
1412
+	 */
1413
+	public function decrease_reserved($qty = 1)
1414
+	{
1415
+		EE_Error::doing_it_wrong(
1416
+			__FUNCTION__,
1417
+			esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1418
+			'4.9.80.p',
1419
+			'5.0.0.p'
1420
+		);
1421
+		return $this->decreaseReserved($qty);
1422
+	}
1423 1423
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Registration.class.php 2 patches
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
     {
120 120
         switch ($field_name) {
121 121
             case 'REG_code':
122
-                if (! empty($field_value) && $this->reg_code() === null) {
122
+                if ( ! empty($field_value) && $this->reg_code() === null) {
123 123
                     $this->set_reg_code($field_value, $use_default);
124 124
                 }
125 125
                 break;
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
     public function event()
407 407
     {
408 408
         $event = $this->get_first_related('Event');
409
-        if (! $event instanceof \EE_Event) {
409
+        if ( ! $event instanceof \EE_Event) {
410 410
             throw new EntityNotFoundException('Event ID', $this->event_ID());
411 411
         }
412 412
         return $event;
@@ -449,7 +449,7 @@  discard block
 block discarded – undo
449 449
     {
450 450
         // reserved ticket and datetime counts will be decremented as sold counts are incremented
451 451
         // so stop tracking that this reg has a ticket reserved
452
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
452
+        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:".__LINE__.')');
453 453
         $ticket = $this->ticket();
454 454
         $ticket->increaseSold();
455 455
         // possibly set event status to sold out
@@ -504,7 +504,7 @@  discard block
 block discarded – undo
504 504
                 && $update_ticket
505 505
             ) {
506 506
                 $ticket = $this->ticket();
507
-                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
507
+                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:".__LINE__.')');
508 508
                 $ticket->save();
509 509
             }
510 510
         }
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
                 && $update_ticket
537 537
             ) {
538 538
                 $ticket = $this->ticket();
539
-                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
539
+                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:".__LINE__.')');
540 540
             }
541 541
         }
542 542
     }
@@ -1211,7 +1211,7 @@  discard block
 block discarded – undo
1211 1211
                     : '';
1212 1212
                 break;
1213 1213
         }
1214
-        return $icon . $status[ $this->status_ID() ];
1214
+        return $icon.$status[$this->status_ID()];
1215 1215
     }
1216 1216
 
1217 1217
 
@@ -1455,7 +1455,7 @@  discard block
 block discarded – undo
1455 1455
     {
1456 1456
         $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1457 1457
 
1458
-        if (! $DTT_ID) {
1458
+        if ( ! $DTT_ID) {
1459 1459
             return false;
1460 1460
         }
1461 1461
 
@@ -1463,7 +1463,7 @@  discard block
 block discarded – undo
1463 1463
 
1464 1464
         // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1465 1465
         // check-in or not.
1466
-        if (! $max_uses || $max_uses === EE_INF) {
1466
+        if ( ! $max_uses || $max_uses === EE_INF) {
1467 1467
             return true;
1468 1468
         }
1469 1469
 
@@ -1523,7 +1523,7 @@  discard block
 block discarded – undo
1523 1523
             $datetime = $this->get_latest_related_datetime();
1524 1524
             $DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1525 1525
             // verify the registration can checkin for the given DTT_ID
1526
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1526
+        } elseif ( ! $this->can_checkin($DTT_ID, $verify)) {
1527 1527
             EE_Error::add_error(
1528 1528
                 sprintf(
1529 1529
                     esc_html__(
@@ -1546,7 +1546,7 @@  discard block
 block discarded – undo
1546 1546
         );
1547 1547
         // start by getting the current status so we know what status we'll be changing to.
1548 1548
         $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1549
-        $status_to = $status_paths[ $cur_status ];
1549
+        $status_to = $status_paths[$cur_status];
1550 1550
         // database only records true for checked IN or false for checked OUT
1551 1551
         // no record ( null ) means checked in NEVER, but we obviously don't save that
1552 1552
         $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
@@ -1714,7 +1714,7 @@  discard block
 block discarded – undo
1714 1714
     public function transaction()
1715 1715
     {
1716 1716
         $transaction = $this->get_first_related('Transaction');
1717
-        if (! $transaction instanceof \EE_Transaction) {
1717
+        if ( ! $transaction instanceof \EE_Transaction) {
1718 1718
             throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1719 1719
         }
1720 1720
         return $transaction;
@@ -1768,11 +1768,11 @@  discard block
 block discarded – undo
1768 1768
             );
1769 1769
             return;
1770 1770
         }
1771
-        if (! $this->reg_code()) {
1771
+        if ( ! $this->reg_code()) {
1772 1772
             parent::set('REG_code', $REG_code, $use_default);
1773 1773
         } else {
1774 1774
             EE_Error::doing_it_wrong(
1775
-                __CLASS__ . '::' . __FUNCTION__,
1775
+                __CLASS__.'::'.__FUNCTION__,
1776 1776
                 esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1777 1777
                 '4.6.0'
1778 1778
             );
@@ -1924,7 +1924,7 @@  discard block
 block discarded – undo
1924 1924
                 break;
1925 1925
             }
1926 1926
         }
1927
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1927
+        if ( ! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1928 1928
             throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1929 1929
         }
1930 1930
         return $line_item;
Please login to merge, or discard this patch.
Indentation   +2113 added lines, -2113 removed lines patch added patch discarded remove patch
@@ -16,2117 +16,2117 @@
 block discarded – undo
16 16
  */
17 17
 class EE_Registration extends EE_Soft_Delete_Base_Class implements EEI_Registration, EEI_Admin_Links
18 18
 {
19
-    /**
20
-     * Used to reference when a registration has never been checked in.
21
-     *
22
-     * @deprecated use \EE_Checkin::status_checked_never instead
23
-     * @type int
24
-     */
25
-    const checkin_status_never = 2;
26
-
27
-    /**
28
-     * Used to reference when a registration has been checked in.
29
-     *
30
-     * @deprecated use \EE_Checkin::status_checked_in instead
31
-     * @type int
32
-     */
33
-    const checkin_status_in = 1;
34
-
35
-
36
-    /**
37
-     * Used to reference when a registration has been checked out.
38
-     *
39
-     * @deprecated use \EE_Checkin::status_checked_out instead
40
-     * @type int
41
-     */
42
-    const checkin_status_out = 0;
43
-
44
-
45
-    /**
46
-     * extra meta key for tracking reg status os trashed registrations
47
-     *
48
-     * @type string
49
-     */
50
-    const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
51
-
52
-
53
-    /**
54
-     * extra meta key for tracking if registration has reserved ticket
55
-     *
56
-     * @type string
57
-     */
58
-    const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
59
-
60
-
61
-    /**
62
-     * @param array  $props_n_values          incoming values
63
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
64
-     *                                        used.)
65
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
66
-     *                                        date_format and the second value is the time format
67
-     * @return EE_Registration
68
-     * @throws EE_Error
69
-     */
70
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
71
-    {
72
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
73
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
74
-    }
75
-
76
-
77
-    /**
78
-     * @param array  $props_n_values  incoming values from the database
79
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
80
-     *                                the website will be used.
81
-     * @return EE_Registration
82
-     */
83
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
84
-    {
85
-        return new self($props_n_values, true, $timezone);
86
-    }
87
-
88
-
89
-    /**
90
-     *        Set Event ID
91
-     *
92
-     * @param        int $EVT_ID Event ID
93
-     * @throws EE_Error
94
-     * @throws RuntimeException
95
-     */
96
-    public function set_event($EVT_ID = 0)
97
-    {
98
-        $this->set('EVT_ID', $EVT_ID);
99
-    }
100
-
101
-
102
-    /**
103
-     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
104
-     * be routed to internal methods
105
-     *
106
-     * @param string $field_name
107
-     * @param mixed  $field_value
108
-     * @param bool   $use_default
109
-     * @throws EE_Error
110
-     * @throws EntityNotFoundException
111
-     * @throws InvalidArgumentException
112
-     * @throws InvalidDataTypeException
113
-     * @throws InvalidInterfaceException
114
-     * @throws ReflectionException
115
-     * @throws RuntimeException
116
-     */
117
-    public function set($field_name, $field_value, $use_default = false)
118
-    {
119
-        switch ($field_name) {
120
-            case 'REG_code':
121
-                if (! empty($field_value) && $this->reg_code() === null) {
122
-                    $this->set_reg_code($field_value, $use_default);
123
-                }
124
-                break;
125
-            case 'STS_ID':
126
-                $this->set_status($field_value, $use_default);
127
-                break;
128
-            default:
129
-                parent::set($field_name, $field_value, $use_default);
130
-        }
131
-    }
132
-
133
-
134
-    /**
135
-     * Set Status ID
136
-     * updates the registration status and ALSO...
137
-     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
138
-     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
139
-     *
140
-     * @param string                $new_STS_ID
141
-     * @param boolean               $use_default
142
-     * @param ContextInterface|null $context
143
-     * @return bool
144
-     * @throws DomainException
145
-     * @throws EE_Error
146
-     * @throws EntityNotFoundException
147
-     * @throws InvalidArgumentException
148
-     * @throws InvalidDataTypeException
149
-     * @throws InvalidInterfaceException
150
-     * @throws ReflectionException
151
-     * @throws RuntimeException
152
-     * @throws UnexpectedEntityException
153
-     */
154
-    public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
155
-    {
156
-        // get current REG_Status
157
-        $old_STS_ID = $this->status_ID();
158
-        // if status has changed
159
-        if (
160
-            $old_STS_ID !== $new_STS_ID // and that status has actually changed
161
-            && ! empty($old_STS_ID) // and that old status is actually set
162
-            && ! empty($new_STS_ID) // as well as the new status
163
-            && $this->ID() // ensure registration is in the db
164
-        ) {
165
-            // update internal status first
166
-            parent::set('STS_ID', $new_STS_ID, $use_default);
167
-            // THEN handle other changes that occur when reg status changes
168
-            // TO approved
169
-            if ($new_STS_ID === EEM_Registration::status_id_approved) {
170
-                // reserve a space by incrementing ticket and datetime sold values
171
-                $this->reserveRegistrationSpace();
172
-                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
173
-                // OR FROM  approved
174
-            } elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
175
-                // release a space by decrementing ticket and datetime sold values
176
-                $this->releaseRegistrationSpace();
177
-                do_action(
178
-                    'AHEE__EE_Registration__set_status__from_approved',
179
-                    $this,
180
-                    $old_STS_ID,
181
-                    $new_STS_ID,
182
-                    $context
183
-                );
184
-            }
185
-            // update status
186
-            parent::set('STS_ID', $new_STS_ID, $use_default);
187
-            $this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
188
-            if ($this->statusChangeUpdatesTransaction($context)) {
189
-                $this->updateTransactionAfterStatusChange();
190
-            }
191
-            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
192
-            return true;
193
-        }
194
-        // even though the old value matches the new value, it's still good to
195
-        // allow the parent set method to have a say
196
-        parent::set('STS_ID', $new_STS_ID, $use_default);
197
-        return true;
198
-    }
199
-
200
-
201
-    /**
202
-     * update REGs and TXN when cancelled or declined registrations involved
203
-     *
204
-     * @param string                $new_STS_ID
205
-     * @param string                $old_STS_ID
206
-     * @param ContextInterface|null $context
207
-     * @throws EE_Error
208
-     * @throws InvalidArgumentException
209
-     * @throws InvalidDataTypeException
210
-     * @throws InvalidInterfaceException
211
-     * @throws ReflectionException
212
-     * @throws RuntimeException
213
-     */
214
-    private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
215
-    {
216
-        // these reg statuses should not be considered in any calculations involving monies owing
217
-        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
218
-        // true if registration has been cancelled or declined
219
-        $this->updateIfCanceled(
220
-            $closed_reg_statuses,
221
-            $new_STS_ID,
222
-            $old_STS_ID,
223
-            $context
224
-        );
225
-        $this->updateIfReinstated(
226
-            $closed_reg_statuses,
227
-            $new_STS_ID,
228
-            $old_STS_ID,
229
-            $context
230
-        );
231
-    }
232
-
233
-
234
-    /**
235
-     * update REGs and TXN when cancelled or declined registrations involved
236
-     *
237
-     * @param array                 $closed_reg_statuses
238
-     * @param string                $new_STS_ID
239
-     * @param string                $old_STS_ID
240
-     * @param ContextInterface|null $context
241
-     * @throws EE_Error
242
-     * @throws InvalidArgumentException
243
-     * @throws InvalidDataTypeException
244
-     * @throws InvalidInterfaceException
245
-     * @throws ReflectionException
246
-     * @throws RuntimeException
247
-     */
248
-    private function updateIfCanceled(
249
-        array $closed_reg_statuses,
250
-        $new_STS_ID,
251
-        $old_STS_ID,
252
-        ContextInterface $context = null
253
-    ) {
254
-        // true if registration has been cancelled or declined
255
-        if (
256
-            in_array($new_STS_ID, $closed_reg_statuses, true)
257
-            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
258
-        ) {
259
-            /** @type EE_Registration_Processor $registration_processor */
260
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
261
-            /** @type EE_Transaction_Processor $transaction_processor */
262
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
263
-            // cancelled or declined registration
264
-            $registration_processor->update_registration_after_being_canceled_or_declined(
265
-                $this,
266
-                $closed_reg_statuses
267
-            );
268
-            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
269
-                $this,
270
-                $closed_reg_statuses,
271
-                false
272
-            );
273
-            do_action(
274
-                'AHEE__EE_Registration__set_status__canceled_or_declined',
275
-                $this,
276
-                $old_STS_ID,
277
-                $new_STS_ID,
278
-                $context
279
-            );
280
-            return;
281
-        }
282
-    }
283
-
284
-
285
-    /**
286
-     * update REGs and TXN when cancelled or declined registrations involved
287
-     *
288
-     * @param array                 $closed_reg_statuses
289
-     * @param string                $new_STS_ID
290
-     * @param string                $old_STS_ID
291
-     * @param ContextInterface|null $context
292
-     * @throws EE_Error
293
-     * @throws InvalidArgumentException
294
-     * @throws InvalidDataTypeException
295
-     * @throws InvalidInterfaceException
296
-     * @throws ReflectionException
297
-     */
298
-    private function updateIfReinstated(
299
-        array $closed_reg_statuses,
300
-        $new_STS_ID,
301
-        $old_STS_ID,
302
-        ContextInterface $context = null
303
-    ) {
304
-        // true if reinstating cancelled or declined registration
305
-        if (
306
-            in_array($old_STS_ID, $closed_reg_statuses, true)
307
-            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
308
-        ) {
309
-            /** @type EE_Registration_Processor $registration_processor */
310
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
311
-            /** @type EE_Transaction_Processor $transaction_processor */
312
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
313
-            // reinstating cancelled or declined registration
314
-            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
315
-                $this,
316
-                $closed_reg_statuses
317
-            );
318
-            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
319
-                $this,
320
-                $closed_reg_statuses,
321
-                false
322
-            );
323
-            do_action(
324
-                'AHEE__EE_Registration__set_status__after_reinstated',
325
-                $this,
326
-                $old_STS_ID,
327
-                $new_STS_ID,
328
-                $context
329
-            );
330
-        }
331
-    }
332
-
333
-
334
-    /**
335
-     * @param ContextInterface|null $context
336
-     * @return bool
337
-     */
338
-    private function statusChangeUpdatesTransaction(ContextInterface $context = null)
339
-    {
340
-        $contexts_that_do_not_update_transaction = (array) apply_filters(
341
-            'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
342
-            array('spco_reg_step_attendee_information_process_registrations'),
343
-            $context,
344
-            $this
345
-        );
346
-        return ! (
347
-            $context instanceof ContextInterface
348
-            && in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
349
-        );
350
-    }
351
-
352
-
353
-    /**
354
-     * @throws EE_Error
355
-     * @throws EntityNotFoundException
356
-     * @throws InvalidArgumentException
357
-     * @throws InvalidDataTypeException
358
-     * @throws InvalidInterfaceException
359
-     * @throws ReflectionException
360
-     * @throws RuntimeException
361
-     */
362
-    private function updateTransactionAfterStatusChange()
363
-    {
364
-        /** @type EE_Transaction_Payments $transaction_payments */
365
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
366
-        $transaction_payments->recalculate_transaction_total($this->transaction(), false);
367
-        $this->transaction()->update_status_based_on_total_paid(true);
368
-    }
369
-
370
-
371
-    /**
372
-     *        get Status ID
373
-     */
374
-    public function status_ID()
375
-    {
376
-        return $this->get('STS_ID');
377
-    }
378
-
379
-
380
-    /**
381
-     * Gets the ticket this registration is for
382
-     *
383
-     * @param boolean $include_archived whether to include archived tickets or not.
384
-     *
385
-     * @return EE_Ticket|EE_Base_Class
386
-     * @throws EE_Error
387
-     */
388
-    public function ticket($include_archived = true)
389
-    {
390
-        $query_params = array();
391
-        if ($include_archived) {
392
-            $query_params['default_where_conditions'] = 'none';
393
-        }
394
-        return $this->get_first_related('Ticket', $query_params);
395
-    }
396
-
397
-
398
-    /**
399
-     * Gets the event this registration is for
400
-     *
401
-     * @return EE_Event
402
-     * @throws EE_Error
403
-     * @throws EntityNotFoundException
404
-     */
405
-    public function event()
406
-    {
407
-        $event = $this->get_first_related('Event');
408
-        if (! $event instanceof \EE_Event) {
409
-            throw new EntityNotFoundException('Event ID', $this->event_ID());
410
-        }
411
-        return $event;
412
-    }
413
-
414
-
415
-    /**
416
-     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
417
-     * with the author of the event this registration is for.
418
-     *
419
-     * @since 4.5.0
420
-     * @return int
421
-     * @throws EE_Error
422
-     * @throws EntityNotFoundException
423
-     */
424
-    public function wp_user()
425
-    {
426
-        $event = $this->event();
427
-        if ($event instanceof EE_Event) {
428
-            return $event->wp_user();
429
-        }
430
-        return 0;
431
-    }
432
-
433
-
434
-    /**
435
-     * increments this registration's related ticket sold and corresponding datetime sold values
436
-     *
437
-     * @return void
438
-     * @throws DomainException
439
-     * @throws EE_Error
440
-     * @throws EntityNotFoundException
441
-     * @throws InvalidArgumentException
442
-     * @throws InvalidDataTypeException
443
-     * @throws InvalidInterfaceException
444
-     * @throws ReflectionException
445
-     * @throws UnexpectedEntityException
446
-     */
447
-    private function reserveRegistrationSpace()
448
-    {
449
-        // reserved ticket and datetime counts will be decremented as sold counts are incremented
450
-        // so stop tracking that this reg has a ticket reserved
451
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
452
-        $ticket = $this->ticket();
453
-        $ticket->increaseSold();
454
-        // possibly set event status to sold out
455
-        $this->event()->perform_sold_out_status_check();
456
-    }
457
-
458
-
459
-    /**
460
-     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
461
-     *
462
-     * @return void
463
-     * @throws DomainException
464
-     * @throws EE_Error
465
-     * @throws EntityNotFoundException
466
-     * @throws InvalidArgumentException
467
-     * @throws InvalidDataTypeException
468
-     * @throws InvalidInterfaceException
469
-     * @throws ReflectionException
470
-     * @throws UnexpectedEntityException
471
-     */
472
-    private function releaseRegistrationSpace()
473
-    {
474
-        $ticket = $this->ticket();
475
-        $ticket->decreaseSold();
476
-        // possibly change event status from sold out back to previous status
477
-        $this->event()->perform_sold_out_status_check();
478
-    }
479
-
480
-
481
-    /**
482
-     * tracks this registration's ticket reservation in extra meta
483
-     * and can increment related ticket reserved and corresponding datetime reserved values
484
-     *
485
-     * @param bool $update_ticket if true, will increment ticket and datetime reserved count
486
-     * @return void
487
-     * @throws EE_Error
488
-     * @throws InvalidArgumentException
489
-     * @throws InvalidDataTypeException
490
-     * @throws InvalidInterfaceException
491
-     * @throws ReflectionException
492
-     */
493
-    public function reserve_ticket($update_ticket = false, $source = 'unknown')
494
-    {
495
-        // only reserve ticket if space is not currently reserved
496
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
497
-            $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
498
-            // IMPORTANT !!!
499
-            // although checking $update_ticket first would be more efficient,
500
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
501
-            if (
502
-                $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
503
-                && $update_ticket
504
-            ) {
505
-                $ticket = $this->ticket();
506
-                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
507
-                $ticket->save();
508
-            }
509
-        }
510
-    }
511
-
512
-
513
-    /**
514
-     * stops tracking this registration's ticket reservation in extra meta
515
-     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
516
-     *
517
-     * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
518
-     * @return void
519
-     * @throws EE_Error
520
-     * @throws InvalidArgumentException
521
-     * @throws InvalidDataTypeException
522
-     * @throws InvalidInterfaceException
523
-     * @throws ReflectionException
524
-     */
525
-    public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
526
-    {
527
-        // only release ticket if space is currently reserved
528
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
529
-            $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
530
-            // IMPORTANT !!!
531
-            // although checking $update_ticket first would be more efficient,
532
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
533
-            if (
534
-                $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
535
-                && $update_ticket
536
-            ) {
537
-                $ticket = $this->ticket();
538
-                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
539
-            }
540
-        }
541
-    }
542
-
543
-
544
-    /**
545
-     * Set Attendee ID
546
-     *
547
-     * @param        int $ATT_ID Attendee ID
548
-     * @throws EE_Error
549
-     * @throws RuntimeException
550
-     */
551
-    public function set_attendee_id($ATT_ID = 0)
552
-    {
553
-        $this->set('ATT_ID', $ATT_ID);
554
-    }
555
-
556
-
557
-    /**
558
-     *        Set Transaction ID
559
-     *
560
-     * @param        int $TXN_ID Transaction ID
561
-     * @throws EE_Error
562
-     * @throws RuntimeException
563
-     */
564
-    public function set_transaction_id($TXN_ID = 0)
565
-    {
566
-        $this->set('TXN_ID', $TXN_ID);
567
-    }
568
-
569
-
570
-    /**
571
-     *        Set Session
572
-     *
573
-     * @param    string $REG_session PHP Session ID
574
-     * @throws EE_Error
575
-     * @throws RuntimeException
576
-     */
577
-    public function set_session($REG_session = '')
578
-    {
579
-        $this->set('REG_session', $REG_session);
580
-    }
581
-
582
-
583
-    /**
584
-     *        Set Registration URL Link
585
-     *
586
-     * @param    string $REG_url_link Registration URL Link
587
-     * @throws EE_Error
588
-     * @throws RuntimeException
589
-     */
590
-    public function set_reg_url_link($REG_url_link = '')
591
-    {
592
-        $this->set('REG_url_link', $REG_url_link);
593
-    }
594
-
595
-
596
-    /**
597
-     *        Set Attendee Counter
598
-     *
599
-     * @param        int $REG_count Primary Attendee
600
-     * @throws EE_Error
601
-     * @throws RuntimeException
602
-     */
603
-    public function set_count($REG_count = 1)
604
-    {
605
-        $this->set('REG_count', $REG_count);
606
-    }
607
-
608
-
609
-    /**
610
-     *        Set Group Size
611
-     *
612
-     * @param        boolean $REG_group_size Group Registration
613
-     * @throws EE_Error
614
-     * @throws RuntimeException
615
-     */
616
-    public function set_group_size($REG_group_size = false)
617
-    {
618
-        $this->set('REG_group_size', $REG_group_size);
619
-    }
620
-
621
-
622
-    /**
623
-     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
624
-     *    EEM_Registration::status_id_not_approved
625
-     *
626
-     * @return        boolean
627
-     */
628
-    public function is_not_approved()
629
-    {
630
-        return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
631
-    }
632
-
633
-
634
-    /**
635
-     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
636
-     *    EEM_Registration::status_id_pending_payment
637
-     *
638
-     * @return        boolean
639
-     */
640
-    public function is_pending_payment()
641
-    {
642
-        return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
643
-    }
644
-
645
-
646
-    /**
647
-     *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
648
-     *
649
-     * @return        boolean
650
-     */
651
-    public function is_approved()
652
-    {
653
-        return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
654
-    }
655
-
656
-
657
-    /**
658
-     *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
659
-     *
660
-     * @return        boolean
661
-     */
662
-    public function is_cancelled()
663
-    {
664
-        return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
665
-    }
666
-
667
-
668
-    /**
669
-     *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
670
-     *
671
-     * @return        boolean
672
-     */
673
-    public function is_declined()
674
-    {
675
-        return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
676
-    }
677
-
678
-
679
-    /**
680
-     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
681
-     *    EEM_Registration::status_id_incomplete
682
-     *
683
-     * @return        boolean
684
-     */
685
-    public function is_incomplete()
686
-    {
687
-        return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
688
-    }
689
-
690
-
691
-    /**
692
-     *        Set Registration Date
693
-     *
694
-     * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
695
-     *                                                 Date
696
-     * @throws EE_Error
697
-     * @throws RuntimeException
698
-     */
699
-    public function set_reg_date($REG_date = false)
700
-    {
701
-        $this->set('REG_date', $REG_date);
702
-    }
703
-
704
-
705
-    /**
706
-     *    Set final price owing for this registration after all ticket/price modifications
707
-     *
708
-     * @access    public
709
-     * @param    float $REG_final_price
710
-     * @throws EE_Error
711
-     * @throws RuntimeException
712
-     */
713
-    public function set_final_price($REG_final_price = 0.00)
714
-    {
715
-        $this->set('REG_final_price', $REG_final_price);
716
-    }
717
-
718
-
719
-    /**
720
-     *    Set amount paid towards this registration's final price
721
-     *
722
-     * @access    public
723
-     * @param    float $REG_paid
724
-     * @throws EE_Error
725
-     * @throws RuntimeException
726
-     */
727
-    public function set_paid($REG_paid = 0.00)
728
-    {
729
-        $this->set('REG_paid', $REG_paid);
730
-    }
731
-
732
-
733
-    /**
734
-     *        Attendee Is Going
735
-     *
736
-     * @param        boolean $REG_att_is_going Attendee Is Going
737
-     * @throws EE_Error
738
-     * @throws RuntimeException
739
-     */
740
-    public function set_att_is_going($REG_att_is_going = false)
741
-    {
742
-        $this->set('REG_att_is_going', $REG_att_is_going);
743
-    }
744
-
745
-
746
-    /**
747
-     * Gets the related attendee
748
-     *
749
-     * @return EE_Attendee
750
-     * @throws EE_Error
751
-     */
752
-    public function attendee()
753
-    {
754
-        return $this->get_first_related('Attendee');
755
-    }
756
-
757
-    /**
758
-     * Gets the name of the attendee.
759
-     * @since 4.10.12.p
760
-     * @param bool $apply_html_entities set to true if you want to use HTML entities.
761
-     * @return string
762
-     * @throws EE_Error
763
-     * @throws InvalidArgumentException
764
-     * @throws InvalidDataTypeException
765
-     * @throws InvalidInterfaceException
766
-     * @throws ReflectionException
767
-     */
768
-    public function attendeeName($apply_html_entities = false)
769
-    {
770
-        $attendee = $this->get_first_related('Attendee');
771
-        if ($attendee instanceof EE_Attendee) {
772
-            $attendee_name = $attendee->full_name($apply_html_entities);
773
-        } else {
774
-            $attendee_name = esc_html__('Unknown', 'event_espresso');
775
-        }
776
-        return $attendee_name;
777
-    }
778
-
779
-
780
-    /**
781
-     *        get Event ID
782
-     */
783
-    public function event_ID()
784
-    {
785
-        return $this->get('EVT_ID');
786
-    }
787
-
788
-
789
-    /**
790
-     *        get Event ID
791
-     */
792
-    public function event_name()
793
-    {
794
-        $event = $this->event_obj();
795
-        if ($event) {
796
-            return $event->name();
797
-        } else {
798
-            return null;
799
-        }
800
-    }
801
-
802
-
803
-    /**
804
-     * Fetches the event this registration is for
805
-     *
806
-     * @return EE_Event
807
-     * @throws EE_Error
808
-     */
809
-    public function event_obj()
810
-    {
811
-        return $this->get_first_related('Event');
812
-    }
813
-
814
-
815
-    /**
816
-     *        get Attendee ID
817
-     */
818
-    public function attendee_ID()
819
-    {
820
-        return $this->get('ATT_ID');
821
-    }
822
-
823
-
824
-    /**
825
-     *        get PHP Session ID
826
-     */
827
-    public function session_ID()
828
-    {
829
-        return $this->get('REG_session');
830
-    }
831
-
832
-
833
-    /**
834
-     * Gets the string which represents the URL trigger for the receipt template in the message template system.
835
-     *
836
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
837
-     * @return string
838
-     */
839
-    public function receipt_url($messenger = 'html')
840
-    {
841
-
842
-        /**
843
-         * The below will be deprecated one version after this.  We check first if there is a custom receipt template
844
-         * already in use on old system.  If there is then we just return the standard url for it.
845
-         *
846
-         * @since 4.5.0
847
-         */
848
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
849
-        $has_custom = EEH_Template::locate_template(
850
-            $template_relative_path,
851
-            array(),
852
-            true,
853
-            true,
854
-            true
855
-        );
856
-
857
-        if ($has_custom) {
858
-            return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
859
-        }
860
-        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
861
-    }
862
-
863
-
864
-    /**
865
-     * Gets the string which represents the URL trigger for the invoice template in the message template system.
866
-     *
867
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
868
-     * @return string
869
-     * @throws EE_Error
870
-     */
871
-    public function invoice_url($messenger = 'html')
872
-    {
873
-        /**
874
-         * The below will be deprecated one version after this.  We check first if there is a custom invoice template
875
-         * already in use on old system.  If there is then we just return the standard url for it.
876
-         *
877
-         * @since 4.5.0
878
-         */
879
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
880
-        $has_custom = EEH_Template::locate_template(
881
-            $template_relative_path,
882
-            array(),
883
-            true,
884
-            true,
885
-            true
886
-        );
887
-
888
-        if ($has_custom) {
889
-            if ($messenger == 'html') {
890
-                return $this->invoice_url('launch');
891
-            }
892
-            $route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
893
-
894
-            $query_args = array('ee' => $route, 'id' => $this->reg_url_link());
895
-            if ($messenger == 'html') {
896
-                $query_args['html'] = true;
897
-            }
898
-            return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
899
-        }
900
-        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
901
-    }
902
-
903
-
904
-    /**
905
-     * get Registration URL Link
906
-     *
907
-     * @access public
908
-     * @return string
909
-     * @throws EE_Error
910
-     */
911
-    public function reg_url_link()
912
-    {
913
-        return (string) $this->get('REG_url_link');
914
-    }
915
-
916
-
917
-    /**
918
-     * Echoes out invoice_url()
919
-     *
920
-     * @param string $type 'download','launch', or 'html' (default is 'launch')
921
-     * @return void
922
-     * @throws EE_Error
923
-     */
924
-    public function e_invoice_url($type = 'launch')
925
-    {
926
-        echo esc_url_raw($this->invoice_url($type));
927
-    }
928
-
929
-
930
-    /**
931
-     * Echoes out payment_overview_url
932
-     */
933
-    public function e_payment_overview_url()
934
-    {
935
-        echo esc_url_raw($this->payment_overview_url());
936
-    }
937
-
938
-
939
-    /**
940
-     * Gets the URL for the checkout payment options reg step
941
-     * with this registration's REG_url_link added as a query parameter
942
-     *
943
-     * @param bool $clear_session Set to true when you want to clear the session on revisiting the
944
-     *                            payment overview url.
945
-     * @return string
946
-     * @throws InvalidInterfaceException
947
-     * @throws InvalidDataTypeException
948
-     * @throws EE_Error
949
-     * @throws InvalidArgumentException
950
-     */
951
-    public function payment_overview_url($clear_session = false)
952
-    {
953
-        return add_query_arg(
954
-            (array) apply_filters(
955
-                'FHEE__EE_Registration__payment_overview_url__query_args',
956
-                array(
957
-                    'e_reg_url_link' => $this->reg_url_link(),
958
-                    'step'           => 'payment_options',
959
-                    'revisit'        => true,
960
-                    'clear_session'  => (bool) $clear_session,
961
-                ),
962
-                $this
963
-            ),
964
-            EE_Registry::instance()->CFG->core->reg_page_url()
965
-        );
966
-    }
967
-
968
-
969
-    /**
970
-     * Gets the URL for the checkout attendee information reg step
971
-     * with this registration's REG_url_link added as a query parameter
972
-     *
973
-     * @return string
974
-     * @throws InvalidInterfaceException
975
-     * @throws InvalidDataTypeException
976
-     * @throws EE_Error
977
-     * @throws InvalidArgumentException
978
-     */
979
-    public function edit_attendee_information_url()
980
-    {
981
-        return add_query_arg(
982
-            (array) apply_filters(
983
-                'FHEE__EE_Registration__edit_attendee_information_url__query_args',
984
-                array(
985
-                    'e_reg_url_link' => $this->reg_url_link(),
986
-                    'step'           => 'attendee_information',
987
-                    'revisit'        => true,
988
-                ),
989
-                $this
990
-            ),
991
-            EE_Registry::instance()->CFG->core->reg_page_url()
992
-        );
993
-    }
994
-
995
-
996
-    /**
997
-     * Simply generates and returns the appropriate admin_url link to edit this registration
998
-     *
999
-     * @return string
1000
-     * @throws EE_Error
1001
-     */
1002
-    public function get_admin_edit_url()
1003
-    {
1004
-        return EEH_URL::add_query_args_and_nonce(
1005
-            array(
1006
-                'page'    => 'espresso_registrations',
1007
-                'action'  => 'view_registration',
1008
-                '_REG_ID' => $this->ID(),
1009
-            ),
1010
-            admin_url('admin.php')
1011
-        );
1012
-    }
1013
-
1014
-
1015
-    /**
1016
-     *    is_primary_registrant?
1017
-     */
1018
-    public function is_primary_registrant()
1019
-    {
1020
-        return $this->get('REG_count') === 1 ? true : false;
1021
-    }
1022
-
1023
-
1024
-    /**
1025
-     * This returns the primary registration object for this registration group (which may be this object).
1026
-     *
1027
-     * @return EE_Registration
1028
-     * @throws EE_Error
1029
-     */
1030
-    public function get_primary_registration()
1031
-    {
1032
-        if ($this->is_primary_registrant()) {
1033
-            return $this;
1034
-        }
1035
-
1036
-        // k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1037
-        /** @var EE_Registration $primary_registrant */
1038
-        $primary_registrant = EEM_Registration::instance()->get_one(
1039
-            array(
1040
-                array(
1041
-                    'TXN_ID'    => $this->transaction_ID(),
1042
-                    'REG_count' => 1,
1043
-                ),
1044
-            )
1045
-        );
1046
-        return $primary_registrant;
1047
-    }
1048
-
1049
-
1050
-    /**
1051
-     *        get  Attendee Number
1052
-     *
1053
-     * @access        public
1054
-     */
1055
-    public function count()
1056
-    {
1057
-        return $this->get('REG_count');
1058
-    }
1059
-
1060
-
1061
-    /**
1062
-     *        get Group Size
1063
-     */
1064
-    public function group_size()
1065
-    {
1066
-        return $this->get('REG_group_size');
1067
-    }
1068
-
1069
-
1070
-    /**
1071
-     *        get Registration Date
1072
-     */
1073
-    public function date()
1074
-    {
1075
-        return $this->get('REG_date');
1076
-    }
1077
-
1078
-
1079
-    /**
1080
-     * gets a pretty date
1081
-     *
1082
-     * @param string $date_format
1083
-     * @param string $time_format
1084
-     * @return string
1085
-     * @throws EE_Error
1086
-     */
1087
-    public function pretty_date($date_format = null, $time_format = null)
1088
-    {
1089
-        return $this->get_datetime('REG_date', $date_format, $time_format);
1090
-    }
1091
-
1092
-
1093
-    /**
1094
-     * final_price
1095
-     * the registration's share of the transaction total, so that the
1096
-     * sum of all the transaction's REG_final_prices equal the transaction's total
1097
-     *
1098
-     * @return float
1099
-     * @throws EE_Error
1100
-     */
1101
-    public function final_price()
1102
-    {
1103
-        return $this->get('REG_final_price');
1104
-    }
1105
-
1106
-
1107
-    /**
1108
-     * pretty_final_price
1109
-     *  final price as formatted string, with correct decimal places and currency symbol
1110
-     *
1111
-     * @return string
1112
-     * @throws EE_Error
1113
-     */
1114
-    public function pretty_final_price()
1115
-    {
1116
-        return $this->get_pretty('REG_final_price');
1117
-    }
1118
-
1119
-
1120
-    /**
1121
-     * get paid (yeah)
1122
-     *
1123
-     * @return float
1124
-     * @throws EE_Error
1125
-     */
1126
-    public function paid()
1127
-    {
1128
-        return $this->get('REG_paid');
1129
-    }
1130
-
1131
-
1132
-    /**
1133
-     * pretty_paid
1134
-     *
1135
-     * @return float
1136
-     * @throws EE_Error
1137
-     */
1138
-    public function pretty_paid()
1139
-    {
1140
-        return $this->get_pretty('REG_paid');
1141
-    }
1142
-
1143
-
1144
-    /**
1145
-     * owes_monies_and_can_pay
1146
-     * whether or not this registration has monies owing and it's' status allows payment
1147
-     *
1148
-     * @param array $requires_payment
1149
-     * @return bool
1150
-     * @throws EE_Error
1151
-     */
1152
-    public function owes_monies_and_can_pay($requires_payment = array())
1153
-    {
1154
-        // these reg statuses require payment (if event is not free)
1155
-        $requires_payment = ! empty($requires_payment)
1156
-            ? $requires_payment
1157
-            : EEM_Registration::reg_statuses_that_allow_payment();
1158
-        if (
1159
-            in_array($this->status_ID(), $requires_payment) &&
1160
-            $this->final_price() != 0 &&
1161
-            $this->final_price() != $this->paid()
1162
-        ) {
1163
-            return true;
1164
-        } else {
1165
-            return false;
1166
-        }
1167
-    }
1168
-
1169
-
1170
-    /**
1171
-     * Prints out the return value of $this->pretty_status()
1172
-     *
1173
-     * @param bool $show_icons
1174
-     * @return void
1175
-     * @throws EE_Error
1176
-     */
1177
-    public function e_pretty_status($show_icons = false)
1178
-    {
1179
-        echo wp_kses($this->pretty_status($show_icons), AllowedTags::getAllowedTags());
1180
-    }
1181
-
1182
-
1183
-    /**
1184
-     * Returns a nice version of the status for displaying to customers
1185
-     *
1186
-     * @param bool $show_icons
1187
-     * @return string
1188
-     * @throws EE_Error
1189
-     */
1190
-    public function pretty_status($show_icons = false)
1191
-    {
1192
-        $status = EEM_Status::instance()->localized_status(
1193
-            array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1194
-            false,
1195
-            'sentence'
1196
-        );
1197
-        $icon = '';
1198
-        switch ($this->status_ID()) {
1199
-            case EEM_Registration::status_id_approved:
1200
-                $icon = $show_icons
1201
-                    ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1202
-                    : '';
1203
-                break;
1204
-            case EEM_Registration::status_id_pending_payment:
1205
-                $icon = $show_icons
1206
-                    ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1207
-                    : '';
1208
-                break;
1209
-            case EEM_Registration::status_id_not_approved:
1210
-                $icon = $show_icons
1211
-                    ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1212
-                    : '';
1213
-                break;
1214
-            case EEM_Registration::status_id_cancelled:
1215
-                $icon = $show_icons
1216
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1217
-                    : '';
1218
-                break;
1219
-            case EEM_Registration::status_id_incomplete:
1220
-                $icon = $show_icons
1221
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1222
-                    : '';
1223
-                break;
1224
-            case EEM_Registration::status_id_declined:
1225
-                $icon = $show_icons
1226
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1227
-                    : '';
1228
-                break;
1229
-            case EEM_Registration::status_id_wait_list:
1230
-                $icon = $show_icons
1231
-                    ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1232
-                    : '';
1233
-                break;
1234
-        }
1235
-        return $icon . $status[ $this->status_ID() ];
1236
-    }
1237
-
1238
-
1239
-    /**
1240
-     *        get Attendee Is Going
1241
-     */
1242
-    public function att_is_going()
1243
-    {
1244
-        return $this->get('REG_att_is_going');
1245
-    }
1246
-
1247
-
1248
-    /**
1249
-     * Gets related answers
1250
-     *
1251
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1252
-     * @return EE_Answer[]
1253
-     * @throws EE_Error
1254
-     */
1255
-    public function answers($query_params = null)
1256
-    {
1257
-        return $this->get_many_related('Answer', $query_params);
1258
-    }
1259
-
1260
-
1261
-    /**
1262
-     * Gets the registration's answer value to the specified question
1263
-     * (either the question's ID or a question object)
1264
-     *
1265
-     * @param EE_Question|int $question
1266
-     * @param bool            $pretty_value
1267
-     * @return array|string if pretty_value= true, the result will always be a string
1268
-     * (because the answer might be an array of answer values, so passing pretty_value=true
1269
-     * will convert it into some kind of string)
1270
-     * @throws EE_Error
1271
-     */
1272
-    public function answer_value_to_question($question, $pretty_value = true)
1273
-    {
1274
-        $question_id = EEM_Question::instance()->ensure_is_ID($question);
1275
-        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * question_groups
1281
-     * returns an array of EE_Question_Group objects for this registration
1282
-     *
1283
-     * @return EE_Question_Group[]
1284
-     * @throws EE_Error
1285
-     * @throws InvalidArgumentException
1286
-     * @throws InvalidDataTypeException
1287
-     * @throws InvalidInterfaceException
1288
-     * @throws ReflectionException
1289
-     */
1290
-    public function question_groups()
1291
-    {
1292
-        return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1293
-    }
1294
-
1295
-
1296
-    /**
1297
-     * count_question_groups
1298
-     * returns a count of the number of EE_Question_Group objects for this registration
1299
-     *
1300
-     * @return int
1301
-     * @throws EE_Error
1302
-     * @throws EntityNotFoundException
1303
-     * @throws InvalidArgumentException
1304
-     * @throws InvalidDataTypeException
1305
-     * @throws InvalidInterfaceException
1306
-     * @throws ReflectionException
1307
-     */
1308
-    public function count_question_groups()
1309
-    {
1310
-        return EEM_Event::instance()->count_related(
1311
-            $this->event_ID(),
1312
-            'Question_Group',
1313
-            [
1314
-                [
1315
-                    'Event_Question_Group.'
1316
-                    . EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1317
-                ]
1318
-            ]
1319
-        );
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * Returns the registration date in the 'standard' string format
1325
-     * (function may be improved in the future to allow for different formats and timezones)
1326
-     *
1327
-     * @return string
1328
-     * @throws EE_Error
1329
-     */
1330
-    public function reg_date()
1331
-    {
1332
-        return $this->get_datetime('REG_date');
1333
-    }
1334
-
1335
-
1336
-    /**
1337
-     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1338
-     * the ticket this registration purchased, or the datetime they have registered
1339
-     * to attend)
1340
-     *
1341
-     * @return EE_Datetime_Ticket
1342
-     * @throws EE_Error
1343
-     */
1344
-    public function datetime_ticket()
1345
-    {
1346
-        return $this->get_first_related('Datetime_Ticket');
1347
-    }
1348
-
1349
-
1350
-    /**
1351
-     * Sets the registration's datetime_ticket.
1352
-     *
1353
-     * @param EE_Datetime_Ticket $datetime_ticket
1354
-     * @return EE_Datetime_Ticket
1355
-     * @throws EE_Error
1356
-     */
1357
-    public function set_datetime_ticket($datetime_ticket)
1358
-    {
1359
-        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1360
-    }
1361
-
1362
-    /**
1363
-     * Gets deleted
1364
-     *
1365
-     * @return bool
1366
-     * @throws EE_Error
1367
-     */
1368
-    public function deleted()
1369
-    {
1370
-        return $this->get('REG_deleted');
1371
-    }
1372
-
1373
-    /**
1374
-     * Sets deleted
1375
-     *
1376
-     * @param boolean $deleted
1377
-     * @return bool
1378
-     * @throws EE_Error
1379
-     * @throws RuntimeException
1380
-     */
1381
-    public function set_deleted($deleted)
1382
-    {
1383
-        if ($deleted) {
1384
-            $this->delete();
1385
-        } else {
1386
-            $this->restore();
1387
-        }
1388
-    }
1389
-
1390
-
1391
-    /**
1392
-     * Get the status object of this object
1393
-     *
1394
-     * @return EE_Status
1395
-     * @throws EE_Error
1396
-     */
1397
-    public function status_obj()
1398
-    {
1399
-        return $this->get_first_related('Status');
1400
-    }
1401
-
1402
-
1403
-    /**
1404
-     * Returns the number of times this registration has checked into any of the datetimes
1405
-     * its available for
1406
-     *
1407
-     * @return int
1408
-     * @throws EE_Error
1409
-     */
1410
-    public function count_checkins()
1411
-    {
1412
-        return $this->get_model()->count_related($this, 'Checkin');
1413
-    }
1414
-
1415
-
1416
-    /**
1417
-     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1418
-     * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1419
-     *
1420
-     * @return int
1421
-     * @throws EE_Error
1422
-     */
1423
-    public function count_checkins_not_checkedout()
1424
-    {
1425
-        return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1426
-    }
1427
-
1428
-
1429
-    /**
1430
-     * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1431
-     *
1432
-     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1433
-     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1434
-     *                                          consider registration status as well as datetime access.
1435
-     * @return bool
1436
-     * @throws EE_Error
1437
-     */
1438
-    public function can_checkin($DTT_OR_ID, $check_approved = true)
1439
-    {
1440
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1441
-
1442
-        // first check registration status
1443
-        if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1444
-            return false;
1445
-        }
1446
-        // is there a datetime ticket that matches this dtt_ID?
1447
-        if (
1448
-            ! (EEM_Datetime_Ticket::instance()->exists(
1449
-                array(
1450
-                array(
1451
-                    'TKT_ID' => $this->get('TKT_ID'),
1452
-                    'DTT_ID' => $DTT_ID,
1453
-                ),
1454
-                )
1455
-            ))
1456
-        ) {
1457
-            return false;
1458
-        }
1459
-
1460
-        // final check is against TKT_uses
1461
-        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1462
-    }
1463
-
1464
-
1465
-    /**
1466
-     * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1467
-     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1468
-     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1469
-     * then return false.  Otherwise return true.
1470
-     *
1471
-     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1472
-     * @return bool true means can checkin.  false means cannot checkin.
1473
-     * @throws EE_Error
1474
-     */
1475
-    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1476
-    {
1477
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1478
-
1479
-        if (! $DTT_ID) {
1480
-            return false;
1481
-        }
1482
-
1483
-        $max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1484
-
1485
-        // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1486
-        // check-in or not.
1487
-        if (! $max_uses || $max_uses === EE_INF) {
1488
-            return true;
1489
-        }
1490
-
1491
-        // does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1492
-        // go ahead and toggle.
1493
-        if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1494
-            return true;
1495
-        }
1496
-
1497
-        // made it here so the last check is whether the number of checkins per unique datetime on this registration
1498
-        // disallows further check-ins.
1499
-        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1500
-            array(
1501
-                array(
1502
-                    'REG_ID' => $this->ID(),
1503
-                    'CHK_in' => true,
1504
-                ),
1505
-            ),
1506
-            'DTT_ID',
1507
-            true
1508
-        );
1509
-        // checkins have already reached their max number of uses
1510
-        // so registrant can NOT checkin
1511
-        if ($count_unique_dtt_checkins >= $max_uses) {
1512
-            EE_Error::add_error(
1513
-                esc_html__(
1514
-                    'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1515
-                    'event_espresso'
1516
-                ),
1517
-                __FILE__,
1518
-                __FUNCTION__,
1519
-                __LINE__
1520
-            );
1521
-            return false;
1522
-        }
1523
-        return true;
1524
-    }
1525
-
1526
-
1527
-    /**
1528
-     * toggle Check-in status for this registration
1529
-     * Check-ins are toggled in the following order:
1530
-     * never checked in -> checked in
1531
-     * checked in -> checked out
1532
-     * checked out -> checked in
1533
-     *
1534
-     * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1535
-     *                      If not included or null, then it is assumed latest datetime is being toggled.
1536
-     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1537
-     *                      can be checked in or not.  Otherwise this forces change in checkin status.
1538
-     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1539
-     * @throws EE_Error
1540
-     */
1541
-    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1542
-    {
1543
-        if (empty($DTT_ID)) {
1544
-            $datetime = $this->get_latest_related_datetime();
1545
-            $DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1546
-            // verify the registration can checkin for the given DTT_ID
1547
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1548
-            EE_Error::add_error(
1549
-                sprintf(
1550
-                    esc_html__(
1551
-                        'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1552
-                        'event_espresso'
1553
-                    ),
1554
-                    $this->ID(),
1555
-                    $DTT_ID
1556
-                ),
1557
-                __FILE__,
1558
-                __FUNCTION__,
1559
-                __LINE__
1560
-            );
1561
-            return false;
1562
-        }
1563
-        $status_paths = array(
1564
-            EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1565
-            EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1566
-            EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1567
-        );
1568
-        // start by getting the current status so we know what status we'll be changing to.
1569
-        $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1570
-        $status_to = $status_paths[ $cur_status ];
1571
-        // database only records true for checked IN or false for checked OUT
1572
-        // no record ( null ) means checked in NEVER, but we obviously don't save that
1573
-        $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1574
-        // add relation - note Check-ins are always creating new rows
1575
-        // because we are keeping track of Check-ins over time.
1576
-        // Eventually we'll probably want to show a list table
1577
-        // for the individual Check-ins so that they can be managed.
1578
-        $checkin = EE_Checkin::new_instance(
1579
-            array(
1580
-                'REG_ID' => $this->ID(),
1581
-                'DTT_ID' => $DTT_ID,
1582
-                'CHK_in' => $new_status,
1583
-            )
1584
-        );
1585
-        // if the record could not be saved then return false
1586
-        if ($checkin->save() === 0) {
1587
-            if (WP_DEBUG) {
1588
-                global $wpdb;
1589
-                $error = sprintf(
1590
-                    esc_html__(
1591
-                        'Registration check in update failed because of the following database error: %1$s%2$s',
1592
-                        'event_espresso'
1593
-                    ),
1594
-                    '<br />',
1595
-                    $wpdb->last_error
1596
-                );
1597
-            } else {
1598
-                $error = esc_html__(
1599
-                    'Registration check in update failed because of an unknown database error',
1600
-                    'event_espresso'
1601
-                );
1602
-            }
1603
-            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1604
-            return false;
1605
-        }
1606
-        // Fire a checked_in and checkout_out action.
1607
-        $checked_status = $status_to === EE_Checkin::status_checked_in ? 'checked_in' : 'checked_out';
1608
-        do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1609
-        return $status_to;
1610
-    }
1611
-
1612
-
1613
-    /**
1614
-     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1615
-     * "Latest" is defined by the `DTT_EVT_start` column.
1616
-     *
1617
-     * @return EE_Datetime|null
1618
-     * @throws EE_Error
1619
-     */
1620
-    public function get_latest_related_datetime()
1621
-    {
1622
-        return EEM_Datetime::instance()->get_one(
1623
-            array(
1624
-                array(
1625
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1626
-                ),
1627
-                'order_by' => array('DTT_EVT_start' => 'DESC'),
1628
-            )
1629
-        );
1630
-    }
1631
-
1632
-
1633
-    /**
1634
-     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1635
-     * "Earliest" is defined by the `DTT_EVT_start` column.
1636
-     *
1637
-     * @throws EE_Error
1638
-     */
1639
-    public function get_earliest_related_datetime()
1640
-    {
1641
-        return EEM_Datetime::instance()->get_one(
1642
-            array(
1643
-                array(
1644
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1645
-                ),
1646
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
1647
-            )
1648
-        );
1649
-    }
1650
-
1651
-
1652
-    /**
1653
-     * This method simply returns the check-in status for this registration and the given datetime.
1654
-     * If neither the datetime nor the checkin values are provided as arguments,
1655
-     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1656
-     *
1657
-     * @param  int       $DTT_ID  The ID of the datetime we're checking against
1658
-     *                            (if empty we'll get the primary datetime for
1659
-     *                            this registration (via event) and use it's ID);
1660
-     * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1661
-     *
1662
-     * @return int                Integer representing Check-in status.
1663
-     * @throws EE_Error
1664
-     */
1665
-    public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1666
-    {
1667
-        $checkin_query_params = array(
1668
-            'order_by' => array('CHK_timestamp' => 'DESC'),
1669
-        );
1670
-
1671
-        if ($DTT_ID > 0) {
1672
-            $checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1673
-        }
1674
-
1675
-        // get checkin object (if exists)
1676
-        $checkin = $checkin instanceof EE_Checkin
1677
-            ? $checkin
1678
-            : $this->get_first_related('Checkin', $checkin_query_params);
1679
-        if ($checkin instanceof EE_Checkin) {
1680
-            if ($checkin->get('CHK_in')) {
1681
-                return EE_Checkin::status_checked_in; // checked in
1682
-            }
1683
-            return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1684
-        }
1685
-        return EE_Checkin::status_checked_never; // never been checked in
1686
-    }
1687
-
1688
-
1689
-    /**
1690
-     * This method returns a localized message for the toggled Check-in message.
1691
-     *
1692
-     * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1693
-     *                     then it is assumed Check-in for primary datetime was toggled.
1694
-     * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1695
-     *                     message can be customized with the attendee name.
1696
-     * @return string internationalized message
1697
-     * @throws EE_Error
1698
-     */
1699
-    public function get_checkin_msg($DTT_ID, $error = false)
1700
-    {
1701
-        // let's get the attendee first so we can include the name of the attendee
1702
-        $attendee = $this->get_first_related('Attendee');
1703
-        if ($attendee instanceof EE_Attendee) {
1704
-            if ($error) {
1705
-                return sprintf(esc_html__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1706
-            }
1707
-            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1708
-            // what is the status message going to be?
1709
-            switch ($cur_status) {
1710
-                case EE_Checkin::status_checked_never:
1711
-                    return sprintf(
1712
-                        esc_html__("%s has been removed from Check-in records", "event_espresso"),
1713
-                        $attendee->full_name()
1714
-                    );
1715
-                    break;
1716
-                case EE_Checkin::status_checked_in:
1717
-                    return sprintf(esc_html__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1718
-                    break;
1719
-                case EE_Checkin::status_checked_out:
1720
-                    return sprintf(esc_html__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1721
-                    break;
1722
-            }
1723
-        }
1724
-        return esc_html__("The check-in status could not be determined.", "event_espresso");
1725
-    }
1726
-
1727
-
1728
-    /**
1729
-     * Returns the related EE_Transaction to this registration
1730
-     *
1731
-     * @return EE_Transaction
1732
-     * @throws EE_Error
1733
-     * @throws EntityNotFoundException
1734
-     */
1735
-    public function transaction()
1736
-    {
1737
-        $transaction = $this->get_first_related('Transaction');
1738
-        if (! $transaction instanceof \EE_Transaction) {
1739
-            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1740
-        }
1741
-        return $transaction;
1742
-    }
1743
-
1744
-
1745
-    /**
1746
-     *        get Registration Code
1747
-     */
1748
-    public function reg_code()
1749
-    {
1750
-        return $this->get('REG_code');
1751
-    }
1752
-
1753
-
1754
-    /**
1755
-     *        get Transaction ID
1756
-     */
1757
-    public function transaction_ID()
1758
-    {
1759
-        return $this->get('TXN_ID');
1760
-    }
1761
-
1762
-
1763
-    /**
1764
-     * @return int
1765
-     * @throws EE_Error
1766
-     */
1767
-    public function ticket_ID()
1768
-    {
1769
-        return $this->get('TKT_ID');
1770
-    }
1771
-
1772
-
1773
-    /**
1774
-     *        Set Registration Code
1775
-     *
1776
-     * @access    public
1777
-     * @param    string  $REG_code Registration Code
1778
-     * @param    boolean $use_default
1779
-     * @throws EE_Error
1780
-     */
1781
-    public function set_reg_code($REG_code, $use_default = false)
1782
-    {
1783
-        if (empty($REG_code)) {
1784
-            EE_Error::add_error(
1785
-                esc_html__('REG_code can not be empty.', 'event_espresso'),
1786
-                __FILE__,
1787
-                __FUNCTION__,
1788
-                __LINE__
1789
-            );
1790
-            return;
1791
-        }
1792
-        if (! $this->reg_code()) {
1793
-            parent::set('REG_code', $REG_code, $use_default);
1794
-        } else {
1795
-            EE_Error::doing_it_wrong(
1796
-                __CLASS__ . '::' . __FUNCTION__,
1797
-                esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1798
-                '4.6.0'
1799
-            );
1800
-        }
1801
-    }
1802
-
1803
-
1804
-    /**
1805
-     * Returns all other registrations in the same group as this registrant who have the same ticket option.
1806
-     * Note, if you want to just get all registrations in the same transaction (group), use:
1807
-     *    $registration->transaction()->registrations();
1808
-     *
1809
-     * @since 4.5.0
1810
-     * @return EE_Registration[] or empty array if this isn't a group registration.
1811
-     * @throws EE_Error
1812
-     */
1813
-    public function get_all_other_registrations_in_group()
1814
-    {
1815
-        if ($this->group_size() < 2) {
1816
-            return array();
1817
-        }
1818
-
1819
-        $query[0] = array(
1820
-            'TXN_ID' => $this->transaction_ID(),
1821
-            'REG_ID' => array('!=', $this->ID()),
1822
-            'TKT_ID' => $this->ticket_ID(),
1823
-        );
1824
-        /** @var EE_Registration[] $registrations */
1825
-        $registrations = $this->get_model()->get_all($query);
1826
-        return $registrations;
1827
-    }
1828
-
1829
-    /**
1830
-     * Return the link to the admin details for the object.
1831
-     *
1832
-     * @return string
1833
-     * @throws EE_Error
1834
-     */
1835
-    public function get_admin_details_link()
1836
-    {
1837
-        EE_Registry::instance()->load_helper('URL');
1838
-        return EEH_URL::add_query_args_and_nonce(
1839
-            array(
1840
-                'page'    => 'espresso_registrations',
1841
-                'action'  => 'view_registration',
1842
-                '_REG_ID' => $this->ID(),
1843
-            ),
1844
-            admin_url('admin.php')
1845
-        );
1846
-    }
1847
-
1848
-    /**
1849
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1850
-     *
1851
-     * @return string
1852
-     * @throws EE_Error
1853
-     */
1854
-    public function get_admin_edit_link()
1855
-    {
1856
-        return $this->get_admin_details_link();
1857
-    }
1858
-
1859
-    /**
1860
-     * Returns the link to a settings page for the object.
1861
-     *
1862
-     * @return string
1863
-     * @throws EE_Error
1864
-     */
1865
-    public function get_admin_settings_link()
1866
-    {
1867
-        return $this->get_admin_details_link();
1868
-    }
1869
-
1870
-    /**
1871
-     * Returns the link to the "overview" for the object (typically the "list table" view).
1872
-     *
1873
-     * @return string
1874
-     */
1875
-    public function get_admin_overview_link()
1876
-    {
1877
-        EE_Registry::instance()->load_helper('URL');
1878
-        return EEH_URL::add_query_args_and_nonce(
1879
-            array(
1880
-                'page' => 'espresso_registrations',
1881
-            ),
1882
-            admin_url('admin.php')
1883
-        );
1884
-    }
1885
-
1886
-
1887
-    /**
1888
-     * @param array $query_params
1889
-     *
1890
-     * @return \EE_Registration[]
1891
-     * @throws EE_Error
1892
-     */
1893
-    public function payments($query_params = array())
1894
-    {
1895
-        return $this->get_many_related('Payment', $query_params);
1896
-    }
1897
-
1898
-
1899
-    /**
1900
-     * @param array $query_params
1901
-     *
1902
-     * @return \EE_Registration_Payment[]
1903
-     * @throws EE_Error
1904
-     */
1905
-    public function registration_payments($query_params = array())
1906
-    {
1907
-        return $this->get_many_related('Registration_Payment', $query_params);
1908
-    }
1909
-
1910
-
1911
-    /**
1912
-     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1913
-     * Note: if there are no payments on the registration there will be no payment method returned.
1914
-     *
1915
-     * @return EE_Payment_Method|null
1916
-     */
1917
-    public function payment_method()
1918
-    {
1919
-        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1920
-    }
1921
-
1922
-
1923
-    /**
1924
-     * @return \EE_Line_Item
1925
-     * @throws EntityNotFoundException
1926
-     * @throws EE_Error
1927
-     */
1928
-    public function ticket_line_item()
1929
-    {
1930
-        $ticket = $this->ticket();
1931
-        $transaction = $this->transaction();
1932
-        $line_item = null;
1933
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1934
-            $transaction->total_line_item(),
1935
-            'Ticket',
1936
-            array($ticket->ID())
1937
-        );
1938
-        foreach ($ticket_line_items as $ticket_line_item) {
1939
-            if (
1940
-                $ticket_line_item instanceof \EE_Line_Item
1941
-                && $ticket_line_item->OBJ_type() === 'Ticket'
1942
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
1943
-            ) {
1944
-                $line_item = $ticket_line_item;
1945
-                break;
1946
-            }
1947
-        }
1948
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1949
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1950
-        }
1951
-        return $line_item;
1952
-    }
1953
-
1954
-
1955
-    /**
1956
-     * Soft Deletes this model object.
1957
-     *
1958
-     * @return boolean | int
1959
-     * @throws RuntimeException
1960
-     * @throws EE_Error
1961
-     */
1962
-    public function delete()
1963
-    {
1964
-        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1965
-            $this->set_status(EEM_Registration::status_id_cancelled);
1966
-        }
1967
-        return parent::delete();
1968
-    }
1969
-
1970
-
1971
-    /**
1972
-     * Restores whatever the previous status was on a registration before it was trashed (if possible)
1973
-     *
1974
-     * @throws EE_Error
1975
-     * @throws RuntimeException
1976
-     */
1977
-    public function restore()
1978
-    {
1979
-        $previous_status = $this->get_extra_meta(
1980
-            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1981
-            true,
1982
-            EEM_Registration::status_id_cancelled
1983
-        );
1984
-        if ($previous_status) {
1985
-            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1986
-            $this->set_status($previous_status);
1987
-        }
1988
-        return parent::restore();
1989
-    }
1990
-
1991
-
1992
-    /**
1993
-     * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1994
-     *
1995
-     * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1996
-     *                                           depending on whether the reg status changes to or from "Approved"
1997
-     * @return boolean whether the Registration status was updated
1998
-     * @throws EE_Error
1999
-     * @throws RuntimeException
2000
-     */
2001
-    public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
2002
-    {
2003
-        $paid = $this->paid();
2004
-        $price = $this->final_price();
2005
-        switch (true) {
2006
-            // overpaid or paid
2007
-            case EEH_Money::compare_floats($paid, $price, '>'):
2008
-            case EEH_Money::compare_floats($paid, $price):
2009
-                $new_status = EEM_Registration::status_id_approved;
2010
-                break;
2011
-            //  underpaid
2012
-            case EEH_Money::compare_floats($paid, $price, '<'):
2013
-                $new_status = EEM_Registration::status_id_pending_payment;
2014
-                break;
2015
-            // uhhh Houston...
2016
-            default:
2017
-                throw new RuntimeException(
2018
-                    esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2019
-                );
2020
-        }
2021
-        if ($new_status !== $this->status_ID()) {
2022
-            if ($trigger_set_status_logic) {
2023
-                return $this->set_status($new_status);
2024
-            }
2025
-            parent::set('STS_ID', $new_status);
2026
-            return true;
2027
-        }
2028
-        return false;
2029
-    }
2030
-
2031
-
2032
-    /*************************** DEPRECATED ***************************/
2033
-
2034
-
2035
-    /**
2036
-     * @deprecated
2037
-     * @since     4.7.0
2038
-     * @access    public
2039
-     */
2040
-    public function price_paid()
2041
-    {
2042
-        EE_Error::doing_it_wrong(
2043
-            'EE_Registration::price_paid()',
2044
-            esc_html__(
2045
-                'This method is deprecated, please use EE_Registration::final_price() instead.',
2046
-                'event_espresso'
2047
-            ),
2048
-            '4.7.0'
2049
-        );
2050
-        return $this->final_price();
2051
-    }
2052
-
2053
-
2054
-    /**
2055
-     * @deprecated
2056
-     * @since     4.7.0
2057
-     * @access    public
2058
-     * @param    float $REG_final_price
2059
-     * @throws EE_Error
2060
-     * @throws RuntimeException
2061
-     */
2062
-    public function set_price_paid($REG_final_price = 0.00)
2063
-    {
2064
-        EE_Error::doing_it_wrong(
2065
-            'EE_Registration::set_price_paid()',
2066
-            esc_html__(
2067
-                'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2068
-                'event_espresso'
2069
-            ),
2070
-            '4.7.0'
2071
-        );
2072
-        $this->set_final_price($REG_final_price);
2073
-    }
2074
-
2075
-
2076
-    /**
2077
-     * @deprecated
2078
-     * @since 4.7.0
2079
-     * @return string
2080
-     * @throws EE_Error
2081
-     */
2082
-    public function pretty_price_paid()
2083
-    {
2084
-        EE_Error::doing_it_wrong(
2085
-            'EE_Registration::pretty_price_paid()',
2086
-            esc_html__(
2087
-                'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2088
-                'event_espresso'
2089
-            ),
2090
-            '4.7.0'
2091
-        );
2092
-        return $this->pretty_final_price();
2093
-    }
2094
-
2095
-
2096
-    /**
2097
-     * Gets the primary datetime related to this registration via the related Event to this registration
2098
-     *
2099
-     * @deprecated 4.9.17
2100
-     * @return EE_Datetime
2101
-     * @throws EE_Error
2102
-     * @throws EntityNotFoundException
2103
-     */
2104
-    public function get_related_primary_datetime()
2105
-    {
2106
-        EE_Error::doing_it_wrong(
2107
-            __METHOD__,
2108
-            esc_html__(
2109
-                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2110
-                'event_espresso'
2111
-            ),
2112
-            '4.9.17',
2113
-            '5.0.0'
2114
-        );
2115
-        return $this->event()->primary_datetime();
2116
-    }
2117
-
2118
-    /**
2119
-     * Returns the contact's name (or "Unknown" if there is no contact.)
2120
-     * @since 4.10.12.p
2121
-     * @return string
2122
-     * @throws EE_Error
2123
-     * @throws InvalidArgumentException
2124
-     * @throws InvalidDataTypeException
2125
-     * @throws InvalidInterfaceException
2126
-     * @throws ReflectionException
2127
-     */
2128
-    public function name()
2129
-    {
2130
-        return $this->attendeeName();
2131
-    }
19
+	/**
20
+	 * Used to reference when a registration has never been checked in.
21
+	 *
22
+	 * @deprecated use \EE_Checkin::status_checked_never instead
23
+	 * @type int
24
+	 */
25
+	const checkin_status_never = 2;
26
+
27
+	/**
28
+	 * Used to reference when a registration has been checked in.
29
+	 *
30
+	 * @deprecated use \EE_Checkin::status_checked_in instead
31
+	 * @type int
32
+	 */
33
+	const checkin_status_in = 1;
34
+
35
+
36
+	/**
37
+	 * Used to reference when a registration has been checked out.
38
+	 *
39
+	 * @deprecated use \EE_Checkin::status_checked_out instead
40
+	 * @type int
41
+	 */
42
+	const checkin_status_out = 0;
43
+
44
+
45
+	/**
46
+	 * extra meta key for tracking reg status os trashed registrations
47
+	 *
48
+	 * @type string
49
+	 */
50
+	const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
51
+
52
+
53
+	/**
54
+	 * extra meta key for tracking if registration has reserved ticket
55
+	 *
56
+	 * @type string
57
+	 */
58
+	const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
59
+
60
+
61
+	/**
62
+	 * @param array  $props_n_values          incoming values
63
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
64
+	 *                                        used.)
65
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
66
+	 *                                        date_format and the second value is the time format
67
+	 * @return EE_Registration
68
+	 * @throws EE_Error
69
+	 */
70
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
71
+	{
72
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
73
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
74
+	}
75
+
76
+
77
+	/**
78
+	 * @param array  $props_n_values  incoming values from the database
79
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
80
+	 *                                the website will be used.
81
+	 * @return EE_Registration
82
+	 */
83
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
84
+	{
85
+		return new self($props_n_values, true, $timezone);
86
+	}
87
+
88
+
89
+	/**
90
+	 *        Set Event ID
91
+	 *
92
+	 * @param        int $EVT_ID Event ID
93
+	 * @throws EE_Error
94
+	 * @throws RuntimeException
95
+	 */
96
+	public function set_event($EVT_ID = 0)
97
+	{
98
+		$this->set('EVT_ID', $EVT_ID);
99
+	}
100
+
101
+
102
+	/**
103
+	 * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
104
+	 * be routed to internal methods
105
+	 *
106
+	 * @param string $field_name
107
+	 * @param mixed  $field_value
108
+	 * @param bool   $use_default
109
+	 * @throws EE_Error
110
+	 * @throws EntityNotFoundException
111
+	 * @throws InvalidArgumentException
112
+	 * @throws InvalidDataTypeException
113
+	 * @throws InvalidInterfaceException
114
+	 * @throws ReflectionException
115
+	 * @throws RuntimeException
116
+	 */
117
+	public function set($field_name, $field_value, $use_default = false)
118
+	{
119
+		switch ($field_name) {
120
+			case 'REG_code':
121
+				if (! empty($field_value) && $this->reg_code() === null) {
122
+					$this->set_reg_code($field_value, $use_default);
123
+				}
124
+				break;
125
+			case 'STS_ID':
126
+				$this->set_status($field_value, $use_default);
127
+				break;
128
+			default:
129
+				parent::set($field_name, $field_value, $use_default);
130
+		}
131
+	}
132
+
133
+
134
+	/**
135
+	 * Set Status ID
136
+	 * updates the registration status and ALSO...
137
+	 * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
138
+	 * calls release_registration_space() if the reg status changes FROM approved to any other reg status
139
+	 *
140
+	 * @param string                $new_STS_ID
141
+	 * @param boolean               $use_default
142
+	 * @param ContextInterface|null $context
143
+	 * @return bool
144
+	 * @throws DomainException
145
+	 * @throws EE_Error
146
+	 * @throws EntityNotFoundException
147
+	 * @throws InvalidArgumentException
148
+	 * @throws InvalidDataTypeException
149
+	 * @throws InvalidInterfaceException
150
+	 * @throws ReflectionException
151
+	 * @throws RuntimeException
152
+	 * @throws UnexpectedEntityException
153
+	 */
154
+	public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
155
+	{
156
+		// get current REG_Status
157
+		$old_STS_ID = $this->status_ID();
158
+		// if status has changed
159
+		if (
160
+			$old_STS_ID !== $new_STS_ID // and that status has actually changed
161
+			&& ! empty($old_STS_ID) // and that old status is actually set
162
+			&& ! empty($new_STS_ID) // as well as the new status
163
+			&& $this->ID() // ensure registration is in the db
164
+		) {
165
+			// update internal status first
166
+			parent::set('STS_ID', $new_STS_ID, $use_default);
167
+			// THEN handle other changes that occur when reg status changes
168
+			// TO approved
169
+			if ($new_STS_ID === EEM_Registration::status_id_approved) {
170
+				// reserve a space by incrementing ticket and datetime sold values
171
+				$this->reserveRegistrationSpace();
172
+				do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
173
+				// OR FROM  approved
174
+			} elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
175
+				// release a space by decrementing ticket and datetime sold values
176
+				$this->releaseRegistrationSpace();
177
+				do_action(
178
+					'AHEE__EE_Registration__set_status__from_approved',
179
+					$this,
180
+					$old_STS_ID,
181
+					$new_STS_ID,
182
+					$context
183
+				);
184
+			}
185
+			// update status
186
+			parent::set('STS_ID', $new_STS_ID, $use_default);
187
+			$this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
188
+			if ($this->statusChangeUpdatesTransaction($context)) {
189
+				$this->updateTransactionAfterStatusChange();
190
+			}
191
+			do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
192
+			return true;
193
+		}
194
+		// even though the old value matches the new value, it's still good to
195
+		// allow the parent set method to have a say
196
+		parent::set('STS_ID', $new_STS_ID, $use_default);
197
+		return true;
198
+	}
199
+
200
+
201
+	/**
202
+	 * update REGs and TXN when cancelled or declined registrations involved
203
+	 *
204
+	 * @param string                $new_STS_ID
205
+	 * @param string                $old_STS_ID
206
+	 * @param ContextInterface|null $context
207
+	 * @throws EE_Error
208
+	 * @throws InvalidArgumentException
209
+	 * @throws InvalidDataTypeException
210
+	 * @throws InvalidInterfaceException
211
+	 * @throws ReflectionException
212
+	 * @throws RuntimeException
213
+	 */
214
+	private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
215
+	{
216
+		// these reg statuses should not be considered in any calculations involving monies owing
217
+		$closed_reg_statuses = EEM_Registration::closed_reg_statuses();
218
+		// true if registration has been cancelled or declined
219
+		$this->updateIfCanceled(
220
+			$closed_reg_statuses,
221
+			$new_STS_ID,
222
+			$old_STS_ID,
223
+			$context
224
+		);
225
+		$this->updateIfReinstated(
226
+			$closed_reg_statuses,
227
+			$new_STS_ID,
228
+			$old_STS_ID,
229
+			$context
230
+		);
231
+	}
232
+
233
+
234
+	/**
235
+	 * update REGs and TXN when cancelled or declined registrations involved
236
+	 *
237
+	 * @param array                 $closed_reg_statuses
238
+	 * @param string                $new_STS_ID
239
+	 * @param string                $old_STS_ID
240
+	 * @param ContextInterface|null $context
241
+	 * @throws EE_Error
242
+	 * @throws InvalidArgumentException
243
+	 * @throws InvalidDataTypeException
244
+	 * @throws InvalidInterfaceException
245
+	 * @throws ReflectionException
246
+	 * @throws RuntimeException
247
+	 */
248
+	private function updateIfCanceled(
249
+		array $closed_reg_statuses,
250
+		$new_STS_ID,
251
+		$old_STS_ID,
252
+		ContextInterface $context = null
253
+	) {
254
+		// true if registration has been cancelled or declined
255
+		if (
256
+			in_array($new_STS_ID, $closed_reg_statuses, true)
257
+			&& ! in_array($old_STS_ID, $closed_reg_statuses, true)
258
+		) {
259
+			/** @type EE_Registration_Processor $registration_processor */
260
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
261
+			/** @type EE_Transaction_Processor $transaction_processor */
262
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
263
+			// cancelled or declined registration
264
+			$registration_processor->update_registration_after_being_canceled_or_declined(
265
+				$this,
266
+				$closed_reg_statuses
267
+			);
268
+			$transaction_processor->update_transaction_after_canceled_or_declined_registration(
269
+				$this,
270
+				$closed_reg_statuses,
271
+				false
272
+			);
273
+			do_action(
274
+				'AHEE__EE_Registration__set_status__canceled_or_declined',
275
+				$this,
276
+				$old_STS_ID,
277
+				$new_STS_ID,
278
+				$context
279
+			);
280
+			return;
281
+		}
282
+	}
283
+
284
+
285
+	/**
286
+	 * update REGs and TXN when cancelled or declined registrations involved
287
+	 *
288
+	 * @param array                 $closed_reg_statuses
289
+	 * @param string                $new_STS_ID
290
+	 * @param string                $old_STS_ID
291
+	 * @param ContextInterface|null $context
292
+	 * @throws EE_Error
293
+	 * @throws InvalidArgumentException
294
+	 * @throws InvalidDataTypeException
295
+	 * @throws InvalidInterfaceException
296
+	 * @throws ReflectionException
297
+	 */
298
+	private function updateIfReinstated(
299
+		array $closed_reg_statuses,
300
+		$new_STS_ID,
301
+		$old_STS_ID,
302
+		ContextInterface $context = null
303
+	) {
304
+		// true if reinstating cancelled or declined registration
305
+		if (
306
+			in_array($old_STS_ID, $closed_reg_statuses, true)
307
+			&& ! in_array($new_STS_ID, $closed_reg_statuses, true)
308
+		) {
309
+			/** @type EE_Registration_Processor $registration_processor */
310
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
311
+			/** @type EE_Transaction_Processor $transaction_processor */
312
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
313
+			// reinstating cancelled or declined registration
314
+			$registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
315
+				$this,
316
+				$closed_reg_statuses
317
+			);
318
+			$transaction_processor->update_transaction_after_reinstating_canceled_registration(
319
+				$this,
320
+				$closed_reg_statuses,
321
+				false
322
+			);
323
+			do_action(
324
+				'AHEE__EE_Registration__set_status__after_reinstated',
325
+				$this,
326
+				$old_STS_ID,
327
+				$new_STS_ID,
328
+				$context
329
+			);
330
+		}
331
+	}
332
+
333
+
334
+	/**
335
+	 * @param ContextInterface|null $context
336
+	 * @return bool
337
+	 */
338
+	private function statusChangeUpdatesTransaction(ContextInterface $context = null)
339
+	{
340
+		$contexts_that_do_not_update_transaction = (array) apply_filters(
341
+			'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
342
+			array('spco_reg_step_attendee_information_process_registrations'),
343
+			$context,
344
+			$this
345
+		);
346
+		return ! (
347
+			$context instanceof ContextInterface
348
+			&& in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
349
+		);
350
+	}
351
+
352
+
353
+	/**
354
+	 * @throws EE_Error
355
+	 * @throws EntityNotFoundException
356
+	 * @throws InvalidArgumentException
357
+	 * @throws InvalidDataTypeException
358
+	 * @throws InvalidInterfaceException
359
+	 * @throws ReflectionException
360
+	 * @throws RuntimeException
361
+	 */
362
+	private function updateTransactionAfterStatusChange()
363
+	{
364
+		/** @type EE_Transaction_Payments $transaction_payments */
365
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
366
+		$transaction_payments->recalculate_transaction_total($this->transaction(), false);
367
+		$this->transaction()->update_status_based_on_total_paid(true);
368
+	}
369
+
370
+
371
+	/**
372
+	 *        get Status ID
373
+	 */
374
+	public function status_ID()
375
+	{
376
+		return $this->get('STS_ID');
377
+	}
378
+
379
+
380
+	/**
381
+	 * Gets the ticket this registration is for
382
+	 *
383
+	 * @param boolean $include_archived whether to include archived tickets or not.
384
+	 *
385
+	 * @return EE_Ticket|EE_Base_Class
386
+	 * @throws EE_Error
387
+	 */
388
+	public function ticket($include_archived = true)
389
+	{
390
+		$query_params = array();
391
+		if ($include_archived) {
392
+			$query_params['default_where_conditions'] = 'none';
393
+		}
394
+		return $this->get_first_related('Ticket', $query_params);
395
+	}
396
+
397
+
398
+	/**
399
+	 * Gets the event this registration is for
400
+	 *
401
+	 * @return EE_Event
402
+	 * @throws EE_Error
403
+	 * @throws EntityNotFoundException
404
+	 */
405
+	public function event()
406
+	{
407
+		$event = $this->get_first_related('Event');
408
+		if (! $event instanceof \EE_Event) {
409
+			throw new EntityNotFoundException('Event ID', $this->event_ID());
410
+		}
411
+		return $event;
412
+	}
413
+
414
+
415
+	/**
416
+	 * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
417
+	 * with the author of the event this registration is for.
418
+	 *
419
+	 * @since 4.5.0
420
+	 * @return int
421
+	 * @throws EE_Error
422
+	 * @throws EntityNotFoundException
423
+	 */
424
+	public function wp_user()
425
+	{
426
+		$event = $this->event();
427
+		if ($event instanceof EE_Event) {
428
+			return $event->wp_user();
429
+		}
430
+		return 0;
431
+	}
432
+
433
+
434
+	/**
435
+	 * increments this registration's related ticket sold and corresponding datetime sold values
436
+	 *
437
+	 * @return void
438
+	 * @throws DomainException
439
+	 * @throws EE_Error
440
+	 * @throws EntityNotFoundException
441
+	 * @throws InvalidArgumentException
442
+	 * @throws InvalidDataTypeException
443
+	 * @throws InvalidInterfaceException
444
+	 * @throws ReflectionException
445
+	 * @throws UnexpectedEntityException
446
+	 */
447
+	private function reserveRegistrationSpace()
448
+	{
449
+		// reserved ticket and datetime counts will be decremented as sold counts are incremented
450
+		// so stop tracking that this reg has a ticket reserved
451
+		$this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
452
+		$ticket = $this->ticket();
453
+		$ticket->increaseSold();
454
+		// possibly set event status to sold out
455
+		$this->event()->perform_sold_out_status_check();
456
+	}
457
+
458
+
459
+	/**
460
+	 * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
461
+	 *
462
+	 * @return void
463
+	 * @throws DomainException
464
+	 * @throws EE_Error
465
+	 * @throws EntityNotFoundException
466
+	 * @throws InvalidArgumentException
467
+	 * @throws InvalidDataTypeException
468
+	 * @throws InvalidInterfaceException
469
+	 * @throws ReflectionException
470
+	 * @throws UnexpectedEntityException
471
+	 */
472
+	private function releaseRegistrationSpace()
473
+	{
474
+		$ticket = $this->ticket();
475
+		$ticket->decreaseSold();
476
+		// possibly change event status from sold out back to previous status
477
+		$this->event()->perform_sold_out_status_check();
478
+	}
479
+
480
+
481
+	/**
482
+	 * tracks this registration's ticket reservation in extra meta
483
+	 * and can increment related ticket reserved and corresponding datetime reserved values
484
+	 *
485
+	 * @param bool $update_ticket if true, will increment ticket and datetime reserved count
486
+	 * @return void
487
+	 * @throws EE_Error
488
+	 * @throws InvalidArgumentException
489
+	 * @throws InvalidDataTypeException
490
+	 * @throws InvalidInterfaceException
491
+	 * @throws ReflectionException
492
+	 */
493
+	public function reserve_ticket($update_ticket = false, $source = 'unknown')
494
+	{
495
+		// only reserve ticket if space is not currently reserved
496
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
497
+			$this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
498
+			// IMPORTANT !!!
499
+			// although checking $update_ticket first would be more efficient,
500
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
501
+			if (
502
+				$this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
503
+				&& $update_ticket
504
+			) {
505
+				$ticket = $this->ticket();
506
+				$ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
507
+				$ticket->save();
508
+			}
509
+		}
510
+	}
511
+
512
+
513
+	/**
514
+	 * stops tracking this registration's ticket reservation in extra meta
515
+	 * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
516
+	 *
517
+	 * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
518
+	 * @return void
519
+	 * @throws EE_Error
520
+	 * @throws InvalidArgumentException
521
+	 * @throws InvalidDataTypeException
522
+	 * @throws InvalidInterfaceException
523
+	 * @throws ReflectionException
524
+	 */
525
+	public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
526
+	{
527
+		// only release ticket if space is currently reserved
528
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
529
+			$this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
530
+			// IMPORTANT !!!
531
+			// although checking $update_ticket first would be more efficient,
532
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
533
+			if (
534
+				$this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
535
+				&& $update_ticket
536
+			) {
537
+				$ticket = $this->ticket();
538
+				$ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
539
+			}
540
+		}
541
+	}
542
+
543
+
544
+	/**
545
+	 * Set Attendee ID
546
+	 *
547
+	 * @param        int $ATT_ID Attendee ID
548
+	 * @throws EE_Error
549
+	 * @throws RuntimeException
550
+	 */
551
+	public function set_attendee_id($ATT_ID = 0)
552
+	{
553
+		$this->set('ATT_ID', $ATT_ID);
554
+	}
555
+
556
+
557
+	/**
558
+	 *        Set Transaction ID
559
+	 *
560
+	 * @param        int $TXN_ID Transaction ID
561
+	 * @throws EE_Error
562
+	 * @throws RuntimeException
563
+	 */
564
+	public function set_transaction_id($TXN_ID = 0)
565
+	{
566
+		$this->set('TXN_ID', $TXN_ID);
567
+	}
568
+
569
+
570
+	/**
571
+	 *        Set Session
572
+	 *
573
+	 * @param    string $REG_session PHP Session ID
574
+	 * @throws EE_Error
575
+	 * @throws RuntimeException
576
+	 */
577
+	public function set_session($REG_session = '')
578
+	{
579
+		$this->set('REG_session', $REG_session);
580
+	}
581
+
582
+
583
+	/**
584
+	 *        Set Registration URL Link
585
+	 *
586
+	 * @param    string $REG_url_link Registration URL Link
587
+	 * @throws EE_Error
588
+	 * @throws RuntimeException
589
+	 */
590
+	public function set_reg_url_link($REG_url_link = '')
591
+	{
592
+		$this->set('REG_url_link', $REG_url_link);
593
+	}
594
+
595
+
596
+	/**
597
+	 *        Set Attendee Counter
598
+	 *
599
+	 * @param        int $REG_count Primary Attendee
600
+	 * @throws EE_Error
601
+	 * @throws RuntimeException
602
+	 */
603
+	public function set_count($REG_count = 1)
604
+	{
605
+		$this->set('REG_count', $REG_count);
606
+	}
607
+
608
+
609
+	/**
610
+	 *        Set Group Size
611
+	 *
612
+	 * @param        boolean $REG_group_size Group Registration
613
+	 * @throws EE_Error
614
+	 * @throws RuntimeException
615
+	 */
616
+	public function set_group_size($REG_group_size = false)
617
+	{
618
+		$this->set('REG_group_size', $REG_group_size);
619
+	}
620
+
621
+
622
+	/**
623
+	 *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
624
+	 *    EEM_Registration::status_id_not_approved
625
+	 *
626
+	 * @return        boolean
627
+	 */
628
+	public function is_not_approved()
629
+	{
630
+		return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
631
+	}
632
+
633
+
634
+	/**
635
+	 *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
636
+	 *    EEM_Registration::status_id_pending_payment
637
+	 *
638
+	 * @return        boolean
639
+	 */
640
+	public function is_pending_payment()
641
+	{
642
+		return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
643
+	}
644
+
645
+
646
+	/**
647
+	 *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
648
+	 *
649
+	 * @return        boolean
650
+	 */
651
+	public function is_approved()
652
+	{
653
+		return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
654
+	}
655
+
656
+
657
+	/**
658
+	 *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
659
+	 *
660
+	 * @return        boolean
661
+	 */
662
+	public function is_cancelled()
663
+	{
664
+		return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
665
+	}
666
+
667
+
668
+	/**
669
+	 *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
670
+	 *
671
+	 * @return        boolean
672
+	 */
673
+	public function is_declined()
674
+	{
675
+		return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
676
+	}
677
+
678
+
679
+	/**
680
+	 *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
681
+	 *    EEM_Registration::status_id_incomplete
682
+	 *
683
+	 * @return        boolean
684
+	 */
685
+	public function is_incomplete()
686
+	{
687
+		return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
688
+	}
689
+
690
+
691
+	/**
692
+	 *        Set Registration Date
693
+	 *
694
+	 * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
695
+	 *                                                 Date
696
+	 * @throws EE_Error
697
+	 * @throws RuntimeException
698
+	 */
699
+	public function set_reg_date($REG_date = false)
700
+	{
701
+		$this->set('REG_date', $REG_date);
702
+	}
703
+
704
+
705
+	/**
706
+	 *    Set final price owing for this registration after all ticket/price modifications
707
+	 *
708
+	 * @access    public
709
+	 * @param    float $REG_final_price
710
+	 * @throws EE_Error
711
+	 * @throws RuntimeException
712
+	 */
713
+	public function set_final_price($REG_final_price = 0.00)
714
+	{
715
+		$this->set('REG_final_price', $REG_final_price);
716
+	}
717
+
718
+
719
+	/**
720
+	 *    Set amount paid towards this registration's final price
721
+	 *
722
+	 * @access    public
723
+	 * @param    float $REG_paid
724
+	 * @throws EE_Error
725
+	 * @throws RuntimeException
726
+	 */
727
+	public function set_paid($REG_paid = 0.00)
728
+	{
729
+		$this->set('REG_paid', $REG_paid);
730
+	}
731
+
732
+
733
+	/**
734
+	 *        Attendee Is Going
735
+	 *
736
+	 * @param        boolean $REG_att_is_going Attendee Is Going
737
+	 * @throws EE_Error
738
+	 * @throws RuntimeException
739
+	 */
740
+	public function set_att_is_going($REG_att_is_going = false)
741
+	{
742
+		$this->set('REG_att_is_going', $REG_att_is_going);
743
+	}
744
+
745
+
746
+	/**
747
+	 * Gets the related attendee
748
+	 *
749
+	 * @return EE_Attendee
750
+	 * @throws EE_Error
751
+	 */
752
+	public function attendee()
753
+	{
754
+		return $this->get_first_related('Attendee');
755
+	}
756
+
757
+	/**
758
+	 * Gets the name of the attendee.
759
+	 * @since 4.10.12.p
760
+	 * @param bool $apply_html_entities set to true if you want to use HTML entities.
761
+	 * @return string
762
+	 * @throws EE_Error
763
+	 * @throws InvalidArgumentException
764
+	 * @throws InvalidDataTypeException
765
+	 * @throws InvalidInterfaceException
766
+	 * @throws ReflectionException
767
+	 */
768
+	public function attendeeName($apply_html_entities = false)
769
+	{
770
+		$attendee = $this->get_first_related('Attendee');
771
+		if ($attendee instanceof EE_Attendee) {
772
+			$attendee_name = $attendee->full_name($apply_html_entities);
773
+		} else {
774
+			$attendee_name = esc_html__('Unknown', 'event_espresso');
775
+		}
776
+		return $attendee_name;
777
+	}
778
+
779
+
780
+	/**
781
+	 *        get Event ID
782
+	 */
783
+	public function event_ID()
784
+	{
785
+		return $this->get('EVT_ID');
786
+	}
787
+
788
+
789
+	/**
790
+	 *        get Event ID
791
+	 */
792
+	public function event_name()
793
+	{
794
+		$event = $this->event_obj();
795
+		if ($event) {
796
+			return $event->name();
797
+		} else {
798
+			return null;
799
+		}
800
+	}
801
+
802
+
803
+	/**
804
+	 * Fetches the event this registration is for
805
+	 *
806
+	 * @return EE_Event
807
+	 * @throws EE_Error
808
+	 */
809
+	public function event_obj()
810
+	{
811
+		return $this->get_first_related('Event');
812
+	}
813
+
814
+
815
+	/**
816
+	 *        get Attendee ID
817
+	 */
818
+	public function attendee_ID()
819
+	{
820
+		return $this->get('ATT_ID');
821
+	}
822
+
823
+
824
+	/**
825
+	 *        get PHP Session ID
826
+	 */
827
+	public function session_ID()
828
+	{
829
+		return $this->get('REG_session');
830
+	}
831
+
832
+
833
+	/**
834
+	 * Gets the string which represents the URL trigger for the receipt template in the message template system.
835
+	 *
836
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
837
+	 * @return string
838
+	 */
839
+	public function receipt_url($messenger = 'html')
840
+	{
841
+
842
+		/**
843
+		 * The below will be deprecated one version after this.  We check first if there is a custom receipt template
844
+		 * already in use on old system.  If there is then we just return the standard url for it.
845
+		 *
846
+		 * @since 4.5.0
847
+		 */
848
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
849
+		$has_custom = EEH_Template::locate_template(
850
+			$template_relative_path,
851
+			array(),
852
+			true,
853
+			true,
854
+			true
855
+		);
856
+
857
+		if ($has_custom) {
858
+			return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
859
+		}
860
+		return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
861
+	}
862
+
863
+
864
+	/**
865
+	 * Gets the string which represents the URL trigger for the invoice template in the message template system.
866
+	 *
867
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
868
+	 * @return string
869
+	 * @throws EE_Error
870
+	 */
871
+	public function invoice_url($messenger = 'html')
872
+	{
873
+		/**
874
+		 * The below will be deprecated one version after this.  We check first if there is a custom invoice template
875
+		 * already in use on old system.  If there is then we just return the standard url for it.
876
+		 *
877
+		 * @since 4.5.0
878
+		 */
879
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
880
+		$has_custom = EEH_Template::locate_template(
881
+			$template_relative_path,
882
+			array(),
883
+			true,
884
+			true,
885
+			true
886
+		);
887
+
888
+		if ($has_custom) {
889
+			if ($messenger == 'html') {
890
+				return $this->invoice_url('launch');
891
+			}
892
+			$route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
893
+
894
+			$query_args = array('ee' => $route, 'id' => $this->reg_url_link());
895
+			if ($messenger == 'html') {
896
+				$query_args['html'] = true;
897
+			}
898
+			return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
899
+		}
900
+		return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
901
+	}
902
+
903
+
904
+	/**
905
+	 * get Registration URL Link
906
+	 *
907
+	 * @access public
908
+	 * @return string
909
+	 * @throws EE_Error
910
+	 */
911
+	public function reg_url_link()
912
+	{
913
+		return (string) $this->get('REG_url_link');
914
+	}
915
+
916
+
917
+	/**
918
+	 * Echoes out invoice_url()
919
+	 *
920
+	 * @param string $type 'download','launch', or 'html' (default is 'launch')
921
+	 * @return void
922
+	 * @throws EE_Error
923
+	 */
924
+	public function e_invoice_url($type = 'launch')
925
+	{
926
+		echo esc_url_raw($this->invoice_url($type));
927
+	}
928
+
929
+
930
+	/**
931
+	 * Echoes out payment_overview_url
932
+	 */
933
+	public function e_payment_overview_url()
934
+	{
935
+		echo esc_url_raw($this->payment_overview_url());
936
+	}
937
+
938
+
939
+	/**
940
+	 * Gets the URL for the checkout payment options reg step
941
+	 * with this registration's REG_url_link added as a query parameter
942
+	 *
943
+	 * @param bool $clear_session Set to true when you want to clear the session on revisiting the
944
+	 *                            payment overview url.
945
+	 * @return string
946
+	 * @throws InvalidInterfaceException
947
+	 * @throws InvalidDataTypeException
948
+	 * @throws EE_Error
949
+	 * @throws InvalidArgumentException
950
+	 */
951
+	public function payment_overview_url($clear_session = false)
952
+	{
953
+		return add_query_arg(
954
+			(array) apply_filters(
955
+				'FHEE__EE_Registration__payment_overview_url__query_args',
956
+				array(
957
+					'e_reg_url_link' => $this->reg_url_link(),
958
+					'step'           => 'payment_options',
959
+					'revisit'        => true,
960
+					'clear_session'  => (bool) $clear_session,
961
+				),
962
+				$this
963
+			),
964
+			EE_Registry::instance()->CFG->core->reg_page_url()
965
+		);
966
+	}
967
+
968
+
969
+	/**
970
+	 * Gets the URL for the checkout attendee information reg step
971
+	 * with this registration's REG_url_link added as a query parameter
972
+	 *
973
+	 * @return string
974
+	 * @throws InvalidInterfaceException
975
+	 * @throws InvalidDataTypeException
976
+	 * @throws EE_Error
977
+	 * @throws InvalidArgumentException
978
+	 */
979
+	public function edit_attendee_information_url()
980
+	{
981
+		return add_query_arg(
982
+			(array) apply_filters(
983
+				'FHEE__EE_Registration__edit_attendee_information_url__query_args',
984
+				array(
985
+					'e_reg_url_link' => $this->reg_url_link(),
986
+					'step'           => 'attendee_information',
987
+					'revisit'        => true,
988
+				),
989
+				$this
990
+			),
991
+			EE_Registry::instance()->CFG->core->reg_page_url()
992
+		);
993
+	}
994
+
995
+
996
+	/**
997
+	 * Simply generates and returns the appropriate admin_url link to edit this registration
998
+	 *
999
+	 * @return string
1000
+	 * @throws EE_Error
1001
+	 */
1002
+	public function get_admin_edit_url()
1003
+	{
1004
+		return EEH_URL::add_query_args_and_nonce(
1005
+			array(
1006
+				'page'    => 'espresso_registrations',
1007
+				'action'  => 'view_registration',
1008
+				'_REG_ID' => $this->ID(),
1009
+			),
1010
+			admin_url('admin.php')
1011
+		);
1012
+	}
1013
+
1014
+
1015
+	/**
1016
+	 *    is_primary_registrant?
1017
+	 */
1018
+	public function is_primary_registrant()
1019
+	{
1020
+		return $this->get('REG_count') === 1 ? true : false;
1021
+	}
1022
+
1023
+
1024
+	/**
1025
+	 * This returns the primary registration object for this registration group (which may be this object).
1026
+	 *
1027
+	 * @return EE_Registration
1028
+	 * @throws EE_Error
1029
+	 */
1030
+	public function get_primary_registration()
1031
+	{
1032
+		if ($this->is_primary_registrant()) {
1033
+			return $this;
1034
+		}
1035
+
1036
+		// k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1037
+		/** @var EE_Registration $primary_registrant */
1038
+		$primary_registrant = EEM_Registration::instance()->get_one(
1039
+			array(
1040
+				array(
1041
+					'TXN_ID'    => $this->transaction_ID(),
1042
+					'REG_count' => 1,
1043
+				),
1044
+			)
1045
+		);
1046
+		return $primary_registrant;
1047
+	}
1048
+
1049
+
1050
+	/**
1051
+	 *        get  Attendee Number
1052
+	 *
1053
+	 * @access        public
1054
+	 */
1055
+	public function count()
1056
+	{
1057
+		return $this->get('REG_count');
1058
+	}
1059
+
1060
+
1061
+	/**
1062
+	 *        get Group Size
1063
+	 */
1064
+	public function group_size()
1065
+	{
1066
+		return $this->get('REG_group_size');
1067
+	}
1068
+
1069
+
1070
+	/**
1071
+	 *        get Registration Date
1072
+	 */
1073
+	public function date()
1074
+	{
1075
+		return $this->get('REG_date');
1076
+	}
1077
+
1078
+
1079
+	/**
1080
+	 * gets a pretty date
1081
+	 *
1082
+	 * @param string $date_format
1083
+	 * @param string $time_format
1084
+	 * @return string
1085
+	 * @throws EE_Error
1086
+	 */
1087
+	public function pretty_date($date_format = null, $time_format = null)
1088
+	{
1089
+		return $this->get_datetime('REG_date', $date_format, $time_format);
1090
+	}
1091
+
1092
+
1093
+	/**
1094
+	 * final_price
1095
+	 * the registration's share of the transaction total, so that the
1096
+	 * sum of all the transaction's REG_final_prices equal the transaction's total
1097
+	 *
1098
+	 * @return float
1099
+	 * @throws EE_Error
1100
+	 */
1101
+	public function final_price()
1102
+	{
1103
+		return $this->get('REG_final_price');
1104
+	}
1105
+
1106
+
1107
+	/**
1108
+	 * pretty_final_price
1109
+	 *  final price as formatted string, with correct decimal places and currency symbol
1110
+	 *
1111
+	 * @return string
1112
+	 * @throws EE_Error
1113
+	 */
1114
+	public function pretty_final_price()
1115
+	{
1116
+		return $this->get_pretty('REG_final_price');
1117
+	}
1118
+
1119
+
1120
+	/**
1121
+	 * get paid (yeah)
1122
+	 *
1123
+	 * @return float
1124
+	 * @throws EE_Error
1125
+	 */
1126
+	public function paid()
1127
+	{
1128
+		return $this->get('REG_paid');
1129
+	}
1130
+
1131
+
1132
+	/**
1133
+	 * pretty_paid
1134
+	 *
1135
+	 * @return float
1136
+	 * @throws EE_Error
1137
+	 */
1138
+	public function pretty_paid()
1139
+	{
1140
+		return $this->get_pretty('REG_paid');
1141
+	}
1142
+
1143
+
1144
+	/**
1145
+	 * owes_monies_and_can_pay
1146
+	 * whether or not this registration has monies owing and it's' status allows payment
1147
+	 *
1148
+	 * @param array $requires_payment
1149
+	 * @return bool
1150
+	 * @throws EE_Error
1151
+	 */
1152
+	public function owes_monies_and_can_pay($requires_payment = array())
1153
+	{
1154
+		// these reg statuses require payment (if event is not free)
1155
+		$requires_payment = ! empty($requires_payment)
1156
+			? $requires_payment
1157
+			: EEM_Registration::reg_statuses_that_allow_payment();
1158
+		if (
1159
+			in_array($this->status_ID(), $requires_payment) &&
1160
+			$this->final_price() != 0 &&
1161
+			$this->final_price() != $this->paid()
1162
+		) {
1163
+			return true;
1164
+		} else {
1165
+			return false;
1166
+		}
1167
+	}
1168
+
1169
+
1170
+	/**
1171
+	 * Prints out the return value of $this->pretty_status()
1172
+	 *
1173
+	 * @param bool $show_icons
1174
+	 * @return void
1175
+	 * @throws EE_Error
1176
+	 */
1177
+	public function e_pretty_status($show_icons = false)
1178
+	{
1179
+		echo wp_kses($this->pretty_status($show_icons), AllowedTags::getAllowedTags());
1180
+	}
1181
+
1182
+
1183
+	/**
1184
+	 * Returns a nice version of the status for displaying to customers
1185
+	 *
1186
+	 * @param bool $show_icons
1187
+	 * @return string
1188
+	 * @throws EE_Error
1189
+	 */
1190
+	public function pretty_status($show_icons = false)
1191
+	{
1192
+		$status = EEM_Status::instance()->localized_status(
1193
+			array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1194
+			false,
1195
+			'sentence'
1196
+		);
1197
+		$icon = '';
1198
+		switch ($this->status_ID()) {
1199
+			case EEM_Registration::status_id_approved:
1200
+				$icon = $show_icons
1201
+					? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1202
+					: '';
1203
+				break;
1204
+			case EEM_Registration::status_id_pending_payment:
1205
+				$icon = $show_icons
1206
+					? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1207
+					: '';
1208
+				break;
1209
+			case EEM_Registration::status_id_not_approved:
1210
+				$icon = $show_icons
1211
+					? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1212
+					: '';
1213
+				break;
1214
+			case EEM_Registration::status_id_cancelled:
1215
+				$icon = $show_icons
1216
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1217
+					: '';
1218
+				break;
1219
+			case EEM_Registration::status_id_incomplete:
1220
+				$icon = $show_icons
1221
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1222
+					: '';
1223
+				break;
1224
+			case EEM_Registration::status_id_declined:
1225
+				$icon = $show_icons
1226
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1227
+					: '';
1228
+				break;
1229
+			case EEM_Registration::status_id_wait_list:
1230
+				$icon = $show_icons
1231
+					? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1232
+					: '';
1233
+				break;
1234
+		}
1235
+		return $icon . $status[ $this->status_ID() ];
1236
+	}
1237
+
1238
+
1239
+	/**
1240
+	 *        get Attendee Is Going
1241
+	 */
1242
+	public function att_is_going()
1243
+	{
1244
+		return $this->get('REG_att_is_going');
1245
+	}
1246
+
1247
+
1248
+	/**
1249
+	 * Gets related answers
1250
+	 *
1251
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1252
+	 * @return EE_Answer[]
1253
+	 * @throws EE_Error
1254
+	 */
1255
+	public function answers($query_params = null)
1256
+	{
1257
+		return $this->get_many_related('Answer', $query_params);
1258
+	}
1259
+
1260
+
1261
+	/**
1262
+	 * Gets the registration's answer value to the specified question
1263
+	 * (either the question's ID or a question object)
1264
+	 *
1265
+	 * @param EE_Question|int $question
1266
+	 * @param bool            $pretty_value
1267
+	 * @return array|string if pretty_value= true, the result will always be a string
1268
+	 * (because the answer might be an array of answer values, so passing pretty_value=true
1269
+	 * will convert it into some kind of string)
1270
+	 * @throws EE_Error
1271
+	 */
1272
+	public function answer_value_to_question($question, $pretty_value = true)
1273
+	{
1274
+		$question_id = EEM_Question::instance()->ensure_is_ID($question);
1275
+		return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * question_groups
1281
+	 * returns an array of EE_Question_Group objects for this registration
1282
+	 *
1283
+	 * @return EE_Question_Group[]
1284
+	 * @throws EE_Error
1285
+	 * @throws InvalidArgumentException
1286
+	 * @throws InvalidDataTypeException
1287
+	 * @throws InvalidInterfaceException
1288
+	 * @throws ReflectionException
1289
+	 */
1290
+	public function question_groups()
1291
+	{
1292
+		return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1293
+	}
1294
+
1295
+
1296
+	/**
1297
+	 * count_question_groups
1298
+	 * returns a count of the number of EE_Question_Group objects for this registration
1299
+	 *
1300
+	 * @return int
1301
+	 * @throws EE_Error
1302
+	 * @throws EntityNotFoundException
1303
+	 * @throws InvalidArgumentException
1304
+	 * @throws InvalidDataTypeException
1305
+	 * @throws InvalidInterfaceException
1306
+	 * @throws ReflectionException
1307
+	 */
1308
+	public function count_question_groups()
1309
+	{
1310
+		return EEM_Event::instance()->count_related(
1311
+			$this->event_ID(),
1312
+			'Question_Group',
1313
+			[
1314
+				[
1315
+					'Event_Question_Group.'
1316
+					. EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1317
+				]
1318
+			]
1319
+		);
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * Returns the registration date in the 'standard' string format
1325
+	 * (function may be improved in the future to allow for different formats and timezones)
1326
+	 *
1327
+	 * @return string
1328
+	 * @throws EE_Error
1329
+	 */
1330
+	public function reg_date()
1331
+	{
1332
+		return $this->get_datetime('REG_date');
1333
+	}
1334
+
1335
+
1336
+	/**
1337
+	 * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1338
+	 * the ticket this registration purchased, or the datetime they have registered
1339
+	 * to attend)
1340
+	 *
1341
+	 * @return EE_Datetime_Ticket
1342
+	 * @throws EE_Error
1343
+	 */
1344
+	public function datetime_ticket()
1345
+	{
1346
+		return $this->get_first_related('Datetime_Ticket');
1347
+	}
1348
+
1349
+
1350
+	/**
1351
+	 * Sets the registration's datetime_ticket.
1352
+	 *
1353
+	 * @param EE_Datetime_Ticket $datetime_ticket
1354
+	 * @return EE_Datetime_Ticket
1355
+	 * @throws EE_Error
1356
+	 */
1357
+	public function set_datetime_ticket($datetime_ticket)
1358
+	{
1359
+		return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1360
+	}
1361
+
1362
+	/**
1363
+	 * Gets deleted
1364
+	 *
1365
+	 * @return bool
1366
+	 * @throws EE_Error
1367
+	 */
1368
+	public function deleted()
1369
+	{
1370
+		return $this->get('REG_deleted');
1371
+	}
1372
+
1373
+	/**
1374
+	 * Sets deleted
1375
+	 *
1376
+	 * @param boolean $deleted
1377
+	 * @return bool
1378
+	 * @throws EE_Error
1379
+	 * @throws RuntimeException
1380
+	 */
1381
+	public function set_deleted($deleted)
1382
+	{
1383
+		if ($deleted) {
1384
+			$this->delete();
1385
+		} else {
1386
+			$this->restore();
1387
+		}
1388
+	}
1389
+
1390
+
1391
+	/**
1392
+	 * Get the status object of this object
1393
+	 *
1394
+	 * @return EE_Status
1395
+	 * @throws EE_Error
1396
+	 */
1397
+	public function status_obj()
1398
+	{
1399
+		return $this->get_first_related('Status');
1400
+	}
1401
+
1402
+
1403
+	/**
1404
+	 * Returns the number of times this registration has checked into any of the datetimes
1405
+	 * its available for
1406
+	 *
1407
+	 * @return int
1408
+	 * @throws EE_Error
1409
+	 */
1410
+	public function count_checkins()
1411
+	{
1412
+		return $this->get_model()->count_related($this, 'Checkin');
1413
+	}
1414
+
1415
+
1416
+	/**
1417
+	 * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1418
+	 * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1419
+	 *
1420
+	 * @return int
1421
+	 * @throws EE_Error
1422
+	 */
1423
+	public function count_checkins_not_checkedout()
1424
+	{
1425
+		return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1426
+	}
1427
+
1428
+
1429
+	/**
1430
+	 * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1431
+	 *
1432
+	 * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1433
+	 * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1434
+	 *                                          consider registration status as well as datetime access.
1435
+	 * @return bool
1436
+	 * @throws EE_Error
1437
+	 */
1438
+	public function can_checkin($DTT_OR_ID, $check_approved = true)
1439
+	{
1440
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1441
+
1442
+		// first check registration status
1443
+		if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1444
+			return false;
1445
+		}
1446
+		// is there a datetime ticket that matches this dtt_ID?
1447
+		if (
1448
+			! (EEM_Datetime_Ticket::instance()->exists(
1449
+				array(
1450
+				array(
1451
+					'TKT_ID' => $this->get('TKT_ID'),
1452
+					'DTT_ID' => $DTT_ID,
1453
+				),
1454
+				)
1455
+			))
1456
+		) {
1457
+			return false;
1458
+		}
1459
+
1460
+		// final check is against TKT_uses
1461
+		return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1462
+	}
1463
+
1464
+
1465
+	/**
1466
+	 * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1467
+	 * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1468
+	 * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1469
+	 * then return false.  Otherwise return true.
1470
+	 *
1471
+	 * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1472
+	 * @return bool true means can checkin.  false means cannot checkin.
1473
+	 * @throws EE_Error
1474
+	 */
1475
+	public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1476
+	{
1477
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1478
+
1479
+		if (! $DTT_ID) {
1480
+			return false;
1481
+		}
1482
+
1483
+		$max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1484
+
1485
+		// if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1486
+		// check-in or not.
1487
+		if (! $max_uses || $max_uses === EE_INF) {
1488
+			return true;
1489
+		}
1490
+
1491
+		// does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1492
+		// go ahead and toggle.
1493
+		if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1494
+			return true;
1495
+		}
1496
+
1497
+		// made it here so the last check is whether the number of checkins per unique datetime on this registration
1498
+		// disallows further check-ins.
1499
+		$count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1500
+			array(
1501
+				array(
1502
+					'REG_ID' => $this->ID(),
1503
+					'CHK_in' => true,
1504
+				),
1505
+			),
1506
+			'DTT_ID',
1507
+			true
1508
+		);
1509
+		// checkins have already reached their max number of uses
1510
+		// so registrant can NOT checkin
1511
+		if ($count_unique_dtt_checkins >= $max_uses) {
1512
+			EE_Error::add_error(
1513
+				esc_html__(
1514
+					'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1515
+					'event_espresso'
1516
+				),
1517
+				__FILE__,
1518
+				__FUNCTION__,
1519
+				__LINE__
1520
+			);
1521
+			return false;
1522
+		}
1523
+		return true;
1524
+	}
1525
+
1526
+
1527
+	/**
1528
+	 * toggle Check-in status for this registration
1529
+	 * Check-ins are toggled in the following order:
1530
+	 * never checked in -> checked in
1531
+	 * checked in -> checked out
1532
+	 * checked out -> checked in
1533
+	 *
1534
+	 * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1535
+	 *                      If not included or null, then it is assumed latest datetime is being toggled.
1536
+	 * @param bool $verify  If true then can_checkin() is used to verify whether the person
1537
+	 *                      can be checked in or not.  Otherwise this forces change in checkin status.
1538
+	 * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1539
+	 * @throws EE_Error
1540
+	 */
1541
+	public function toggle_checkin_status($DTT_ID = null, $verify = false)
1542
+	{
1543
+		if (empty($DTT_ID)) {
1544
+			$datetime = $this->get_latest_related_datetime();
1545
+			$DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1546
+			// verify the registration can checkin for the given DTT_ID
1547
+		} elseif (! $this->can_checkin($DTT_ID, $verify)) {
1548
+			EE_Error::add_error(
1549
+				sprintf(
1550
+					esc_html__(
1551
+						'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1552
+						'event_espresso'
1553
+					),
1554
+					$this->ID(),
1555
+					$DTT_ID
1556
+				),
1557
+				__FILE__,
1558
+				__FUNCTION__,
1559
+				__LINE__
1560
+			);
1561
+			return false;
1562
+		}
1563
+		$status_paths = array(
1564
+			EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1565
+			EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1566
+			EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1567
+		);
1568
+		// start by getting the current status so we know what status we'll be changing to.
1569
+		$cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1570
+		$status_to = $status_paths[ $cur_status ];
1571
+		// database only records true for checked IN or false for checked OUT
1572
+		// no record ( null ) means checked in NEVER, but we obviously don't save that
1573
+		$new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1574
+		// add relation - note Check-ins are always creating new rows
1575
+		// because we are keeping track of Check-ins over time.
1576
+		// Eventually we'll probably want to show a list table
1577
+		// for the individual Check-ins so that they can be managed.
1578
+		$checkin = EE_Checkin::new_instance(
1579
+			array(
1580
+				'REG_ID' => $this->ID(),
1581
+				'DTT_ID' => $DTT_ID,
1582
+				'CHK_in' => $new_status,
1583
+			)
1584
+		);
1585
+		// if the record could not be saved then return false
1586
+		if ($checkin->save() === 0) {
1587
+			if (WP_DEBUG) {
1588
+				global $wpdb;
1589
+				$error = sprintf(
1590
+					esc_html__(
1591
+						'Registration check in update failed because of the following database error: %1$s%2$s',
1592
+						'event_espresso'
1593
+					),
1594
+					'<br />',
1595
+					$wpdb->last_error
1596
+				);
1597
+			} else {
1598
+				$error = esc_html__(
1599
+					'Registration check in update failed because of an unknown database error',
1600
+					'event_espresso'
1601
+				);
1602
+			}
1603
+			EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1604
+			return false;
1605
+		}
1606
+		// Fire a checked_in and checkout_out action.
1607
+		$checked_status = $status_to === EE_Checkin::status_checked_in ? 'checked_in' : 'checked_out';
1608
+		do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1609
+		return $status_to;
1610
+	}
1611
+
1612
+
1613
+	/**
1614
+	 * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1615
+	 * "Latest" is defined by the `DTT_EVT_start` column.
1616
+	 *
1617
+	 * @return EE_Datetime|null
1618
+	 * @throws EE_Error
1619
+	 */
1620
+	public function get_latest_related_datetime()
1621
+	{
1622
+		return EEM_Datetime::instance()->get_one(
1623
+			array(
1624
+				array(
1625
+					'Ticket.Registration.REG_ID' => $this->ID(),
1626
+				),
1627
+				'order_by' => array('DTT_EVT_start' => 'DESC'),
1628
+			)
1629
+		);
1630
+	}
1631
+
1632
+
1633
+	/**
1634
+	 * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1635
+	 * "Earliest" is defined by the `DTT_EVT_start` column.
1636
+	 *
1637
+	 * @throws EE_Error
1638
+	 */
1639
+	public function get_earliest_related_datetime()
1640
+	{
1641
+		return EEM_Datetime::instance()->get_one(
1642
+			array(
1643
+				array(
1644
+					'Ticket.Registration.REG_ID' => $this->ID(),
1645
+				),
1646
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
1647
+			)
1648
+		);
1649
+	}
1650
+
1651
+
1652
+	/**
1653
+	 * This method simply returns the check-in status for this registration and the given datetime.
1654
+	 * If neither the datetime nor the checkin values are provided as arguments,
1655
+	 * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1656
+	 *
1657
+	 * @param  int       $DTT_ID  The ID of the datetime we're checking against
1658
+	 *                            (if empty we'll get the primary datetime for
1659
+	 *                            this registration (via event) and use it's ID);
1660
+	 * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1661
+	 *
1662
+	 * @return int                Integer representing Check-in status.
1663
+	 * @throws EE_Error
1664
+	 */
1665
+	public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1666
+	{
1667
+		$checkin_query_params = array(
1668
+			'order_by' => array('CHK_timestamp' => 'DESC'),
1669
+		);
1670
+
1671
+		if ($DTT_ID > 0) {
1672
+			$checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1673
+		}
1674
+
1675
+		// get checkin object (if exists)
1676
+		$checkin = $checkin instanceof EE_Checkin
1677
+			? $checkin
1678
+			: $this->get_first_related('Checkin', $checkin_query_params);
1679
+		if ($checkin instanceof EE_Checkin) {
1680
+			if ($checkin->get('CHK_in')) {
1681
+				return EE_Checkin::status_checked_in; // checked in
1682
+			}
1683
+			return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1684
+		}
1685
+		return EE_Checkin::status_checked_never; // never been checked in
1686
+	}
1687
+
1688
+
1689
+	/**
1690
+	 * This method returns a localized message for the toggled Check-in message.
1691
+	 *
1692
+	 * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1693
+	 *                     then it is assumed Check-in for primary datetime was toggled.
1694
+	 * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1695
+	 *                     message can be customized with the attendee name.
1696
+	 * @return string internationalized message
1697
+	 * @throws EE_Error
1698
+	 */
1699
+	public function get_checkin_msg($DTT_ID, $error = false)
1700
+	{
1701
+		// let's get the attendee first so we can include the name of the attendee
1702
+		$attendee = $this->get_first_related('Attendee');
1703
+		if ($attendee instanceof EE_Attendee) {
1704
+			if ($error) {
1705
+				return sprintf(esc_html__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1706
+			}
1707
+			$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1708
+			// what is the status message going to be?
1709
+			switch ($cur_status) {
1710
+				case EE_Checkin::status_checked_never:
1711
+					return sprintf(
1712
+						esc_html__("%s has been removed from Check-in records", "event_espresso"),
1713
+						$attendee->full_name()
1714
+					);
1715
+					break;
1716
+				case EE_Checkin::status_checked_in:
1717
+					return sprintf(esc_html__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1718
+					break;
1719
+				case EE_Checkin::status_checked_out:
1720
+					return sprintf(esc_html__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1721
+					break;
1722
+			}
1723
+		}
1724
+		return esc_html__("The check-in status could not be determined.", "event_espresso");
1725
+	}
1726
+
1727
+
1728
+	/**
1729
+	 * Returns the related EE_Transaction to this registration
1730
+	 *
1731
+	 * @return EE_Transaction
1732
+	 * @throws EE_Error
1733
+	 * @throws EntityNotFoundException
1734
+	 */
1735
+	public function transaction()
1736
+	{
1737
+		$transaction = $this->get_first_related('Transaction');
1738
+		if (! $transaction instanceof \EE_Transaction) {
1739
+			throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1740
+		}
1741
+		return $transaction;
1742
+	}
1743
+
1744
+
1745
+	/**
1746
+	 *        get Registration Code
1747
+	 */
1748
+	public function reg_code()
1749
+	{
1750
+		return $this->get('REG_code');
1751
+	}
1752
+
1753
+
1754
+	/**
1755
+	 *        get Transaction ID
1756
+	 */
1757
+	public function transaction_ID()
1758
+	{
1759
+		return $this->get('TXN_ID');
1760
+	}
1761
+
1762
+
1763
+	/**
1764
+	 * @return int
1765
+	 * @throws EE_Error
1766
+	 */
1767
+	public function ticket_ID()
1768
+	{
1769
+		return $this->get('TKT_ID');
1770
+	}
1771
+
1772
+
1773
+	/**
1774
+	 *        Set Registration Code
1775
+	 *
1776
+	 * @access    public
1777
+	 * @param    string  $REG_code Registration Code
1778
+	 * @param    boolean $use_default
1779
+	 * @throws EE_Error
1780
+	 */
1781
+	public function set_reg_code($REG_code, $use_default = false)
1782
+	{
1783
+		if (empty($REG_code)) {
1784
+			EE_Error::add_error(
1785
+				esc_html__('REG_code can not be empty.', 'event_espresso'),
1786
+				__FILE__,
1787
+				__FUNCTION__,
1788
+				__LINE__
1789
+			);
1790
+			return;
1791
+		}
1792
+		if (! $this->reg_code()) {
1793
+			parent::set('REG_code', $REG_code, $use_default);
1794
+		} else {
1795
+			EE_Error::doing_it_wrong(
1796
+				__CLASS__ . '::' . __FUNCTION__,
1797
+				esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1798
+				'4.6.0'
1799
+			);
1800
+		}
1801
+	}
1802
+
1803
+
1804
+	/**
1805
+	 * Returns all other registrations in the same group as this registrant who have the same ticket option.
1806
+	 * Note, if you want to just get all registrations in the same transaction (group), use:
1807
+	 *    $registration->transaction()->registrations();
1808
+	 *
1809
+	 * @since 4.5.0
1810
+	 * @return EE_Registration[] or empty array if this isn't a group registration.
1811
+	 * @throws EE_Error
1812
+	 */
1813
+	public function get_all_other_registrations_in_group()
1814
+	{
1815
+		if ($this->group_size() < 2) {
1816
+			return array();
1817
+		}
1818
+
1819
+		$query[0] = array(
1820
+			'TXN_ID' => $this->transaction_ID(),
1821
+			'REG_ID' => array('!=', $this->ID()),
1822
+			'TKT_ID' => $this->ticket_ID(),
1823
+		);
1824
+		/** @var EE_Registration[] $registrations */
1825
+		$registrations = $this->get_model()->get_all($query);
1826
+		return $registrations;
1827
+	}
1828
+
1829
+	/**
1830
+	 * Return the link to the admin details for the object.
1831
+	 *
1832
+	 * @return string
1833
+	 * @throws EE_Error
1834
+	 */
1835
+	public function get_admin_details_link()
1836
+	{
1837
+		EE_Registry::instance()->load_helper('URL');
1838
+		return EEH_URL::add_query_args_and_nonce(
1839
+			array(
1840
+				'page'    => 'espresso_registrations',
1841
+				'action'  => 'view_registration',
1842
+				'_REG_ID' => $this->ID(),
1843
+			),
1844
+			admin_url('admin.php')
1845
+		);
1846
+	}
1847
+
1848
+	/**
1849
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1850
+	 *
1851
+	 * @return string
1852
+	 * @throws EE_Error
1853
+	 */
1854
+	public function get_admin_edit_link()
1855
+	{
1856
+		return $this->get_admin_details_link();
1857
+	}
1858
+
1859
+	/**
1860
+	 * Returns the link to a settings page for the object.
1861
+	 *
1862
+	 * @return string
1863
+	 * @throws EE_Error
1864
+	 */
1865
+	public function get_admin_settings_link()
1866
+	{
1867
+		return $this->get_admin_details_link();
1868
+	}
1869
+
1870
+	/**
1871
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
1872
+	 *
1873
+	 * @return string
1874
+	 */
1875
+	public function get_admin_overview_link()
1876
+	{
1877
+		EE_Registry::instance()->load_helper('URL');
1878
+		return EEH_URL::add_query_args_and_nonce(
1879
+			array(
1880
+				'page' => 'espresso_registrations',
1881
+			),
1882
+			admin_url('admin.php')
1883
+		);
1884
+	}
1885
+
1886
+
1887
+	/**
1888
+	 * @param array $query_params
1889
+	 *
1890
+	 * @return \EE_Registration[]
1891
+	 * @throws EE_Error
1892
+	 */
1893
+	public function payments($query_params = array())
1894
+	{
1895
+		return $this->get_many_related('Payment', $query_params);
1896
+	}
1897
+
1898
+
1899
+	/**
1900
+	 * @param array $query_params
1901
+	 *
1902
+	 * @return \EE_Registration_Payment[]
1903
+	 * @throws EE_Error
1904
+	 */
1905
+	public function registration_payments($query_params = array())
1906
+	{
1907
+		return $this->get_many_related('Registration_Payment', $query_params);
1908
+	}
1909
+
1910
+
1911
+	/**
1912
+	 * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1913
+	 * Note: if there are no payments on the registration there will be no payment method returned.
1914
+	 *
1915
+	 * @return EE_Payment_Method|null
1916
+	 */
1917
+	public function payment_method()
1918
+	{
1919
+		return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1920
+	}
1921
+
1922
+
1923
+	/**
1924
+	 * @return \EE_Line_Item
1925
+	 * @throws EntityNotFoundException
1926
+	 * @throws EE_Error
1927
+	 */
1928
+	public function ticket_line_item()
1929
+	{
1930
+		$ticket = $this->ticket();
1931
+		$transaction = $this->transaction();
1932
+		$line_item = null;
1933
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1934
+			$transaction->total_line_item(),
1935
+			'Ticket',
1936
+			array($ticket->ID())
1937
+		);
1938
+		foreach ($ticket_line_items as $ticket_line_item) {
1939
+			if (
1940
+				$ticket_line_item instanceof \EE_Line_Item
1941
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
1942
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
1943
+			) {
1944
+				$line_item = $ticket_line_item;
1945
+				break;
1946
+			}
1947
+		}
1948
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1949
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1950
+		}
1951
+		return $line_item;
1952
+	}
1953
+
1954
+
1955
+	/**
1956
+	 * Soft Deletes this model object.
1957
+	 *
1958
+	 * @return boolean | int
1959
+	 * @throws RuntimeException
1960
+	 * @throws EE_Error
1961
+	 */
1962
+	public function delete()
1963
+	{
1964
+		if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1965
+			$this->set_status(EEM_Registration::status_id_cancelled);
1966
+		}
1967
+		return parent::delete();
1968
+	}
1969
+
1970
+
1971
+	/**
1972
+	 * Restores whatever the previous status was on a registration before it was trashed (if possible)
1973
+	 *
1974
+	 * @throws EE_Error
1975
+	 * @throws RuntimeException
1976
+	 */
1977
+	public function restore()
1978
+	{
1979
+		$previous_status = $this->get_extra_meta(
1980
+			EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1981
+			true,
1982
+			EEM_Registration::status_id_cancelled
1983
+		);
1984
+		if ($previous_status) {
1985
+			$this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1986
+			$this->set_status($previous_status);
1987
+		}
1988
+		return parent::restore();
1989
+	}
1990
+
1991
+
1992
+	/**
1993
+	 * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1994
+	 *
1995
+	 * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1996
+	 *                                           depending on whether the reg status changes to or from "Approved"
1997
+	 * @return boolean whether the Registration status was updated
1998
+	 * @throws EE_Error
1999
+	 * @throws RuntimeException
2000
+	 */
2001
+	public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
2002
+	{
2003
+		$paid = $this->paid();
2004
+		$price = $this->final_price();
2005
+		switch (true) {
2006
+			// overpaid or paid
2007
+			case EEH_Money::compare_floats($paid, $price, '>'):
2008
+			case EEH_Money::compare_floats($paid, $price):
2009
+				$new_status = EEM_Registration::status_id_approved;
2010
+				break;
2011
+			//  underpaid
2012
+			case EEH_Money::compare_floats($paid, $price, '<'):
2013
+				$new_status = EEM_Registration::status_id_pending_payment;
2014
+				break;
2015
+			// uhhh Houston...
2016
+			default:
2017
+				throw new RuntimeException(
2018
+					esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2019
+				);
2020
+		}
2021
+		if ($new_status !== $this->status_ID()) {
2022
+			if ($trigger_set_status_logic) {
2023
+				return $this->set_status($new_status);
2024
+			}
2025
+			parent::set('STS_ID', $new_status);
2026
+			return true;
2027
+		}
2028
+		return false;
2029
+	}
2030
+
2031
+
2032
+	/*************************** DEPRECATED ***************************/
2033
+
2034
+
2035
+	/**
2036
+	 * @deprecated
2037
+	 * @since     4.7.0
2038
+	 * @access    public
2039
+	 */
2040
+	public function price_paid()
2041
+	{
2042
+		EE_Error::doing_it_wrong(
2043
+			'EE_Registration::price_paid()',
2044
+			esc_html__(
2045
+				'This method is deprecated, please use EE_Registration::final_price() instead.',
2046
+				'event_espresso'
2047
+			),
2048
+			'4.7.0'
2049
+		);
2050
+		return $this->final_price();
2051
+	}
2052
+
2053
+
2054
+	/**
2055
+	 * @deprecated
2056
+	 * @since     4.7.0
2057
+	 * @access    public
2058
+	 * @param    float $REG_final_price
2059
+	 * @throws EE_Error
2060
+	 * @throws RuntimeException
2061
+	 */
2062
+	public function set_price_paid($REG_final_price = 0.00)
2063
+	{
2064
+		EE_Error::doing_it_wrong(
2065
+			'EE_Registration::set_price_paid()',
2066
+			esc_html__(
2067
+				'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2068
+				'event_espresso'
2069
+			),
2070
+			'4.7.0'
2071
+		);
2072
+		$this->set_final_price($REG_final_price);
2073
+	}
2074
+
2075
+
2076
+	/**
2077
+	 * @deprecated
2078
+	 * @since 4.7.0
2079
+	 * @return string
2080
+	 * @throws EE_Error
2081
+	 */
2082
+	public function pretty_price_paid()
2083
+	{
2084
+		EE_Error::doing_it_wrong(
2085
+			'EE_Registration::pretty_price_paid()',
2086
+			esc_html__(
2087
+				'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2088
+				'event_espresso'
2089
+			),
2090
+			'4.7.0'
2091
+		);
2092
+		return $this->pretty_final_price();
2093
+	}
2094
+
2095
+
2096
+	/**
2097
+	 * Gets the primary datetime related to this registration via the related Event to this registration
2098
+	 *
2099
+	 * @deprecated 4.9.17
2100
+	 * @return EE_Datetime
2101
+	 * @throws EE_Error
2102
+	 * @throws EntityNotFoundException
2103
+	 */
2104
+	public function get_related_primary_datetime()
2105
+	{
2106
+		EE_Error::doing_it_wrong(
2107
+			__METHOD__,
2108
+			esc_html__(
2109
+				'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2110
+				'event_espresso'
2111
+			),
2112
+			'4.9.17',
2113
+			'5.0.0'
2114
+		);
2115
+		return $this->event()->primary_datetime();
2116
+	}
2117
+
2118
+	/**
2119
+	 * Returns the contact's name (or "Unknown" if there is no contact.)
2120
+	 * @since 4.10.12.p
2121
+	 * @return string
2122
+	 * @throws EE_Error
2123
+	 * @throws InvalidArgumentException
2124
+	 * @throws InvalidDataTypeException
2125
+	 * @throws InvalidInterfaceException
2126
+	 * @throws ReflectionException
2127
+	 */
2128
+	public function name()
2129
+	{
2130
+		return $this->attendeeName();
2131
+	}
2132 2132
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Spacing   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
         $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147 147
         // verify client code has not passed any invalid field names
148 148
         foreach ($fieldValues as $field_name => $field_value) {
149
-            if (! isset($model_fields[ $field_name ])) {
149
+            if ( ! isset($model_fields[$field_name])) {
150 150
                 throw new EE_Error(
151 151
                     sprintf(
152 152
                         esc_html__(
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
             }
162 162
         }
163 163
         $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
-        if (! empty($date_formats) && is_array($date_formats)) {
164
+        if ( ! empty($date_formats) && is_array($date_formats)) {
165 165
             list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
166 166
         } else {
167 167
             // set default formats for date and time
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
             foreach ($model_fields as $fieldName => $field) {
175 175
                 $this->set_from_db(
176 176
                     $fieldName,
177
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
177
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null
178 178
                 );
179 179
             }
180 180
         } else {
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
             foreach ($model_fields as $fieldName => $field) {
184 184
                 $this->set(
185 185
                     $fieldName,
186
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
186
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null,
187 187
                     true
188 188
                 );
189 189
             }
@@ -191,15 +191,15 @@  discard block
 block discarded – undo
191 191
         // remember what values were passed to this constructor
192 192
         $this->_props_n_values_provided_in_constructor = $fieldValues;
193 193
         // remember in entity mapper
194
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
194
+        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
195 195
             $model->add_to_entity_map($this);
196 196
         }
197 197
         // setup all the relations
198 198
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199 199
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
-                $this->_model_relations[ $relation_name ] = null;
200
+                $this->_model_relations[$relation_name] = null;
201 201
             } else {
202
-                $this->_model_relations[ $relation_name ] = array();
202
+                $this->_model_relations[$relation_name] = array();
203 203
             }
204 204
         }
205 205
         /**
@@ -251,10 +251,10 @@  discard block
 block discarded – undo
251 251
     public function get_original($field_name)
252 252
     {
253 253
         if (
254
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
254
+            isset($this->_props_n_values_provided_in_constructor[$field_name])
255 255
             && $field_settings = $this->get_model()->field_settings_for($field_name)
256 256
         ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
257
+            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
258 258
         }
259 259
         return null;
260 260
     }
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
         // then don't do anything
292 292
         if (
293 293
             ! $use_default
294
-            && $this->_fields[ $field_name ] === $field_value
294
+            && $this->_fields[$field_name] === $field_value
295 295
             && $this->ID()
296 296
         ) {
297 297
             return;
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
             $holder_of_value = $field_obj->prepare_for_set($field_value);
310 310
             // should the value be null?
311 311
             if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
312
+                $this->_fields[$field_name] = $field_obj->get_default_value();
313 313
                 /**
314 314
                  * To save having to refactor all the models, if a default value is used for a
315 315
                  * EE_Datetime_Field, and that value is not null nor is it a DateTime
@@ -320,15 +320,15 @@  discard block
 block discarded – undo
320 320
                  */
321 321
                 if (
322 322
                     $field_obj instanceof EE_Datetime_Field
323
-                    && $this->_fields[ $field_name ] !== null
324
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
323
+                    && $this->_fields[$field_name] !== null
324
+                    && ! $this->_fields[$field_name] instanceof DateTime
325 325
                 ) {
326
-                    empty($this->_fields[ $field_name ])
326
+                    empty($this->_fields[$field_name])
327 327
                         ? $this->set($field_name, time())
328
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
328
+                        : $this->set($field_name, $this->_fields[$field_name]);
329 329
                 }
330 330
             } else {
331
-                $this->_fields[ $field_name ] = $holder_of_value;
331
+                $this->_fields[$field_name] = $holder_of_value;
332 332
             }
333 333
             // if we're not in the constructor...
334 334
             // now check if what we set was a primary key
@@ -391,8 +391,8 @@  discard block
 block discarded – undo
391 391
      */
392 392
     public function getCustomSelect($alias)
393 393
     {
394
-        return isset($this->custom_selection_results[ $alias ])
395
-            ? $this->custom_selection_results[ $alias ]
394
+        return isset($this->custom_selection_results[$alias])
395
+            ? $this->custom_selection_results[$alias]
396 396
             : null;
397 397
     }
398 398
 
@@ -479,8 +479,8 @@  discard block
 block discarded – undo
479 479
         foreach ($model_fields as $field_name => $field_obj) {
480 480
             if ($field_obj instanceof EE_Datetime_Field) {
481 481
                 $field_obj->set_timezone($this->_timezone);
482
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
482
+                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
483
+                    EEH_DTT_Helper::setTimezone($this->_fields[$field_name], new DateTimeZone($this->_timezone));
484 484
                 }
485 485
             }
486 486
         }
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
      */
539 539
     public function get_format($full = true)
540 540
     {
541
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
541
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542 542
     }
543 543
 
544 544
 
@@ -564,11 +564,11 @@  discard block
 block discarded – undo
564 564
     public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565 565
     {
566 566
         // its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
-        if (! $object_to_cache instanceof EE_Base_Class) {
567
+        if ( ! $object_to_cache instanceof EE_Base_Class) {
568 568
             return false;
569 569
         }
570 570
         // also get "how" the object is related, or throw an error
571
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
571
+        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572 572
             throw new EE_Error(
573 573
                 sprintf(
574 574
                     esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
@@ -582,38 +582,38 @@  discard block
 block discarded – undo
582 582
             // if it's a "belongs to" relationship, then there's only one related model object
583 583
             // eg, if this is a registration, there's only 1 attendee for it
584 584
             // so for these model objects just set it to be cached
585
-            $this->_model_relations[ $relationName ] = $object_to_cache;
585
+            $this->_model_relations[$relationName] = $object_to_cache;
586 586
             $return = true;
587 587
         } else {
588 588
             // otherwise, this is the "many" side of a one to many relationship,
589 589
             // so we'll add the object to the array of related objects for that type.
590 590
             // eg: if this is an event, there are many registrations for that event,
591 591
             // so we cache the registrations in an array
592
-            if (! is_array($this->_model_relations[ $relationName ])) {
592
+            if ( ! is_array($this->_model_relations[$relationName])) {
593 593
                 // if for some reason, the cached item is a model object,
594 594
                 // then stick that in the array, otherwise start with an empty array
595
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
595
+                $this->_model_relations[$relationName] = $this->_model_relations[$relationName]
596 596
                                                            instanceof
597 597
                                                            EE_Base_Class
598
-                    ? array($this->_model_relations[ $relationName ]) : array();
598
+                    ? array($this->_model_relations[$relationName]) : array();
599 599
             }
600 600
             // first check for a cache_id which is normally empty
601
-            if (! empty($cache_id)) {
601
+            if ( ! empty($cache_id)) {
602 602
                 // if the cache_id exists, then it means we are purposely trying to cache this
603 603
                 // with a known key that can then be used to retrieve the object later on
604
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
604
+                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
605 605
                 $return = $cache_id;
606 606
             } elseif ($object_to_cache->ID()) {
607 607
                 // OR the cached object originally came from the db, so let's just use it's PK for an ID
608
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
608
+                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
609 609
                 $return = $object_to_cache->ID();
610 610
             } else {
611 611
                 // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
612
+                $this->_model_relations[$relationName][] = $object_to_cache;
613 613
                 // move the internal pointer to the end of the array
614
-                end($this->_model_relations[ $relationName ]);
614
+                end($this->_model_relations[$relationName]);
615 615
                 // and grab the key so that we can return it
616
-                $return = key($this->_model_relations[ $relationName ]);
616
+                $return = key($this->_model_relations[$relationName]);
617 617
             }
618 618
         }
619 619
         return $return;
@@ -639,7 +639,7 @@  discard block
 block discarded – undo
639 639
         // first make sure this property exists
640 640
         $this->get_model()->field_settings_for($fieldname);
641 641
         $cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
642
+        $this->_cached_properties[$fieldname][$cache_type] = $value;
643 643
     }
644 644
 
645 645
 
@@ -668,9 +668,9 @@  discard block
 block discarded – undo
668 668
         $model = $this->get_model();
669 669
         $model->field_settings_for($fieldname);
670 670
         $cache_type = $pretty ? 'pretty' : 'standard';
671
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
671
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
672
+        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
673
+            return $this->_cached_properties[$fieldname][$cache_type];
674 674
         }
675 675
         $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676 676
         $this->_set_cached_property($fieldname, $value, $cache_type);
@@ -698,12 +698,12 @@  discard block
 block discarded – undo
698 698
         if ($field_obj instanceof EE_Datetime_Field) {
699 699
             $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700 700
         }
701
-        if (! isset($this->_fields[ $fieldname ])) {
702
-            $this->_fields[ $fieldname ] = null;
701
+        if ( ! isset($this->_fields[$fieldname])) {
702
+            $this->_fields[$fieldname] = null;
703 703
         }
704 704
         $value = $pretty
705
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
705
+            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
706
+            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
707 707
         return $value;
708 708
     }
709 709
 
@@ -761,8 +761,8 @@  discard block
 block discarded – undo
761 761
      */
762 762
     protected function _clear_cached_property($property_name)
763 763
     {
764
-        if (isset($this->_cached_properties[ $property_name ])) {
765
-            unset($this->_cached_properties[ $property_name ]);
764
+        if (isset($this->_cached_properties[$property_name])) {
765
+            unset($this->_cached_properties[$property_name]);
766 766
         }
767 767
     }
768 768
 
@@ -814,7 +814,7 @@  discard block
 block discarded – undo
814 814
     {
815 815
         $relationship_to_model = $this->get_model()->related_settings_for($relationName);
816 816
         $index_in_cache = '';
817
-        if (! $relationship_to_model) {
817
+        if ( ! $relationship_to_model) {
818 818
             throw new EE_Error(
819 819
                 sprintf(
820 820
                     esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
@@ -825,10 +825,10 @@  discard block
 block discarded – undo
825 825
         }
826 826
         if ($clear_all) {
827 827
             $obj_removed = true;
828
-            $this->_model_relations[ $relationName ] = null;
828
+            $this->_model_relations[$relationName] = null;
829 829
         } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
830
-            $obj_removed = $this->_model_relations[ $relationName ];
831
-            $this->_model_relations[ $relationName ] = null;
830
+            $obj_removed = $this->_model_relations[$relationName];
831
+            $this->_model_relations[$relationName] = null;
832 832
         } else {
833 833
             if (
834 834
                 $object_to_remove_or_index_into_array instanceof EE_Base_Class
@@ -836,12 +836,12 @@  discard block
 block discarded – undo
836 836
             ) {
837 837
                 $index_in_cache = $object_to_remove_or_index_into_array->ID();
838 838
                 if (
839
-                    is_array($this->_model_relations[ $relationName ])
840
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
839
+                    is_array($this->_model_relations[$relationName])
840
+                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
841 841
                 ) {
842 842
                     $index_found_at = null;
843 843
                     // find this object in the array even though it has a different key
844
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
844
+                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
845 845
                         /** @noinspection TypeUnsafeComparisonInspection */
846 846
                         if (
847 847
                             $obj instanceof EE_Base_Class
@@ -875,9 +875,9 @@  discard block
 block discarded – undo
875 875
             }
876 876
             // supposedly we've found it. But it could just be that the client code
877 877
             // provided a bad index/object
878
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
879
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
880
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
878
+            if (isset($this->_model_relations[$relationName][$index_in_cache])) {
879
+                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
880
+                unset($this->_model_relations[$relationName][$index_in_cache]);
881 881
             } else {
882 882
                 // that thing was never cached anyways.
883 883
                 $obj_removed = null;
@@ -908,7 +908,7 @@  discard block
 block discarded – undo
908 908
         $current_cache_id = ''
909 909
     ) {
910 910
         // verify that incoming object is of the correct type
911
-        $obj_class = 'EE_' . $relationName;
911
+        $obj_class = 'EE_'.$relationName;
912 912
         if ($newly_saved_object instanceof $obj_class) {
913 913
             /* @type EE_Base_Class $newly_saved_object */
914 914
             // now get the type of relation
@@ -916,18 +916,18 @@  discard block
 block discarded – undo
916 916
             // if this is a 1:1 relationship
917 917
             if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
918 918
                 // then just replace the cached object with the newly saved object
919
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
919
+                $this->_model_relations[$relationName] = $newly_saved_object;
920 920
                 return true;
921 921
                 // or if it's some kind of sordid feral polyamorous relationship...
922 922
             }
923 923
             if (
924
-                is_array($this->_model_relations[ $relationName ])
925
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
924
+                is_array($this->_model_relations[$relationName])
925
+                && isset($this->_model_relations[$relationName][$current_cache_id])
926 926
             ) {
927 927
                 // then remove the current cached item
928
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
928
+                unset($this->_model_relations[$relationName][$current_cache_id]);
929 929
                 // and cache the newly saved object using it's new ID
930
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
930
+                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
931 931
                 return true;
932 932
             }
933 933
         }
@@ -944,8 +944,8 @@  discard block
 block discarded – undo
944 944
      */
945 945
     public function get_one_from_cache($relationName)
946 946
     {
947
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
948
-            ? $this->_model_relations[ $relationName ]
947
+        $cached_array_or_object = isset($this->_model_relations[$relationName])
948
+            ? $this->_model_relations[$relationName]
949 949
             : null;
950 950
         if (is_array($cached_array_or_object)) {
951 951
             return array_shift($cached_array_or_object);
@@ -968,7 +968,7 @@  discard block
 block discarded – undo
968 968
      */
969 969
     public function get_all_from_cache($relationName)
970 970
     {
971
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
971
+        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
972 972
         // if the result is not an array, but exists, make it an array
973 973
         $objects = is_array($objects) ? $objects : array($objects);
974 974
         // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
@@ -1152,7 +1152,7 @@  discard block
 block discarded – undo
1152 1152
             } else {
1153 1153
                 $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1154 1154
             }
1155
-            $this->_fields[ $field_name ] = $field_value;
1155
+            $this->_fields[$field_name] = $field_value;
1156 1156
             $this->_clear_cached_property($field_name);
1157 1157
         }
1158 1158
     }
@@ -1192,9 +1192,9 @@  discard block
 block discarded – undo
1192 1192
     public function get_raw($field_name)
1193 1193
     {
1194 1194
         $field_settings = $this->get_model()->field_settings_for($field_name);
1195
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
-            ? $this->_fields[ $field_name ]->format('U')
1197
-            : $this->_fields[ $field_name ];
1195
+        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1196
+            ? $this->_fields[$field_name]->format('U')
1197
+            : $this->_fields[$field_name];
1198 1198
     }
1199 1199
 
1200 1200
 
@@ -1216,7 +1216,7 @@  discard block
 block discarded – undo
1216 1216
     public function get_DateTime_object($field_name)
1217 1217
     {
1218 1218
         $field_settings = $this->get_model()->field_settings_for($field_name);
1219
-        if (! $field_settings instanceof EE_Datetime_Field) {
1219
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1220 1220
             EE_Error::add_error(
1221 1221
                 sprintf(
1222 1222
                     esc_html__(
@@ -1231,8 +1231,8 @@  discard block
 block discarded – undo
1231 1231
             );
1232 1232
             return false;
1233 1233
         }
1234
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
-            ? clone $this->_fields[ $field_name ]
1234
+        return isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime
1235
+            ? clone $this->_fields[$field_name]
1236 1236
             : null;
1237 1237
     }
1238 1238
 
@@ -1474,7 +1474,7 @@  discard block
 block discarded – undo
1474 1474
      */
1475 1475
     public function get_i18n_datetime($field_name, $format = '')
1476 1476
     {
1477
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1477
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1478 1478
         return date_i18n(
1479 1479
             $format,
1480 1480
             EEH_DTT_Helper::get_timestamp_with_offset(
@@ -1586,21 +1586,21 @@  discard block
 block discarded – undo
1586 1586
         $field->set_time_format($this->_tm_frmt);
1587 1587
         switch ($what) {
1588 1588
             case 'T':
1589
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1589
+                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1590 1590
                     $datetime_value,
1591
-                    $this->_fields[ $fieldname ]
1591
+                    $this->_fields[$fieldname]
1592 1592
                 );
1593 1593
                 $this->_has_changes = true;
1594 1594
                 break;
1595 1595
             case 'D':
1596
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1596
+                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1597 1597
                     $datetime_value,
1598
-                    $this->_fields[ $fieldname ]
1598
+                    $this->_fields[$fieldname]
1599 1599
                 );
1600 1600
                 $this->_has_changes = true;
1601 1601
                 break;
1602 1602
             case 'B':
1603
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1603
+                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1604 1604
                 $this->_has_changes = true;
1605 1605
                 break;
1606 1606
         }
@@ -1643,7 +1643,7 @@  discard block
 block discarded – undo
1643 1643
         $this->set_timezone($timezone);
1644 1644
         $fn = (array) $field_name;
1645 1645
         $args = array_merge($fn, (array) $args);
1646
-        if (! method_exists($this, $callback)) {
1646
+        if ( ! method_exists($this, $callback)) {
1647 1647
             throw new EE_Error(
1648 1648
                 sprintf(
1649 1649
                     esc_html__(
@@ -1655,7 +1655,7 @@  discard block
 block discarded – undo
1655 1655
             );
1656 1656
         }
1657 1657
         $args = (array) $args;
1658
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1658
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1659 1659
         $this->set_timezone($original_timezone);
1660 1660
         return $return;
1661 1661
     }
@@ -1770,8 +1770,8 @@  discard block
 block discarded – undo
1770 1770
     {
1771 1771
         $model = $this->get_model();
1772 1772
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
-            if (! empty($this->_model_relations[ $relation_name ])) {
1774
-                $related_objects = $this->_model_relations[ $relation_name ];
1773
+            if ( ! empty($this->_model_relations[$relation_name])) {
1774
+                $related_objects = $this->_model_relations[$relation_name];
1775 1775
                 if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776 1776
                     // this relation only stores a single model object, not an array
1777 1777
                     // but let's make it consistent
@@ -1828,7 +1828,7 @@  discard block
 block discarded – undo
1828 1828
             $this->set($column, $value);
1829 1829
         }
1830 1830
         // no changes ? then don't do anything
1831
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1831
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1832 1832
             return 0;
1833 1833
         }
1834 1834
         /**
@@ -1838,7 +1838,7 @@  discard block
 block discarded – undo
1838 1838
          * @param EE_Base_Class $model_object the model object about to be saved.
1839 1839
          */
1840 1840
         do_action('AHEE__EE_Base_Class__save__begin', $this);
1841
-        if (! $this->allow_persist()) {
1841
+        if ( ! $this->allow_persist()) {
1842 1842
             return 0;
1843 1843
         }
1844 1844
         // now get current attribute values
@@ -1853,10 +1853,10 @@  discard block
 block discarded – undo
1853 1853
         if ($model->has_primary_key_field()) {
1854 1854
             if ($model->get_primary_key_field()->is_auto_increment()) {
1855 1855
                 // ok check if it's set, if so: update; if not, insert
1856
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1856
+                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1857 1857
                     $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1858 1858
                 } else {
1859
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1859
+                    unset($save_cols_n_values[$model->primary_key_name()]);
1860 1860
                     $results = $model->insert($save_cols_n_values);
1861 1861
                     if ($results) {
1862 1862
                         // if successful, set the primary key
@@ -1866,7 +1866,7 @@  discard block
 block discarded – undo
1866 1866
                         // will get added to the mapper before we can add this one!
1867 1867
                         // but if we just avoid using the SET method, all that headache can be avoided
1868 1868
                         $pk_field_name = $model->primary_key_name();
1869
-                        $this->_fields[ $pk_field_name ] = $results;
1869
+                        $this->_fields[$pk_field_name] = $results;
1870 1870
                         $this->_clear_cached_property($pk_field_name);
1871 1871
                         $model->add_to_entity_map($this);
1872 1872
                         $this->_update_cached_related_model_objs_fks();
@@ -1883,8 +1883,8 @@  discard block
 block discarded – undo
1883 1883
                                     'event_espresso'
1884 1884
                                 ),
1885 1885
                                 get_class($this),
1886
-                                get_class($model) . '::instance()->add_to_entity_map()',
1887
-                                get_class($model) . '::instance()->get_one_by_ID()',
1886
+                                get_class($model).'::instance()->add_to_entity_map()',
1887
+                                get_class($model).'::instance()->get_one_by_ID()',
1888 1888
                                 '<br />'
1889 1889
                             )
1890 1890
                         );
@@ -1986,27 +1986,27 @@  discard block
 block discarded – undo
1986 1986
     public function save_new_cached_related_model_objs()
1987 1987
     {
1988 1988
         // make sure this has been saved
1989
-        if (! $this->ID()) {
1989
+        if ( ! $this->ID()) {
1990 1990
             $id = $this->save();
1991 1991
         } else {
1992 1992
             $id = $this->ID();
1993 1993
         }
1994 1994
         // now save all the NEW cached model objects  (ie they don't exist in the DB)
1995 1995
         foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1996
-            if ($this->_model_relations[ $relationName ]) {
1996
+            if ($this->_model_relations[$relationName]) {
1997 1997
                 // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1998 1998
                 // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1999 1999
                 /* @var $related_model_obj EE_Base_Class */
2000 2000
                 if ($relationObj instanceof EE_Belongs_To_Relation) {
2001 2001
                     // add a relation to that relation type (which saves the appropriate thing in the process)
2002 2002
                     // but ONLY if it DOES NOT exist in the DB
2003
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2003
+                    $related_model_obj = $this->_model_relations[$relationName];
2004 2004
                     // if( ! $related_model_obj->ID()){
2005 2005
                     $this->_add_relation_to($related_model_obj, $relationName);
2006 2006
                     $related_model_obj->save_new_cached_related_model_objs();
2007 2007
                     // }
2008 2008
                 } else {
2009
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2009
+                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
2010 2010
                         // add a relation to that relation type (which saves the appropriate thing in the process)
2011 2011
                         // but ONLY if it DOES NOT exist in the DB
2012 2012
                         // if( ! $related_model_obj->ID()){
@@ -2033,7 +2033,7 @@  discard block
 block discarded – undo
2033 2033
      */
2034 2034
     public function get_model()
2035 2035
     {
2036
-        if (! $this->_model) {
2036
+        if ( ! $this->_model) {
2037 2037
             $modelName = self::_get_model_classname(get_class($this));
2038 2038
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2039 2039
         } else {
@@ -2059,9 +2059,9 @@  discard block
 block discarded – undo
2059 2059
         $primary_id_ref = self::_get_primary_key_name($classname);
2060 2060
         if (
2061 2061
             array_key_exists($primary_id_ref, $props_n_values)
2062
-            && ! empty($props_n_values[ $primary_id_ref ])
2062
+            && ! empty($props_n_values[$primary_id_ref])
2063 2063
         ) {
2064
-            $id = $props_n_values[ $primary_id_ref ];
2064
+            $id = $props_n_values[$primary_id_ref];
2065 2065
             return self::_get_model($classname)->get_from_entity_map($id);
2066 2066
         }
2067 2067
         return false;
@@ -2096,10 +2096,10 @@  discard block
 block discarded – undo
2096 2096
             $primary_id_ref = self::_get_primary_key_name($classname);
2097 2097
             if (
2098 2098
                 array_key_exists($primary_id_ref, $props_n_values)
2099
-                && ! empty($props_n_values[ $primary_id_ref ])
2099
+                && ! empty($props_n_values[$primary_id_ref])
2100 2100
             ) {
2101 2101
                 $existing = $model->get_one_by_ID(
2102
-                    $props_n_values[ $primary_id_ref ]
2102
+                    $props_n_values[$primary_id_ref]
2103 2103
                 );
2104 2104
             }
2105 2105
         } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
@@ -2111,7 +2111,7 @@  discard block
 block discarded – undo
2111 2111
         }
2112 2112
         if ($existing) {
2113 2113
             // set date formats if present before setting values
2114
-            if (! empty($date_formats) && is_array($date_formats)) {
2114
+            if ( ! empty($date_formats) && is_array($date_formats)) {
2115 2115
                 $existing->set_date_format($date_formats[0]);
2116 2116
                 $existing->set_time_format($date_formats[1]);
2117 2117
             } else {
@@ -2144,7 +2144,7 @@  discard block
 block discarded – undo
2144 2144
     protected static function _get_model($classname, $timezone = null)
2145 2145
     {
2146 2146
         // find model for this class
2147
-        if (! $classname) {
2147
+        if ( ! $classname) {
2148 2148
             throw new EE_Error(
2149 2149
                 sprintf(
2150 2150
                     esc_html__(
@@ -2193,7 +2193,7 @@  discard block
 block discarded – undo
2193 2193
         if (strpos($model_name, 'EE_') === 0) {
2194 2194
             $model_classname = str_replace('EE_', 'EEM_', $model_name);
2195 2195
         } else {
2196
-            $model_classname = 'EEM_' . $model_name;
2196
+            $model_classname = 'EEM_'.$model_name;
2197 2197
         }
2198 2198
         return $model_classname;
2199 2199
     }
@@ -2212,7 +2212,7 @@  discard block
 block discarded – undo
2212 2212
      */
2213 2213
     protected static function _get_primary_key_name($classname = null)
2214 2214
     {
2215
-        if (! $classname) {
2215
+        if ( ! $classname) {
2216 2216
             throw new EE_Error(
2217 2217
                 sprintf(
2218 2218
                     esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
@@ -2242,7 +2242,7 @@  discard block
 block discarded – undo
2242 2242
         $model = $this->get_model();
2243 2243
         // now that we know the name of the variable, use a variable variable to get its value and return its
2244 2244
         if ($model->has_primary_key_field()) {
2245
-            return $this->_fields[ $model->primary_key_name() ];
2245
+            return $this->_fields[$model->primary_key_name()];
2246 2246
         }
2247 2247
         return $model->get_index_primary_key_string($this->_fields);
2248 2248
     }
@@ -2295,7 +2295,7 @@  discard block
 block discarded – undo
2295 2295
             }
2296 2296
         } else {
2297 2297
             // this thing doesn't exist in the DB,  so just cache it
2298
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2298
+            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2299 2299
                 throw new EE_Error(
2300 2300
                     sprintf(
2301 2301
                         esc_html__(
@@ -2460,7 +2460,7 @@  discard block
 block discarded – undo
2460 2460
             } else {
2461 2461
                 // did we already cache the result of this query?
2462 2462
                 $cached_results = $this->get_all_from_cache($relationName);
2463
-                if (! $cached_results) {
2463
+                if ( ! $cached_results) {
2464 2464
                     $related_model_objects = $this->get_model()->get_all_related(
2465 2465
                         $this,
2466 2466
                         $relationName,
@@ -2571,7 +2571,7 @@  discard block
 block discarded – undo
2571 2571
             } else {
2572 2572
                 // first, check if we've already cached the result of this query
2573 2573
                 $cached_result = $this->get_one_from_cache($relationName);
2574
-                if (! $cached_result) {
2574
+                if ( ! $cached_result) {
2575 2575
                     $related_model_object = $model->get_first_related(
2576 2576
                         $this,
2577 2577
                         $relationName,
@@ -2595,7 +2595,7 @@  discard block
 block discarded – undo
2595 2595
             }
2596 2596
             // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2597 2597
             // just get what's cached on this object
2598
-            if (! $related_model_object) {
2598
+            if ( ! $related_model_object) {
2599 2599
                 $related_model_object = $this->get_one_from_cache($relationName);
2600 2600
             }
2601 2601
         }
@@ -2677,7 +2677,7 @@  discard block
 block discarded – undo
2677 2677
      */
2678 2678
     public function is_set($field_name)
2679 2679
     {
2680
-        return isset($this->_fields[ $field_name ]);
2680
+        return isset($this->_fields[$field_name]);
2681 2681
     }
2682 2682
 
2683 2683
 
@@ -2693,7 +2693,7 @@  discard block
 block discarded – undo
2693 2693
     {
2694 2694
         foreach ((array) $properties as $property_name) {
2695 2695
             // first make sure this property exists
2696
-            if (! $this->_fields[ $property_name ]) {
2696
+            if ( ! $this->_fields[$property_name]) {
2697 2697
                 throw new EE_Error(
2698 2698
                     sprintf(
2699 2699
                         esc_html__(
@@ -2725,7 +2725,7 @@  discard block
 block discarded – undo
2725 2725
         $properties = array();
2726 2726
         // remove prepended underscore
2727 2727
         foreach ($fields as $field_name => $settings) {
2728
-            $properties[ $field_name ] = $this->get($field_name);
2728
+            $properties[$field_name] = $this->get($field_name);
2729 2729
         }
2730 2730
         return $properties;
2731 2731
     }
@@ -2762,7 +2762,7 @@  discard block
 block discarded – undo
2762 2762
     {
2763 2763
         $className = get_class($this);
2764 2764
         $tagName = "FHEE__{$className}__{$methodName}";
2765
-        if (! has_filter($tagName)) {
2765
+        if ( ! has_filter($tagName)) {
2766 2766
             throw new EE_Error(
2767 2767
                 sprintf(
2768 2768
                     esc_html__(
@@ -2807,7 +2807,7 @@  discard block
 block discarded – undo
2807 2807
             $query_params[0]['EXM_value'] = $meta_value;
2808 2808
         }
2809 2809
         $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2810
-        if (! $existing_rows_like_that) {
2810
+        if ( ! $existing_rows_like_that) {
2811 2811
             return $this->add_extra_meta($meta_key, $meta_value);
2812 2812
         }
2813 2813
         foreach ($existing_rows_like_that as $existing_row) {
@@ -2925,7 +2925,7 @@  discard block
 block discarded – undo
2925 2925
                 $values = array();
2926 2926
                 foreach ($results as $result) {
2927 2927
                     if ($result instanceof EE_Extra_Meta) {
2928
-                        $values[ $result->ID() ] = $result->value();
2928
+                        $values[$result->ID()] = $result->value();
2929 2929
                     }
2930 2930
                 }
2931 2931
                 return $values;
@@ -2970,17 +2970,17 @@  discard block
 block discarded – undo
2970 2970
             );
2971 2971
             foreach ($extra_meta_objs as $extra_meta_obj) {
2972 2972
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2973
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2973
+                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2974 2974
                 }
2975 2975
             }
2976 2976
         } else {
2977 2977
             $extra_meta_objs = $this->get_many_related('Extra_Meta');
2978 2978
             foreach ($extra_meta_objs as $extra_meta_obj) {
2979 2979
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2980
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2981
-                        $return_array[ $extra_meta_obj->key() ] = array();
2980
+                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2981
+                        $return_array[$extra_meta_obj->key()] = array();
2982 2982
                     }
2983
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2983
+                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2984 2984
                 }
2985 2985
             }
2986 2986
         }
@@ -3061,8 +3061,8 @@  discard block
 block discarded – undo
3061 3061
                             'event_espresso'
3062 3062
                         ),
3063 3063
                         $this->ID(),
3064
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3065
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3064
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
3065
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
3066 3066
                     )
3067 3067
                 );
3068 3068
             }
@@ -3095,7 +3095,7 @@  discard block
 block discarded – undo
3095 3095
     {
3096 3096
         // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3097 3097
         // if it wasn't even there to start off.
3098
-        if (! $this->ID()) {
3098
+        if ( ! $this->ID()) {
3099 3099
             $this->save();
3100 3100
         }
3101 3101
         global $wpdb;
@@ -3325,7 +3325,7 @@  discard block
 block discarded – undo
3325 3325
         $model = $this->get_model();
3326 3326
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3327 3327
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
3328
-                $classname = 'EE_' . $model->get_this_model_name();
3328
+                $classname = 'EE_'.$model->get_this_model_name();
3329 3329
                 if (
3330 3330
                     $this->get_one_from_cache($relation_name) instanceof $classname
3331 3331
                     && $this->get_one_from_cache($relation_name)->ID()
@@ -3366,7 +3366,7 @@  discard block
 block discarded – undo
3366 3366
         // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3367 3367
         foreach ($this->_fields as $field => $value) {
3368 3368
             if ($value instanceof DateTime) {
3369
-                $this->_fields[ $field ] = clone $value;
3369
+                $this->_fields[$field] = clone $value;
3370 3370
             }
3371 3371
         }
3372 3372
     }
Please login to merge, or discard this patch.
Indentation   +3348 added lines, -3348 removed lines patch added patch discarded remove patch
@@ -13,3364 +13,3364 @@
 block discarded – undo
13 13
  */
14 14
 abstract class EE_Base_Class
15 15
 {
16
-    /**
17
-     * This is an array of the original properties and values provided during construction
18
-     * of this model object. (keys are model field names, values are their values).
19
-     * This list is important to remember so that when we are merging data from the db, we know
20
-     * which values to override and which to not override.
21
-     *
22
-     * @var array
23
-     */
24
-    protected $_props_n_values_provided_in_constructor;
25
-
26
-    /**
27
-     * Timezone
28
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
-     * access to it.
32
-     *
33
-     * @var string
34
-     */
35
-    protected $_timezone;
36
-
37
-    /**
38
-     * date format
39
-     * pattern or format for displaying dates
40
-     *
41
-     * @var string $_dt_frmt
42
-     */
43
-    protected $_dt_frmt;
44
-
45
-    /**
46
-     * time format
47
-     * pattern or format for displaying time
48
-     *
49
-     * @var string $_tm_frmt
50
-     */
51
-    protected $_tm_frmt;
52
-
53
-    /**
54
-     * This property is for holding a cached array of object properties indexed by property name as the key.
55
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
56
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
-     *
59
-     * @var array
60
-     */
61
-    protected $_cached_properties = array();
62
-
63
-    /**
64
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
65
-     * single
66
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
-     * all others have an array)
69
-     *
70
-     * @var array
71
-     */
72
-    protected $_model_relations = array();
73
-
74
-    /**
75
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
-     *
78
-     * @var array
79
-     */
80
-    protected $_fields = array();
81
-
82
-    /**
83
-     * @var boolean indicating whether or not this model object is intended to ever be saved
84
-     * For example, we might create model objects intended to only be used for the duration
85
-     * of this request and to be thrown away, and if they were accidentally saved
86
-     * it would be a bug.
87
-     */
88
-    protected $_allow_persist = true;
89
-
90
-    /**
91
-     * @var boolean indicating whether or not this model object's properties have changed since construction
92
-     */
93
-    protected $_has_changes = false;
94
-
95
-    /**
96
-     * @var EEM_Base
97
-     */
98
-    protected $_model;
99
-
100
-    /**
101
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
-     * array as:
107
-     * array(
108
-     *  'Registration_Count' => 24
109
-     * );
110
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
-     * info)
113
-     *
114
-     * @var array
115
-     */
116
-    protected $custom_selection_results = array();
117
-
118
-
119
-    /**
120
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
-     * play nice
122
-     *
123
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
-     *                                                         TXN_amount, QST_name, etc) and values are their values
126
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
-     *                                                         corresponding db model or not.
128
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
-     *                                                         be in when instantiating a EE_Base_Class object.
130
-     * @param array   $date_formats                            An array of date formats to set on construct where first
131
-     *                                                         value is the date_format and second value is the time
132
-     *                                                         format.
133
-     * @throws InvalidArgumentException
134
-     * @throws InvalidInterfaceException
135
-     * @throws InvalidDataTypeException
136
-     * @throws EE_Error
137
-     * @throws ReflectionException
138
-     */
139
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
-    {
141
-        $className = get_class($this);
142
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
-        $model = $this->get_model();
144
-        $model_fields = $model->field_settings(false);
145
-        // ensure $fieldValues is an array
146
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
-        // verify client code has not passed any invalid field names
148
-        foreach ($fieldValues as $field_name => $field_value) {
149
-            if (! isset($model_fields[ $field_name ])) {
150
-                throw new EE_Error(
151
-                    sprintf(
152
-                        esc_html__(
153
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
-                            'event_espresso'
155
-                        ),
156
-                        $field_name,
157
-                        get_class($this),
158
-                        implode(', ', array_keys($model_fields))
159
-                    )
160
-                );
161
-            }
162
-        }
163
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
-        if (! empty($date_formats) && is_array($date_formats)) {
165
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
166
-        } else {
167
-            // set default formats for date and time
168
-            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
-            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
-        }
171
-        // if db model is instantiating
172
-        if ($bydb) {
173
-            // client code has indicated these field values are from the database
174
-            foreach ($model_fields as $fieldName => $field) {
175
-                $this->set_from_db(
176
-                    $fieldName,
177
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
-                );
179
-            }
180
-        } else {
181
-            // we're constructing a brand
182
-            // new instance of the model object. Generally, this means we'll need to do more field validation
183
-            foreach ($model_fields as $fieldName => $field) {
184
-                $this->set(
185
-                    $fieldName,
186
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
-                    true
188
-                );
189
-            }
190
-        }
191
-        // remember what values were passed to this constructor
192
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
193
-        // remember in entity mapper
194
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
-            $model->add_to_entity_map($this);
196
-        }
197
-        // setup all the relations
198
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
-                $this->_model_relations[ $relation_name ] = null;
201
-            } else {
202
-                $this->_model_relations[ $relation_name ] = array();
203
-            }
204
-        }
205
-        /**
206
-         * Action done at the end of each model object construction
207
-         *
208
-         * @param EE_Base_Class $this the model object just created
209
-         */
210
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
-    }
212
-
213
-
214
-    /**
215
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
216
-     *
217
-     * @return boolean
218
-     */
219
-    public function allow_persist()
220
-    {
221
-        return $this->_allow_persist;
222
-    }
223
-
224
-
225
-    /**
226
-     * Sets whether or not this model object should be allowed to be saved to the DB.
227
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
-     * you got new information that somehow made you change your mind.
229
-     *
230
-     * @param boolean $allow_persist
231
-     * @return boolean
232
-     */
233
-    public function set_allow_persist($allow_persist)
234
-    {
235
-        return $this->_allow_persist = $allow_persist;
236
-    }
237
-
238
-
239
-    /**
240
-     * Gets the field's original value when this object was constructed during this request.
241
-     * This can be helpful when determining if a model object has changed or not
242
-     *
243
-     * @param string $field_name
244
-     * @return mixed|null
245
-     * @throws ReflectionException
246
-     * @throws InvalidArgumentException
247
-     * @throws InvalidInterfaceException
248
-     * @throws InvalidDataTypeException
249
-     * @throws EE_Error
250
-     */
251
-    public function get_original($field_name)
252
-    {
253
-        if (
254
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
256
-        ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
-        }
259
-        return null;
260
-    }
261
-
262
-
263
-    /**
264
-     * @param EE_Base_Class $obj
265
-     * @return string
266
-     */
267
-    public function get_class($obj)
268
-    {
269
-        return get_class($obj);
270
-    }
271
-
272
-
273
-    /**
274
-     * Overrides parent because parent expects old models.
275
-     * This also doesn't do any validation, and won't work for serialized arrays
276
-     *
277
-     * @param    string $field_name
278
-     * @param    mixed  $field_value
279
-     * @param bool      $use_default
280
-     * @throws InvalidArgumentException
281
-     * @throws InvalidInterfaceException
282
-     * @throws InvalidDataTypeException
283
-     * @throws EE_Error
284
-     * @throws ReflectionException
285
-     * @throws ReflectionException
286
-     * @throws ReflectionException
287
-     */
288
-    public function set($field_name, $field_value, $use_default = false)
289
-    {
290
-        // if not using default and nothing has changed, and object has already been setup (has ID),
291
-        // then don't do anything
292
-        if (
293
-            ! $use_default
294
-            && $this->_fields[ $field_name ] === $field_value
295
-            && $this->ID()
296
-        ) {
297
-            return;
298
-        }
299
-        $model = $this->get_model();
300
-        $this->_has_changes = true;
301
-        $field_obj = $model->field_settings_for($field_name);
302
-        if ($field_obj instanceof EE_Model_Field_Base) {
303
-            // if ( method_exists( $field_obj, 'set_timezone' )) {
304
-            if ($field_obj instanceof EE_Datetime_Field) {
305
-                $field_obj->set_timezone($this->_timezone);
306
-                $field_obj->set_date_format($this->_dt_frmt);
307
-                $field_obj->set_time_format($this->_tm_frmt);
308
-            }
309
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
310
-            // should the value be null?
311
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
313
-                /**
314
-                 * To save having to refactor all the models, if a default value is used for a
315
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
-                 * object.
318
-                 *
319
-                 * @since 4.6.10+
320
-                 */
321
-                if (
322
-                    $field_obj instanceof EE_Datetime_Field
323
-                    && $this->_fields[ $field_name ] !== null
324
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
325
-                ) {
326
-                    empty($this->_fields[ $field_name ])
327
-                        ? $this->set($field_name, time())
328
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
329
-                }
330
-            } else {
331
-                $this->_fields[ $field_name ] = $holder_of_value;
332
-            }
333
-            // if we're not in the constructor...
334
-            // now check if what we set was a primary key
335
-            if (
16
+	/**
17
+	 * This is an array of the original properties and values provided during construction
18
+	 * of this model object. (keys are model field names, values are their values).
19
+	 * This list is important to remember so that when we are merging data from the db, we know
20
+	 * which values to override and which to not override.
21
+	 *
22
+	 * @var array
23
+	 */
24
+	protected $_props_n_values_provided_in_constructor;
25
+
26
+	/**
27
+	 * Timezone
28
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
+	 * access to it.
32
+	 *
33
+	 * @var string
34
+	 */
35
+	protected $_timezone;
36
+
37
+	/**
38
+	 * date format
39
+	 * pattern or format for displaying dates
40
+	 *
41
+	 * @var string $_dt_frmt
42
+	 */
43
+	protected $_dt_frmt;
44
+
45
+	/**
46
+	 * time format
47
+	 * pattern or format for displaying time
48
+	 *
49
+	 * @var string $_tm_frmt
50
+	 */
51
+	protected $_tm_frmt;
52
+
53
+	/**
54
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
55
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
56
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
+	 *
59
+	 * @var array
60
+	 */
61
+	protected $_cached_properties = array();
62
+
63
+	/**
64
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
65
+	 * single
66
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
+	 * all others have an array)
69
+	 *
70
+	 * @var array
71
+	 */
72
+	protected $_model_relations = array();
73
+
74
+	/**
75
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
+	 *
78
+	 * @var array
79
+	 */
80
+	protected $_fields = array();
81
+
82
+	/**
83
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
84
+	 * For example, we might create model objects intended to only be used for the duration
85
+	 * of this request and to be thrown away, and if they were accidentally saved
86
+	 * it would be a bug.
87
+	 */
88
+	protected $_allow_persist = true;
89
+
90
+	/**
91
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
92
+	 */
93
+	protected $_has_changes = false;
94
+
95
+	/**
96
+	 * @var EEM_Base
97
+	 */
98
+	protected $_model;
99
+
100
+	/**
101
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
+	 * array as:
107
+	 * array(
108
+	 *  'Registration_Count' => 24
109
+	 * );
110
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
+	 * info)
113
+	 *
114
+	 * @var array
115
+	 */
116
+	protected $custom_selection_results = array();
117
+
118
+
119
+	/**
120
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
+	 * play nice
122
+	 *
123
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
126
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
+	 *                                                         corresponding db model or not.
128
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
+	 *                                                         be in when instantiating a EE_Base_Class object.
130
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
131
+	 *                                                         value is the date_format and second value is the time
132
+	 *                                                         format.
133
+	 * @throws InvalidArgumentException
134
+	 * @throws InvalidInterfaceException
135
+	 * @throws InvalidDataTypeException
136
+	 * @throws EE_Error
137
+	 * @throws ReflectionException
138
+	 */
139
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
+	{
141
+		$className = get_class($this);
142
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
+		$model = $this->get_model();
144
+		$model_fields = $model->field_settings(false);
145
+		// ensure $fieldValues is an array
146
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
+		// verify client code has not passed any invalid field names
148
+		foreach ($fieldValues as $field_name => $field_value) {
149
+			if (! isset($model_fields[ $field_name ])) {
150
+				throw new EE_Error(
151
+					sprintf(
152
+						esc_html__(
153
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
+							'event_espresso'
155
+						),
156
+						$field_name,
157
+						get_class($this),
158
+						implode(', ', array_keys($model_fields))
159
+					)
160
+				);
161
+			}
162
+		}
163
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
+		if (! empty($date_formats) && is_array($date_formats)) {
165
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
166
+		} else {
167
+			// set default formats for date and time
168
+			$this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
+			$this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
+		}
171
+		// if db model is instantiating
172
+		if ($bydb) {
173
+			// client code has indicated these field values are from the database
174
+			foreach ($model_fields as $fieldName => $field) {
175
+				$this->set_from_db(
176
+					$fieldName,
177
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
+				);
179
+			}
180
+		} else {
181
+			// we're constructing a brand
182
+			// new instance of the model object. Generally, this means we'll need to do more field validation
183
+			foreach ($model_fields as $fieldName => $field) {
184
+				$this->set(
185
+					$fieldName,
186
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
+					true
188
+				);
189
+			}
190
+		}
191
+		// remember what values were passed to this constructor
192
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
193
+		// remember in entity mapper
194
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
+			$model->add_to_entity_map($this);
196
+		}
197
+		// setup all the relations
198
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
+				$this->_model_relations[ $relation_name ] = null;
201
+			} else {
202
+				$this->_model_relations[ $relation_name ] = array();
203
+			}
204
+		}
205
+		/**
206
+		 * Action done at the end of each model object construction
207
+		 *
208
+		 * @param EE_Base_Class $this the model object just created
209
+		 */
210
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
+	}
212
+
213
+
214
+	/**
215
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
216
+	 *
217
+	 * @return boolean
218
+	 */
219
+	public function allow_persist()
220
+	{
221
+		return $this->_allow_persist;
222
+	}
223
+
224
+
225
+	/**
226
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
227
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
+	 * you got new information that somehow made you change your mind.
229
+	 *
230
+	 * @param boolean $allow_persist
231
+	 * @return boolean
232
+	 */
233
+	public function set_allow_persist($allow_persist)
234
+	{
235
+		return $this->_allow_persist = $allow_persist;
236
+	}
237
+
238
+
239
+	/**
240
+	 * Gets the field's original value when this object was constructed during this request.
241
+	 * This can be helpful when determining if a model object has changed or not
242
+	 *
243
+	 * @param string $field_name
244
+	 * @return mixed|null
245
+	 * @throws ReflectionException
246
+	 * @throws InvalidArgumentException
247
+	 * @throws InvalidInterfaceException
248
+	 * @throws InvalidDataTypeException
249
+	 * @throws EE_Error
250
+	 */
251
+	public function get_original($field_name)
252
+	{
253
+		if (
254
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
256
+		) {
257
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
+		}
259
+		return null;
260
+	}
261
+
262
+
263
+	/**
264
+	 * @param EE_Base_Class $obj
265
+	 * @return string
266
+	 */
267
+	public function get_class($obj)
268
+	{
269
+		return get_class($obj);
270
+	}
271
+
272
+
273
+	/**
274
+	 * Overrides parent because parent expects old models.
275
+	 * This also doesn't do any validation, and won't work for serialized arrays
276
+	 *
277
+	 * @param    string $field_name
278
+	 * @param    mixed  $field_value
279
+	 * @param bool      $use_default
280
+	 * @throws InvalidArgumentException
281
+	 * @throws InvalidInterfaceException
282
+	 * @throws InvalidDataTypeException
283
+	 * @throws EE_Error
284
+	 * @throws ReflectionException
285
+	 * @throws ReflectionException
286
+	 * @throws ReflectionException
287
+	 */
288
+	public function set($field_name, $field_value, $use_default = false)
289
+	{
290
+		// if not using default and nothing has changed, and object has already been setup (has ID),
291
+		// then don't do anything
292
+		if (
293
+			! $use_default
294
+			&& $this->_fields[ $field_name ] === $field_value
295
+			&& $this->ID()
296
+		) {
297
+			return;
298
+		}
299
+		$model = $this->get_model();
300
+		$this->_has_changes = true;
301
+		$field_obj = $model->field_settings_for($field_name);
302
+		if ($field_obj instanceof EE_Model_Field_Base) {
303
+			// if ( method_exists( $field_obj, 'set_timezone' )) {
304
+			if ($field_obj instanceof EE_Datetime_Field) {
305
+				$field_obj->set_timezone($this->_timezone);
306
+				$field_obj->set_date_format($this->_dt_frmt);
307
+				$field_obj->set_time_format($this->_tm_frmt);
308
+			}
309
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
310
+			// should the value be null?
311
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
+				$this->_fields[ $field_name ] = $field_obj->get_default_value();
313
+				/**
314
+				 * To save having to refactor all the models, if a default value is used for a
315
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
+				 * object.
318
+				 *
319
+				 * @since 4.6.10+
320
+				 */
321
+				if (
322
+					$field_obj instanceof EE_Datetime_Field
323
+					&& $this->_fields[ $field_name ] !== null
324
+					&& ! $this->_fields[ $field_name ] instanceof DateTime
325
+				) {
326
+					empty($this->_fields[ $field_name ])
327
+						? $this->set($field_name, time())
328
+						: $this->set($field_name, $this->_fields[ $field_name ]);
329
+				}
330
+			} else {
331
+				$this->_fields[ $field_name ] = $holder_of_value;
332
+			}
333
+			// if we're not in the constructor...
334
+			// now check if what we set was a primary key
335
+			if (
336 336
 // note: props_n_values_provided_in_constructor is only set at the END of the constructor
337
-                $this->_props_n_values_provided_in_constructor
338
-                && $field_value
339
-                && $field_name === $model->primary_key_name()
340
-            ) {
341
-                // if so, we want all this object's fields to be filled either with
342
-                // what we've explicitly set on this model
343
-                // or what we have in the db
344
-                // echo "setting primary key!";
345
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
346
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
-                foreach ($fields_on_model as $field_obj) {
348
-                    if (
349
-                        ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
350
-                        && $field_obj->get_name() !== $field_name
351
-                    ) {
352
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
353
-                    }
354
-                }
355
-                // oh this model object has an ID? well make sure its in the entity mapper
356
-                $model->add_to_entity_map($this);
357
-            }
358
-            // let's unset any cache for this field_name from the $_cached_properties property.
359
-            $this->_clear_cached_property($field_name);
360
-        } else {
361
-            throw new EE_Error(
362
-                sprintf(
363
-                    esc_html__(
364
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
365
-                        'event_espresso'
366
-                    ),
367
-                    $field_name
368
-                )
369
-            );
370
-        }
371
-    }
372
-
373
-
374
-    /**
375
-     * Set custom select values for model.
376
-     *
377
-     * @param array $custom_select_values
378
-     */
379
-    public function setCustomSelectsValues(array $custom_select_values)
380
-    {
381
-        $this->custom_selection_results = $custom_select_values;
382
-    }
383
-
384
-
385
-    /**
386
-     * Returns the custom select value for the provided alias if its set.
387
-     * If not set, returns null.
388
-     *
389
-     * @param string $alias
390
-     * @return string|int|float|null
391
-     */
392
-    public function getCustomSelect($alias)
393
-    {
394
-        return isset($this->custom_selection_results[ $alias ])
395
-            ? $this->custom_selection_results[ $alias ]
396
-            : null;
397
-    }
398
-
399
-
400
-    /**
401
-     * This sets the field value on the db column if it exists for the given $column_name or
402
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
403
-     *
404
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
405
-     * @param string $field_name  Must be the exact column name.
406
-     * @param mixed  $field_value The value to set.
407
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
-     * @throws InvalidArgumentException
409
-     * @throws InvalidInterfaceException
410
-     * @throws InvalidDataTypeException
411
-     * @throws EE_Error
412
-     * @throws ReflectionException
413
-     */
414
-    public function set_field_or_extra_meta($field_name, $field_value)
415
-    {
416
-        if ($this->get_model()->has_field($field_name)) {
417
-            $this->set($field_name, $field_value);
418
-            return true;
419
-        }
420
-        // ensure this object is saved first so that extra meta can be properly related.
421
-        $this->save();
422
-        return $this->update_extra_meta($field_name, $field_value);
423
-    }
424
-
425
-
426
-    /**
427
-     * This retrieves the value of the db column set on this class or if that's not present
428
-     * it will attempt to retrieve from extra_meta if found.
429
-     * Example Usage:
430
-     * Via EE_Message child class:
431
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
432
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
433
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
434
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
435
-     * value for those extra fields dynamically via the EE_message object.
436
-     *
437
-     * @param  string $field_name expecting the fully qualified field name.
438
-     * @return mixed|null  value for the field if found.  null if not found.
439
-     * @throws ReflectionException
440
-     * @throws InvalidArgumentException
441
-     * @throws InvalidInterfaceException
442
-     * @throws InvalidDataTypeException
443
-     * @throws EE_Error
444
-     */
445
-    public function get_field_or_extra_meta($field_name)
446
-    {
447
-        if ($this->get_model()->has_field($field_name)) {
448
-            $column_value = $this->get($field_name);
449
-        } else {
450
-            // This isn't a column in the main table, let's see if it is in the extra meta.
451
-            $column_value = $this->get_extra_meta($field_name, true, null);
452
-        }
453
-        return $column_value;
454
-    }
455
-
456
-
457
-    /**
458
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
459
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
460
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
461
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
462
-     *
463
-     * @access public
464
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
465
-     * @return void
466
-     * @throws InvalidArgumentException
467
-     * @throws InvalidInterfaceException
468
-     * @throws InvalidDataTypeException
469
-     * @throws EE_Error
470
-     * @throws ReflectionException
471
-     */
472
-    public function set_timezone($timezone = '')
473
-    {
474
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
475
-        // make sure we clear all cached properties because they won't be relevant now
476
-        $this->_clear_cached_properties();
477
-        // make sure we update field settings and the date for all EE_Datetime_Fields
478
-        $model_fields = $this->get_model()->field_settings(false);
479
-        foreach ($model_fields as $field_name => $field_obj) {
480
-            if ($field_obj instanceof EE_Datetime_Field) {
481
-                $field_obj->set_timezone($this->_timezone);
482
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
-                }
485
-            }
486
-        }
487
-    }
488
-
489
-
490
-    /**
491
-     * This just returns whatever is set for the current timezone.
492
-     *
493
-     * @access public
494
-     * @return string timezone string
495
-     */
496
-    public function get_timezone()
497
-    {
498
-        return $this->_timezone;
499
-    }
500
-
501
-
502
-    /**
503
-     * This sets the internal date format to what is sent in to be used as the new default for the class
504
-     * internally instead of wp set date format options
505
-     *
506
-     * @since 4.6
507
-     * @param string $format should be a format recognizable by PHP date() functions.
508
-     */
509
-    public function set_date_format($format)
510
-    {
511
-        $this->_dt_frmt = $format;
512
-        // clear cached_properties because they won't be relevant now.
513
-        $this->_clear_cached_properties();
514
-    }
515
-
516
-
517
-    /**
518
-     * This sets the internal time format string to what is sent in to be used as the new default for the
519
-     * class internally instead of wp set time format options.
520
-     *
521
-     * @since 4.6
522
-     * @param string $format should be a format recognizable by PHP date() functions.
523
-     */
524
-    public function set_time_format($format)
525
-    {
526
-        $this->_tm_frmt = $format;
527
-        // clear cached_properties because they won't be relevant now.
528
-        $this->_clear_cached_properties();
529
-    }
530
-
531
-
532
-    /**
533
-     * This returns the current internal set format for the date and time formats.
534
-     *
535
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
536
-     *                             where the first value is the date format and the second value is the time format.
537
-     * @return mixed string|array
538
-     */
539
-    public function get_format($full = true)
540
-    {
541
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542
-    }
543
-
544
-
545
-    /**
546
-     * cache
547
-     * stores the passed model object on the current model object.
548
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
549
-     *
550
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
551
-     *                                       'Registration' associated with this model object
552
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
553
-     *                                       that could be a payment or a registration)
554
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
555
-     *                                       items which will be stored in an array on this object
556
-     * @throws ReflectionException
557
-     * @throws InvalidArgumentException
558
-     * @throws InvalidInterfaceException
559
-     * @throws InvalidDataTypeException
560
-     * @throws EE_Error
561
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
562
-     *                                       related thing, no array)
563
-     */
564
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565
-    {
566
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
-        if (! $object_to_cache instanceof EE_Base_Class) {
568
-            return false;
569
-        }
570
-        // also get "how" the object is related, or throw an error
571
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572
-            throw new EE_Error(
573
-                sprintf(
574
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
575
-                    $relationName,
576
-                    get_class($this)
577
-                )
578
-            );
579
-        }
580
-        // how many things are related ?
581
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
582
-            // if it's a "belongs to" relationship, then there's only one related model object
583
-            // eg, if this is a registration, there's only 1 attendee for it
584
-            // so for these model objects just set it to be cached
585
-            $this->_model_relations[ $relationName ] = $object_to_cache;
586
-            $return = true;
587
-        } else {
588
-            // otherwise, this is the "many" side of a one to many relationship,
589
-            // so we'll add the object to the array of related objects for that type.
590
-            // eg: if this is an event, there are many registrations for that event,
591
-            // so we cache the registrations in an array
592
-            if (! is_array($this->_model_relations[ $relationName ])) {
593
-                // if for some reason, the cached item is a model object,
594
-                // then stick that in the array, otherwise start with an empty array
595
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
596
-                                                           instanceof
597
-                                                           EE_Base_Class
598
-                    ? array($this->_model_relations[ $relationName ]) : array();
599
-            }
600
-            // first check for a cache_id which is normally empty
601
-            if (! empty($cache_id)) {
602
-                // if the cache_id exists, then it means we are purposely trying to cache this
603
-                // with a known key that can then be used to retrieve the object later on
604
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
605
-                $return = $cache_id;
606
-            } elseif ($object_to_cache->ID()) {
607
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
608
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
609
-                $return = $object_to_cache->ID();
610
-            } else {
611
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
613
-                // move the internal pointer to the end of the array
614
-                end($this->_model_relations[ $relationName ]);
615
-                // and grab the key so that we can return it
616
-                $return = key($this->_model_relations[ $relationName ]);
617
-            }
618
-        }
619
-        return $return;
620
-    }
621
-
622
-
623
-    /**
624
-     * For adding an item to the cached_properties property.
625
-     *
626
-     * @access protected
627
-     * @param string      $fieldname the property item the corresponding value is for.
628
-     * @param mixed       $value     The value we are caching.
629
-     * @param string|null $cache_type
630
-     * @return void
631
-     * @throws ReflectionException
632
-     * @throws InvalidArgumentException
633
-     * @throws InvalidInterfaceException
634
-     * @throws InvalidDataTypeException
635
-     * @throws EE_Error
636
-     */
637
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
638
-    {
639
-        // first make sure this property exists
640
-        $this->get_model()->field_settings_for($fieldname);
641
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
643
-    }
644
-
645
-
646
-    /**
647
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
648
-     * This also SETS the cache if we return the actual property!
649
-     *
650
-     * @param string $fieldname        the name of the property we're trying to retrieve
651
-     * @param bool   $pretty
652
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
653
-     *                                 (in cases where the same property may be used for different outputs
654
-     *                                 - i.e. datetime, money etc.)
655
-     *                                 It can also accept certain pre-defined "schema" strings
656
-     *                                 to define how to output the property.
657
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
658
-     * @return mixed                   whatever the value for the property is we're retrieving
659
-     * @throws ReflectionException
660
-     * @throws InvalidArgumentException
661
-     * @throws InvalidInterfaceException
662
-     * @throws InvalidDataTypeException
663
-     * @throws EE_Error
664
-     */
665
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
666
-    {
667
-        // verify the field exists
668
-        $model = $this->get_model();
669
-        $model->field_settings_for($fieldname);
670
-        $cache_type = $pretty ? 'pretty' : 'standard';
671
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
-        }
675
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676
-        $this->_set_cached_property($fieldname, $value, $cache_type);
677
-        return $value;
678
-    }
679
-
680
-
681
-    /**
682
-     * If the cache didn't fetch the needed item, this fetches it.
683
-     *
684
-     * @param string $fieldname
685
-     * @param bool   $pretty
686
-     * @param string $extra_cache_ref
687
-     * @return mixed
688
-     * @throws InvalidArgumentException
689
-     * @throws InvalidInterfaceException
690
-     * @throws InvalidDataTypeException
691
-     * @throws EE_Error
692
-     * @throws ReflectionException
693
-     */
694
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
695
-    {
696
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
697
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
698
-        if ($field_obj instanceof EE_Datetime_Field) {
699
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700
-        }
701
-        if (! isset($this->_fields[ $fieldname ])) {
702
-            $this->_fields[ $fieldname ] = null;
703
-        }
704
-        $value = $pretty
705
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
707
-        return $value;
708
-    }
709
-
710
-
711
-    /**
712
-     * set timezone, formats, and output for EE_Datetime_Field objects
713
-     *
714
-     * @param \EE_Datetime_Field $datetime_field
715
-     * @param bool               $pretty
716
-     * @param null               $date_or_time
717
-     * @return void
718
-     * @throws InvalidArgumentException
719
-     * @throws InvalidInterfaceException
720
-     * @throws InvalidDataTypeException
721
-     * @throws EE_Error
722
-     */
723
-    protected function _prepare_datetime_field(
724
-        EE_Datetime_Field $datetime_field,
725
-        $pretty = false,
726
-        $date_or_time = null
727
-    ) {
728
-        $datetime_field->set_timezone($this->_timezone);
729
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
730
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
731
-        // set the output returned
732
-        switch ($date_or_time) {
733
-            case 'D':
734
-                $datetime_field->set_date_time_output('date');
735
-                break;
736
-            case 'T':
737
-                $datetime_field->set_date_time_output('time');
738
-                break;
739
-            default:
740
-                $datetime_field->set_date_time_output();
741
-        }
742
-    }
743
-
744
-
745
-    /**
746
-     * This just takes care of clearing out the cached_properties
747
-     *
748
-     * @return void
749
-     */
750
-    protected function _clear_cached_properties()
751
-    {
752
-        $this->_cached_properties = array();
753
-    }
754
-
755
-
756
-    /**
757
-     * This just clears out ONE property if it exists in the cache
758
-     *
759
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
760
-     * @return void
761
-     */
762
-    protected function _clear_cached_property($property_name)
763
-    {
764
-        if (isset($this->_cached_properties[ $property_name ])) {
765
-            unset($this->_cached_properties[ $property_name ]);
766
-        }
767
-    }
768
-
769
-
770
-    /**
771
-     * Ensures that this related thing is a model object.
772
-     *
773
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
774
-     * @param string $model_name   name of the related thing, eg 'Attendee',
775
-     * @return EE_Base_Class
776
-     * @throws ReflectionException
777
-     * @throws InvalidArgumentException
778
-     * @throws InvalidInterfaceException
779
-     * @throws InvalidDataTypeException
780
-     * @throws EE_Error
781
-     */
782
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
783
-    {
784
-        $other_model_instance = self::_get_model_instance_with_name(
785
-            self::_get_model_classname($model_name),
786
-            $this->_timezone
787
-        );
788
-        return $other_model_instance->ensure_is_obj($object_or_id);
789
-    }
790
-
791
-
792
-    /**
793
-     * Forgets the cached model of the given relation Name. So the next time we request it,
794
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
795
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
796
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
797
-     *
798
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
799
-     *                                                     Eg 'Registration'
800
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
801
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
802
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
803
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
804
-     *                                                     this is HasMany or HABTM.
805
-     * @throws ReflectionException
806
-     * @throws InvalidArgumentException
807
-     * @throws InvalidInterfaceException
808
-     * @throws InvalidDataTypeException
809
-     * @throws EE_Error
810
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
811
-     *                                                     relation from all
812
-     */
813
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
814
-    {
815
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
816
-        $index_in_cache = '';
817
-        if (! $relationship_to_model) {
818
-            throw new EE_Error(
819
-                sprintf(
820
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
821
-                    $relationName,
822
-                    get_class($this)
823
-                )
824
-            );
825
-        }
826
-        if ($clear_all) {
827
-            $obj_removed = true;
828
-            $this->_model_relations[ $relationName ] = null;
829
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
830
-            $obj_removed = $this->_model_relations[ $relationName ];
831
-            $this->_model_relations[ $relationName ] = null;
832
-        } else {
833
-            if (
834
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
835
-                && $object_to_remove_or_index_into_array->ID()
836
-            ) {
837
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
838
-                if (
839
-                    is_array($this->_model_relations[ $relationName ])
840
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
841
-                ) {
842
-                    $index_found_at = null;
843
-                    // find this object in the array even though it has a different key
844
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
845
-                        /** @noinspection TypeUnsafeComparisonInspection */
846
-                        if (
847
-                            $obj instanceof EE_Base_Class
848
-                            && (
849
-                                $obj == $object_to_remove_or_index_into_array
850
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
851
-                            )
852
-                        ) {
853
-                            $index_found_at = $index;
854
-                            break;
855
-                        }
856
-                    }
857
-                    if ($index_found_at) {
858
-                        $index_in_cache = $index_found_at;
859
-                    } else {
860
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
861
-                        // if it wasn't in it to begin with. So we're done
862
-                        return $object_to_remove_or_index_into_array;
863
-                    }
864
-                }
865
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
866
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
867
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
868
-                    /** @noinspection TypeUnsafeComparisonInspection */
869
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
870
-                        $index_in_cache = $index;
871
-                    }
872
-                }
873
-            } else {
874
-                $index_in_cache = $object_to_remove_or_index_into_array;
875
-            }
876
-            // supposedly we've found it. But it could just be that the client code
877
-            // provided a bad index/object
878
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
879
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
880
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
881
-            } else {
882
-                // that thing was never cached anyways.
883
-                $obj_removed = null;
884
-            }
885
-        }
886
-        return $obj_removed;
887
-    }
888
-
889
-
890
-    /**
891
-     * update_cache_after_object_save
892
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
893
-     * obtained after being saved to the db
894
-     *
895
-     * @param string        $relationName       - the type of object that is cached
896
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
897
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
898
-     * @return boolean TRUE on success, FALSE on fail
899
-     * @throws ReflectionException
900
-     * @throws InvalidArgumentException
901
-     * @throws InvalidInterfaceException
902
-     * @throws InvalidDataTypeException
903
-     * @throws EE_Error
904
-     */
905
-    public function update_cache_after_object_save(
906
-        $relationName,
907
-        EE_Base_Class $newly_saved_object,
908
-        $current_cache_id = ''
909
-    ) {
910
-        // verify that incoming object is of the correct type
911
-        $obj_class = 'EE_' . $relationName;
912
-        if ($newly_saved_object instanceof $obj_class) {
913
-            /* @type EE_Base_Class $newly_saved_object */
914
-            // now get the type of relation
915
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
916
-            // if this is a 1:1 relationship
917
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
918
-                // then just replace the cached object with the newly saved object
919
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
920
-                return true;
921
-                // or if it's some kind of sordid feral polyamorous relationship...
922
-            }
923
-            if (
924
-                is_array($this->_model_relations[ $relationName ])
925
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
926
-            ) {
927
-                // then remove the current cached item
928
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
929
-                // and cache the newly saved object using it's new ID
930
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
931
-                return true;
932
-            }
933
-        }
934
-        return false;
935
-    }
936
-
937
-
938
-    /**
939
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
940
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
941
-     *
942
-     * @param string $relationName
943
-     * @return EE_Base_Class
944
-     */
945
-    public function get_one_from_cache($relationName)
946
-    {
947
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
948
-            ? $this->_model_relations[ $relationName ]
949
-            : null;
950
-        if (is_array($cached_array_or_object)) {
951
-            return array_shift($cached_array_or_object);
952
-        }
953
-        return $cached_array_or_object;
954
-    }
955
-
956
-
957
-    /**
958
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
959
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
960
-     *
961
-     * @param string $relationName
962
-     * @throws ReflectionException
963
-     * @throws InvalidArgumentException
964
-     * @throws InvalidInterfaceException
965
-     * @throws InvalidDataTypeException
966
-     * @throws EE_Error
967
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
968
-     */
969
-    public function get_all_from_cache($relationName)
970
-    {
971
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
972
-        // if the result is not an array, but exists, make it an array
973
-        $objects = is_array($objects) ? $objects : array($objects);
974
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
975
-        // basically, if this model object was stored in the session, and these cached model objects
976
-        // already have IDs, let's make sure they're in their model's entity mapper
977
-        // otherwise we will have duplicates next time we call
978
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
979
-        $model = EE_Registry::instance()->load_model($relationName);
980
-        foreach ($objects as $model_object) {
981
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
982
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
983
-                if ($model_object->ID()) {
984
-                    $model->add_to_entity_map($model_object);
985
-                }
986
-            } else {
987
-                throw new EE_Error(
988
-                    sprintf(
989
-                        esc_html__(
990
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
991
-                            'event_espresso'
992
-                        ),
993
-                        $relationName,
994
-                        gettype($model_object)
995
-                    )
996
-                );
997
-            }
998
-        }
999
-        return $objects;
1000
-    }
1001
-
1002
-
1003
-    /**
1004
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1005
-     * matching the given query conditions.
1006
-     *
1007
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1008
-     * @param int   $limit              How many objects to return.
1009
-     * @param array $query_params       Any additional conditions on the query.
1010
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1011
-     *                                  you can indicate just the columns you want returned
1012
-     * @return array|EE_Base_Class[]
1013
-     * @throws ReflectionException
1014
-     * @throws InvalidArgumentException
1015
-     * @throws InvalidInterfaceException
1016
-     * @throws InvalidDataTypeException
1017
-     * @throws EE_Error
1018
-     */
1019
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1020
-    {
1021
-        $model = $this->get_model();
1022
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1023
-            ? $model->get_primary_key_field()->get_name()
1024
-            : $field_to_order_by;
1025
-        $current_value = ! empty($field) ? $this->get($field) : null;
1026
-        if (empty($field) || empty($current_value)) {
1027
-            return array();
1028
-        }
1029
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1030
-    }
1031
-
1032
-
1033
-    /**
1034
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1035
-     * matching the given query conditions.
1036
-     *
1037
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1038
-     * @param int   $limit              How many objects to return.
1039
-     * @param array $query_params       Any additional conditions on the query.
1040
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1041
-     *                                  you can indicate just the columns you want returned
1042
-     * @return array|EE_Base_Class[]
1043
-     * @throws ReflectionException
1044
-     * @throws InvalidArgumentException
1045
-     * @throws InvalidInterfaceException
1046
-     * @throws InvalidDataTypeException
1047
-     * @throws EE_Error
1048
-     */
1049
-    public function previous_x(
1050
-        $field_to_order_by = null,
1051
-        $limit = 1,
1052
-        $query_params = array(),
1053
-        $columns_to_select = null
1054
-    ) {
1055
-        $model = $this->get_model();
1056
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1057
-            ? $model->get_primary_key_field()->get_name()
1058
-            : $field_to_order_by;
1059
-        $current_value = ! empty($field) ? $this->get($field) : null;
1060
-        if (empty($field) || empty($current_value)) {
1061
-            return array();
1062
-        }
1063
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1064
-    }
1065
-
1066
-
1067
-    /**
1068
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1069
-     * matching the given query conditions.
1070
-     *
1071
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1072
-     * @param array $query_params       Any additional conditions on the query.
1073
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1074
-     *                                  you can indicate just the columns you want returned
1075
-     * @return array|EE_Base_Class
1076
-     * @throws ReflectionException
1077
-     * @throws InvalidArgumentException
1078
-     * @throws InvalidInterfaceException
1079
-     * @throws InvalidDataTypeException
1080
-     * @throws EE_Error
1081
-     */
1082
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1083
-    {
1084
-        $model = $this->get_model();
1085
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1086
-            ? $model->get_primary_key_field()->get_name()
1087
-            : $field_to_order_by;
1088
-        $current_value = ! empty($field) ? $this->get($field) : null;
1089
-        if (empty($field) || empty($current_value)) {
1090
-            return array();
1091
-        }
1092
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1093
-    }
1094
-
1095
-
1096
-    /**
1097
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1098
-     * matching the given query conditions.
1099
-     *
1100
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1101
-     * @param array $query_params       Any additional conditions on the query.
1102
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1103
-     *                                  you can indicate just the column you want returned
1104
-     * @return array|EE_Base_Class
1105
-     * @throws ReflectionException
1106
-     * @throws InvalidArgumentException
1107
-     * @throws InvalidInterfaceException
1108
-     * @throws InvalidDataTypeException
1109
-     * @throws EE_Error
1110
-     */
1111
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1112
-    {
1113
-        $model = $this->get_model();
1114
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1115
-            ? $model->get_primary_key_field()->get_name()
1116
-            : $field_to_order_by;
1117
-        $current_value = ! empty($field) ? $this->get($field) : null;
1118
-        if (empty($field) || empty($current_value)) {
1119
-            return array();
1120
-        }
1121
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1122
-    }
1123
-
1124
-
1125
-    /**
1126
-     * Overrides parent because parent expects old models.
1127
-     * This also doesn't do any validation, and won't work for serialized arrays
1128
-     *
1129
-     * @param string $field_name
1130
-     * @param mixed  $field_value_from_db
1131
-     * @throws ReflectionException
1132
-     * @throws InvalidArgumentException
1133
-     * @throws InvalidInterfaceException
1134
-     * @throws InvalidDataTypeException
1135
-     * @throws EE_Error
1136
-     */
1137
-    public function set_from_db($field_name, $field_value_from_db)
1138
-    {
1139
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1140
-        if ($field_obj instanceof EE_Model_Field_Base) {
1141
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
1142
-            // eg, a CPT model object could have an entry in the posts table, but no
1143
-            // entry in the meta table. Meaning that all its columns in the meta table
1144
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
1145
-            if ($field_value_from_db === null) {
1146
-                if ($field_obj->is_nullable()) {
1147
-                    // if the field allows nulls, then let it be null
1148
-                    $field_value = null;
1149
-                } else {
1150
-                    $field_value = $field_obj->get_default_value();
1151
-                }
1152
-            } else {
1153
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1154
-            }
1155
-            $this->_fields[ $field_name ] = $field_value;
1156
-            $this->_clear_cached_property($field_name);
1157
-        }
1158
-    }
1159
-
1160
-
1161
-    /**
1162
-     * verifies that the specified field is of the correct type
1163
-     *
1164
-     * @param string $field_name
1165
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1166
-     *                                (in cases where the same property may be used for different outputs
1167
-     *                                - i.e. datetime, money etc.)
1168
-     * @return mixed
1169
-     * @throws ReflectionException
1170
-     * @throws InvalidArgumentException
1171
-     * @throws InvalidInterfaceException
1172
-     * @throws InvalidDataTypeException
1173
-     * @throws EE_Error
1174
-     */
1175
-    public function get($field_name, $extra_cache_ref = null)
1176
-    {
1177
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * This method simply returns the RAW unprocessed value for the given property in this class
1183
-     *
1184
-     * @param  string $field_name A valid fieldname
1185
-     * @return mixed              Whatever the raw value stored on the property is.
1186
-     * @throws ReflectionException
1187
-     * @throws InvalidArgumentException
1188
-     * @throws InvalidInterfaceException
1189
-     * @throws InvalidDataTypeException
1190
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1191
-     */
1192
-    public function get_raw($field_name)
1193
-    {
1194
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1195
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
-            ? $this->_fields[ $field_name ]->format('U')
1197
-            : $this->_fields[ $field_name ];
1198
-    }
1199
-
1200
-
1201
-    /**
1202
-     * This is used to return the internal DateTime object used for a field that is a
1203
-     * EE_Datetime_Field.
1204
-     *
1205
-     * @param string $field_name               The field name retrieving the DateTime object.
1206
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1207
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1208
-     *                                         EE_Datetime_Field and but the field value is null, then
1209
-     *                                         just null is returned (because that indicates that likely
1210
-     *                                         this field is nullable).
1211
-     * @throws InvalidArgumentException
1212
-     * @throws InvalidDataTypeException
1213
-     * @throws InvalidInterfaceException
1214
-     * @throws ReflectionException
1215
-     */
1216
-    public function get_DateTime_object($field_name)
1217
-    {
1218
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1219
-        if (! $field_settings instanceof EE_Datetime_Field) {
1220
-            EE_Error::add_error(
1221
-                sprintf(
1222
-                    esc_html__(
1223
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1224
-                        'event_espresso'
1225
-                    ),
1226
-                    $field_name
1227
-                ),
1228
-                __FILE__,
1229
-                __FUNCTION__,
1230
-                __LINE__
1231
-            );
1232
-            return false;
1233
-        }
1234
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
-            ? clone $this->_fields[ $field_name ]
1236
-            : null;
1237
-    }
1238
-
1239
-
1240
-    /**
1241
-     * To be used in template to immediately echo out the value, and format it for output.
1242
-     * Eg, should call stripslashes and whatnot before echoing
1243
-     *
1244
-     * @param string $field_name      the name of the field as it appears in the DB
1245
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1246
-     *                                (in cases where the same property may be used for different outputs
1247
-     *                                - i.e. datetime, money etc.)
1248
-     * @return void
1249
-     * @throws ReflectionException
1250
-     * @throws InvalidArgumentException
1251
-     * @throws InvalidInterfaceException
1252
-     * @throws InvalidDataTypeException
1253
-     * @throws EE_Error
1254
-     */
1255
-    public function e($field_name, $extra_cache_ref = null)
1256
-    {
1257
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1258
-    }
1259
-
1260
-
1261
-    /**
1262
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1263
-     * can be easily used as the value of form input.
1264
-     *
1265
-     * @param string $field_name
1266
-     * @return void
1267
-     * @throws ReflectionException
1268
-     * @throws InvalidArgumentException
1269
-     * @throws InvalidInterfaceException
1270
-     * @throws InvalidDataTypeException
1271
-     * @throws EE_Error
1272
-     */
1273
-    public function f($field_name)
1274
-    {
1275
-        $this->e($field_name, 'form_input');
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * Same as `f()` but just returns the value instead of echoing it
1281
-     *
1282
-     * @param string $field_name
1283
-     * @return string
1284
-     * @throws ReflectionException
1285
-     * @throws InvalidArgumentException
1286
-     * @throws InvalidInterfaceException
1287
-     * @throws InvalidDataTypeException
1288
-     * @throws EE_Error
1289
-     */
1290
-    public function get_f($field_name)
1291
-    {
1292
-        return (string) $this->get_pretty($field_name, 'form_input');
1293
-    }
1294
-
1295
-
1296
-    /**
1297
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1298
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1299
-     * to see what options are available.
1300
-     *
1301
-     * @param string $field_name
1302
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1303
-     *                                (in cases where the same property may be used for different outputs
1304
-     *                                - i.e. datetime, money etc.)
1305
-     * @return mixed
1306
-     * @throws ReflectionException
1307
-     * @throws InvalidArgumentException
1308
-     * @throws InvalidInterfaceException
1309
-     * @throws InvalidDataTypeException
1310
-     * @throws EE_Error
1311
-     */
1312
-    public function get_pretty($field_name, $extra_cache_ref = null)
1313
-    {
1314
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1315
-    }
1316
-
1317
-
1318
-    /**
1319
-     * This simply returns the datetime for the given field name
1320
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1321
-     * (and the equivalent e_date, e_time, e_datetime).
1322
-     *
1323
-     * @access   protected
1324
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1325
-     * @param string   $dt_frmt      valid datetime format used for date
1326
-     *                               (if '' then we just use the default on the field,
1327
-     *                               if NULL we use the last-used format)
1328
-     * @param string   $tm_frmt      Same as above except this is for time format
1329
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1330
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1331
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1332
-     *                               if field is not a valid dtt field, or void if echoing
1333
-     * @throws ReflectionException
1334
-     * @throws InvalidArgumentException
1335
-     * @throws InvalidInterfaceException
1336
-     * @throws InvalidDataTypeException
1337
-     * @throws EE_Error
1338
-     */
1339
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1340
-    {
1341
-        // clear cached property
1342
-        $this->_clear_cached_property($field_name);
1343
-        // reset format properties because they are used in get()
1344
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1345
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1346
-        if ($echo) {
1347
-            $this->e($field_name, $date_or_time);
1348
-            return '';
1349
-        }
1350
-        return $this->get($field_name, $date_or_time);
1351
-    }
1352
-
1353
-
1354
-    /**
1355
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1356
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1357
-     * other echoes the pretty value for dtt)
1358
-     *
1359
-     * @param  string $field_name name of model object datetime field holding the value
1360
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1361
-     * @return string            datetime value formatted
1362
-     * @throws ReflectionException
1363
-     * @throws InvalidArgumentException
1364
-     * @throws InvalidInterfaceException
1365
-     * @throws InvalidDataTypeException
1366
-     * @throws EE_Error
1367
-     */
1368
-    public function get_date($field_name, $format = '')
1369
-    {
1370
-        return $this->_get_datetime($field_name, $format, null, 'D');
1371
-    }
1372
-
1373
-
1374
-    /**
1375
-     * @param        $field_name
1376
-     * @param string $format
1377
-     * @throws ReflectionException
1378
-     * @throws InvalidArgumentException
1379
-     * @throws InvalidInterfaceException
1380
-     * @throws InvalidDataTypeException
1381
-     * @throws EE_Error
1382
-     */
1383
-    public function e_date($field_name, $format = '')
1384
-    {
1385
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1386
-    }
1387
-
1388
-
1389
-    /**
1390
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1391
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1392
-     * other echoes the pretty value for dtt)
1393
-     *
1394
-     * @param  string $field_name name of model object datetime field holding the value
1395
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1396
-     * @return string             datetime value formatted
1397
-     * @throws ReflectionException
1398
-     * @throws InvalidArgumentException
1399
-     * @throws InvalidInterfaceException
1400
-     * @throws InvalidDataTypeException
1401
-     * @throws EE_Error
1402
-     */
1403
-    public function get_time($field_name, $format = '')
1404
-    {
1405
-        return $this->_get_datetime($field_name, null, $format, 'T');
1406
-    }
1407
-
1408
-
1409
-    /**
1410
-     * @param        $field_name
1411
-     * @param string $format
1412
-     * @throws ReflectionException
1413
-     * @throws InvalidArgumentException
1414
-     * @throws InvalidInterfaceException
1415
-     * @throws InvalidDataTypeException
1416
-     * @throws EE_Error
1417
-     */
1418
-    public function e_time($field_name, $format = '')
1419
-    {
1420
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1421
-    }
1422
-
1423
-
1424
-    /**
1425
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1426
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1427
-     * other echoes the pretty value for dtt)
1428
-     *
1429
-     * @param  string $field_name name of model object datetime field holding the value
1430
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1431
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1432
-     * @return string             datetime value formatted
1433
-     * @throws ReflectionException
1434
-     * @throws InvalidArgumentException
1435
-     * @throws InvalidInterfaceException
1436
-     * @throws InvalidDataTypeException
1437
-     * @throws EE_Error
1438
-     */
1439
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1440
-    {
1441
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1442
-    }
1443
-
1444
-
1445
-    /**
1446
-     * @param string $field_name
1447
-     * @param string $dt_frmt
1448
-     * @param string $tm_frmt
1449
-     * @throws ReflectionException
1450
-     * @throws InvalidArgumentException
1451
-     * @throws InvalidInterfaceException
1452
-     * @throws InvalidDataTypeException
1453
-     * @throws EE_Error
1454
-     */
1455
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1456
-    {
1457
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1458
-    }
1459
-
1460
-
1461
-    /**
1462
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1463
-     *
1464
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1465
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1466
-     *                           on the object will be used.
1467
-     * @return string Date and time string in set locale or false if no field exists for the given
1468
-     * @throws ReflectionException
1469
-     * @throws InvalidArgumentException
1470
-     * @throws InvalidInterfaceException
1471
-     * @throws InvalidDataTypeException
1472
-     * @throws EE_Error
1473
-     *                           field name.
1474
-     */
1475
-    public function get_i18n_datetime($field_name, $format = '')
1476
-    {
1477
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1478
-        return date_i18n(
1479
-            $format,
1480
-            EEH_DTT_Helper::get_timestamp_with_offset(
1481
-                $this->get_raw($field_name),
1482
-                $this->_timezone
1483
-            )
1484
-        );
1485
-    }
1486
-
1487
-
1488
-    /**
1489
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1490
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1491
-     * thrown.
1492
-     *
1493
-     * @param  string $field_name The field name being checked
1494
-     * @throws ReflectionException
1495
-     * @throws InvalidArgumentException
1496
-     * @throws InvalidInterfaceException
1497
-     * @throws InvalidDataTypeException
1498
-     * @throws EE_Error
1499
-     * @return EE_Datetime_Field
1500
-     */
1501
-    protected function _get_dtt_field_settings($field_name)
1502
-    {
1503
-        $field = $this->get_model()->field_settings_for($field_name);
1504
-        // check if field is dtt
1505
-        if ($field instanceof EE_Datetime_Field) {
1506
-            return $field;
1507
-        }
1508
-        throw new EE_Error(
1509
-            sprintf(
1510
-                esc_html__(
1511
-                    'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1512
-                    'event_espresso'
1513
-                ),
1514
-                $field_name,
1515
-                self::_get_model_classname(get_class($this))
1516
-            )
1517
-        );
1518
-    }
1519
-
1520
-
1521
-
1522
-
1523
-    /**
1524
-     * NOTE ABOUT BELOW:
1525
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1526
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1527
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1528
-     * method and make sure you send the entire datetime value for setting.
1529
-     */
1530
-    /**
1531
-     * sets the time on a datetime property
1532
-     *
1533
-     * @access protected
1534
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1535
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1536
-     * @throws ReflectionException
1537
-     * @throws InvalidArgumentException
1538
-     * @throws InvalidInterfaceException
1539
-     * @throws InvalidDataTypeException
1540
-     * @throws EE_Error
1541
-     */
1542
-    protected function _set_time_for($time, $fieldname)
1543
-    {
1544
-        $this->_set_date_time('T', $time, $fieldname);
1545
-    }
1546
-
1547
-
1548
-    /**
1549
-     * sets the date on a datetime property
1550
-     *
1551
-     * @access protected
1552
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1553
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1554
-     * @throws ReflectionException
1555
-     * @throws InvalidArgumentException
1556
-     * @throws InvalidInterfaceException
1557
-     * @throws InvalidDataTypeException
1558
-     * @throws EE_Error
1559
-     */
1560
-    protected function _set_date_for($date, $fieldname)
1561
-    {
1562
-        $this->_set_date_time('D', $date, $fieldname);
1563
-    }
1564
-
1565
-
1566
-    /**
1567
-     * This takes care of setting a date or time independently on a given model object property. This method also
1568
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1569
-     *
1570
-     * @access protected
1571
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1572
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1573
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1574
-     *                                        EE_Datetime_Field property)
1575
-     * @throws ReflectionException
1576
-     * @throws InvalidArgumentException
1577
-     * @throws InvalidInterfaceException
1578
-     * @throws InvalidDataTypeException
1579
-     * @throws EE_Error
1580
-     */
1581
-    protected function _set_date_time($what, $datetime_value, $fieldname)
1582
-    {
1583
-        $what  = $what ?: 'T';
1584
-        $field = $this->_get_dtt_field_settings($fieldname);
1585
-        $field->set_timezone($this->_timezone);
1586
-        $field->set_date_format($this->_dt_frmt);
1587
-        $field->set_time_format($this->_tm_frmt);
1588
-        switch ($what) {
1589
-            case 'T':
1590
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1591
-                    $datetime_value,
1592
-                    $this->_fields[ $fieldname ]
1593
-                );
1594
-                $this->_has_changes = true;
1595
-                break;
1596
-            case 'D':
1597
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1598
-                    $datetime_value,
1599
-                    $this->_fields[ $fieldname ]
1600
-                );
1601
-                $this->_has_changes = true;
1602
-                break;
1603
-            case 'B':
1604
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1605
-                $this->_has_changes = true;
1606
-                break;
1607
-        }
1608
-        $this->_clear_cached_property($fieldname);
1609
-    }
1610
-
1611
-
1612
-    /**
1613
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1614
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1615
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1616
-     * that could lead to some unexpected results!
1617
-     *
1618
-     * @access public
1619
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1620
-     *                                         value being returned.
1621
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1622
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1623
-     * @param string $prepend                  You can include something to prepend on the timestamp
1624
-     * @param string $append                   You can include something to append on the timestamp
1625
-     * @throws ReflectionException
1626
-     * @throws InvalidArgumentException
1627
-     * @throws InvalidInterfaceException
1628
-     * @throws InvalidDataTypeException
1629
-     * @throws EE_Error
1630
-     * @return string timestamp
1631
-     */
1632
-    public function display_in_my_timezone(
1633
-        $field_name,
1634
-        $callback = 'get_datetime',
1635
-        $args = null,
1636
-        $prepend = '',
1637
-        $append = ''
1638
-    ) {
1639
-        $timezone = EEH_DTT_Helper::get_timezone();
1640
-        if ($timezone === $this->_timezone) {
1641
-            return '';
1642
-        }
1643
-        $original_timezone = $this->_timezone;
1644
-        $this->set_timezone($timezone);
1645
-        $fn = (array) $field_name;
1646
-        $args = array_merge($fn, (array) $args);
1647
-        if (! method_exists($this, $callback)) {
1648
-            throw new EE_Error(
1649
-                sprintf(
1650
-                    esc_html__(
1651
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1652
-                        'event_espresso'
1653
-                    ),
1654
-                    $callback
1655
-                )
1656
-            );
1657
-        }
1658
-        $args = (array) $args;
1659
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1660
-        $this->set_timezone($original_timezone);
1661
-        return $return;
1662
-    }
1663
-
1664
-
1665
-    /**
1666
-     * Deletes this model object.
1667
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1668
-     * override
1669
-     * `EE_Base_Class::_delete` NOT this class.
1670
-     *
1671
-     * @return boolean | int
1672
-     * @throws ReflectionException
1673
-     * @throws InvalidArgumentException
1674
-     * @throws InvalidInterfaceException
1675
-     * @throws InvalidDataTypeException
1676
-     * @throws EE_Error
1677
-     */
1678
-    public function delete()
1679
-    {
1680
-        /**
1681
-         * Called just before the `EE_Base_Class::_delete` method call.
1682
-         * Note:
1683
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1684
-         * should be aware that `_delete` may not always result in a permanent delete.
1685
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1686
-         * soft deletes (trash) the object and does not permanently delete it.
1687
-         *
1688
-         * @param EE_Base_Class $model_object about to be 'deleted'
1689
-         */
1690
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1691
-        $result = $this->_delete();
1692
-        /**
1693
-         * Called just after the `EE_Base_Class::_delete` method call.
1694
-         * Note:
1695
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1696
-         * should be aware that `_delete` may not always result in a permanent delete.
1697
-         * For example `EE_Soft_Base_Class::_delete`
1698
-         * soft deletes (trash) the object and does not permanently delete it.
1699
-         *
1700
-         * @param EE_Base_Class $model_object that was just 'deleted'
1701
-         * @param boolean       $result
1702
-         */
1703
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1704
-        return $result;
1705
-    }
1706
-
1707
-
1708
-    /**
1709
-     * Calls the specific delete method for the instantiated class.
1710
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1711
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1712
-     * `EE_Base_Class::delete`
1713
-     *
1714
-     * @return bool|int
1715
-     * @throws ReflectionException
1716
-     * @throws InvalidArgumentException
1717
-     * @throws InvalidInterfaceException
1718
-     * @throws InvalidDataTypeException
1719
-     * @throws EE_Error
1720
-     */
1721
-    protected function _delete()
1722
-    {
1723
-        return $this->delete_permanently();
1724
-    }
1725
-
1726
-
1727
-    /**
1728
-     * Deletes this model object permanently from db
1729
-     * (but keep in mind related models may block the delete and return an error)
1730
-     *
1731
-     * @return bool | int
1732
-     * @throws ReflectionException
1733
-     * @throws InvalidArgumentException
1734
-     * @throws InvalidInterfaceException
1735
-     * @throws InvalidDataTypeException
1736
-     * @throws EE_Error
1737
-     */
1738
-    public function delete_permanently()
1739
-    {
1740
-        /**
1741
-         * Called just before HARD deleting a model object
1742
-         *
1743
-         * @param EE_Base_Class $model_object about to be 'deleted'
1744
-         */
1745
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1746
-        $model = $this->get_model();
1747
-        $result = $model->delete_permanently_by_ID($this->ID());
1748
-        $this->refresh_cache_of_related_objects();
1749
-        /**
1750
-         * Called just after HARD deleting a model object
1751
-         *
1752
-         * @param EE_Base_Class $model_object that was just 'deleted'
1753
-         * @param boolean       $result
1754
-         */
1755
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1756
-        return $result;
1757
-    }
1758
-
1759
-
1760
-    /**
1761
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1762
-     * related model objects
1763
-     *
1764
-     * @throws ReflectionException
1765
-     * @throws InvalidArgumentException
1766
-     * @throws InvalidInterfaceException
1767
-     * @throws InvalidDataTypeException
1768
-     * @throws EE_Error
1769
-     */
1770
-    public function refresh_cache_of_related_objects()
1771
-    {
1772
-        $model = $this->get_model();
1773
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1774
-            if (! empty($this->_model_relations[ $relation_name ])) {
1775
-                $related_objects = $this->_model_relations[ $relation_name ];
1776
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1777
-                    // this relation only stores a single model object, not an array
1778
-                    // but let's make it consistent
1779
-                    $related_objects = array($related_objects);
1780
-                }
1781
-                foreach ($related_objects as $related_object) {
1782
-                    // only refresh their cache if they're in memory
1783
-                    if ($related_object instanceof EE_Base_Class) {
1784
-                        $related_object->clear_cache(
1785
-                            $model->get_this_model_name(),
1786
-                            $this
1787
-                        );
1788
-                    }
1789
-                }
1790
-            }
1791
-        }
1792
-    }
1793
-
1794
-
1795
-    /**
1796
-     *        Saves this object to the database. An array may be supplied to set some values on this
1797
-     * object just before saving.
1798
-     *
1799
-     * @access public
1800
-     * @param array $set_cols_n_values  keys are field names, values are their new values,
1801
-     *                                  if provided during the save() method
1802
-     *                                  (often client code will change the fields' values before calling save)
1803
-     * @return false|int|string         1 on a successful update;
1804
-     *                                  the ID of the new entry on insert;
1805
-     *                                  0 on failure, or if the model object isn't allowed to persist
1806
-     *                                  (as determined by EE_Base_Class::allow_persist())
1807
-     * @throws InvalidInterfaceException
1808
-     * @throws InvalidDataTypeException
1809
-     * @throws EE_Error
1810
-     * @throws InvalidArgumentException
1811
-     * @throws ReflectionException
1812
-     * @throws ReflectionException
1813
-     * @throws ReflectionException
1814
-     */
1815
-    public function save($set_cols_n_values = array())
1816
-    {
1817
-        $model = $this->get_model();
1818
-        /**
1819
-         * Filters the fields we're about to save on the model object
1820
-         *
1821
-         * @param array         $set_cols_n_values
1822
-         * @param EE_Base_Class $model_object
1823
-         */
1824
-        $set_cols_n_values = (array) apply_filters(
1825
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1826
-            $set_cols_n_values,
1827
-            $this
1828
-        );
1829
-        // set attributes as provided in $set_cols_n_values
1830
-        foreach ($set_cols_n_values as $column => $value) {
1831
-            $this->set($column, $value);
1832
-        }
1833
-        // no changes ? then don't do anything
1834
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1835
-            return 0;
1836
-        }
1837
-        /**
1838
-         * Saving a model object.
1839
-         * Before we perform a save, this action is fired.
1840
-         *
1841
-         * @param EE_Base_Class $model_object the model object about to be saved.
1842
-         */
1843
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1844
-        if (! $this->allow_persist()) {
1845
-            return 0;
1846
-        }
1847
-        // now get current attribute values
1848
-        $save_cols_n_values = $this->_fields;
1849
-        // if the object already has an ID, update it. Otherwise, insert it
1850
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1851
-        // They have been
1852
-        $old_assumption_concerning_value_preparation = $model
1853
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1854
-        $model->assume_values_already_prepared_by_model_object(true);
1855
-        // does this model have an autoincrement PK?
1856
-        if ($model->has_primary_key_field()) {
1857
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1858
-                // ok check if it's set, if so: update; if not, insert
1859
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1860
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1861
-                } else {
1862
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1863
-                    $results = $model->insert($save_cols_n_values);
1864
-                    if ($results) {
1865
-                        // if successful, set the primary key
1866
-                        // but don't use the normal SET method, because it will check if
1867
-                        // an item with the same ID exists in the mapper & db, then
1868
-                        // will find it in the db (because we just added it) and THAT object
1869
-                        // will get added to the mapper before we can add this one!
1870
-                        // but if we just avoid using the SET method, all that headache can be avoided
1871
-                        $pk_field_name = $model->primary_key_name();
1872
-                        $this->_fields[ $pk_field_name ] = $results;
1873
-                        $this->_clear_cached_property($pk_field_name);
1874
-                        $model->add_to_entity_map($this);
1875
-                        $this->_update_cached_related_model_objs_fks();
1876
-                    }
1877
-                }
1878
-            } else {// PK is NOT auto-increment
1879
-                // so check if one like it already exists in the db
1880
-                if ($model->exists_by_ID($this->ID())) {
1881
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1882
-                        throw new EE_Error(
1883
-                            sprintf(
1884
-                                esc_html__(
1885
-                                    'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1886
-                                    'event_espresso'
1887
-                                ),
1888
-                                get_class($this),
1889
-                                get_class($model) . '::instance()->add_to_entity_map()',
1890
-                                get_class($model) . '::instance()->get_one_by_ID()',
1891
-                                '<br />'
1892
-                            )
1893
-                        );
1894
-                    }
1895
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1896
-                } else {
1897
-                    $results = $model->insert($save_cols_n_values);
1898
-                    $this->_update_cached_related_model_objs_fks();
1899
-                }
1900
-            }
1901
-        } else {// there is NO primary key
1902
-            $already_in_db = false;
1903
-            foreach ($model->unique_indexes() as $index) {
1904
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1905
-                if ($model->exists(array($uniqueness_where_params))) {
1906
-                    $already_in_db = true;
1907
-                }
1908
-            }
1909
-            if ($already_in_db) {
1910
-                $combined_pk_fields_n_values = array_intersect_key(
1911
-                    $save_cols_n_values,
1912
-                    $model->get_combined_primary_key_fields()
1913
-                );
1914
-                $results = $model->update(
1915
-                    $save_cols_n_values,
1916
-                    $combined_pk_fields_n_values
1917
-                );
1918
-            } else {
1919
-                $results = $model->insert($save_cols_n_values);
1920
-            }
1921
-        }
1922
-        // restore the old assumption about values being prepared by the model object
1923
-        $model->assume_values_already_prepared_by_model_object(
1924
-            $old_assumption_concerning_value_preparation
1925
-        );
1926
-        /**
1927
-         * After saving the model object this action is called
1928
-         *
1929
-         * @param EE_Base_Class $model_object which was just saved
1930
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1931
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1932
-         */
1933
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1934
-        $this->_has_changes = false;
1935
-        return $results;
1936
-    }
1937
-
1938
-
1939
-    /**
1940
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1941
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1942
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1943
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1944
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1945
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1946
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1947
-     *
1948
-     * @return void
1949
-     * @throws ReflectionException
1950
-     * @throws InvalidArgumentException
1951
-     * @throws InvalidInterfaceException
1952
-     * @throws InvalidDataTypeException
1953
-     * @throws EE_Error
1954
-     */
1955
-    protected function _update_cached_related_model_objs_fks()
1956
-    {
1957
-        $model = $this->get_model();
1958
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1959
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1960
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1961
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1962
-                        $model->get_this_model_name()
1963
-                    );
1964
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1965
-                    if ($related_model_obj_in_cache->ID()) {
1966
-                        $related_model_obj_in_cache->save();
1967
-                    }
1968
-                }
1969
-            }
1970
-        }
1971
-    }
1972
-
1973
-
1974
-    /**
1975
-     * Saves this model object and its NEW cached relations to the database.
1976
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1977
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1978
-     * because otherwise, there's a potential for infinite looping of saving
1979
-     * Saves the cached related model objects, and ensures the relation between them
1980
-     * and this object and properly setup
1981
-     *
1982
-     * @return int ID of new model object on save; 0 on failure+
1983
-     * @throws ReflectionException
1984
-     * @throws InvalidArgumentException
1985
-     * @throws InvalidInterfaceException
1986
-     * @throws InvalidDataTypeException
1987
-     * @throws EE_Error
1988
-     */
1989
-    public function save_new_cached_related_model_objs()
1990
-    {
1991
-        // make sure this has been saved
1992
-        if (! $this->ID()) {
1993
-            $id = $this->save();
1994
-        } else {
1995
-            $id = $this->ID();
1996
-        }
1997
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1998
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1999
-            if ($this->_model_relations[ $relationName ]) {
2000
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2001
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2002
-                /* @var $related_model_obj EE_Base_Class */
2003
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
2004
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
2005
-                    // but ONLY if it DOES NOT exist in the DB
2006
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2007
-                    // if( ! $related_model_obj->ID()){
2008
-                    $this->_add_relation_to($related_model_obj, $relationName);
2009
-                    $related_model_obj->save_new_cached_related_model_objs();
2010
-                    // }
2011
-                } else {
2012
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2013
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2014
-                        // but ONLY if it DOES NOT exist in the DB
2015
-                        // if( ! $related_model_obj->ID()){
2016
-                        $this->_add_relation_to($related_model_obj, $relationName);
2017
-                        $related_model_obj->save_new_cached_related_model_objs();
2018
-                        // }
2019
-                    }
2020
-                }
2021
-            }
2022
-        }
2023
-        return $id;
2024
-    }
2025
-
2026
-
2027
-    /**
2028
-     * for getting a model while instantiated.
2029
-     *
2030
-     * @return EEM_Base | EEM_CPT_Base
2031
-     * @throws ReflectionException
2032
-     * @throws InvalidArgumentException
2033
-     * @throws InvalidInterfaceException
2034
-     * @throws InvalidDataTypeException
2035
-     * @throws EE_Error
2036
-     */
2037
-    public function get_model()
2038
-    {
2039
-        if (! $this->_model) {
2040
-            $modelName = self::_get_model_classname(get_class($this));
2041
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2042
-        } else {
2043
-            $this->_model->set_timezone($this->_timezone);
2044
-        }
2045
-        return $this->_model;
2046
-    }
2047
-
2048
-
2049
-    /**
2050
-     * @param $props_n_values
2051
-     * @param $classname
2052
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2053
-     * @throws ReflectionException
2054
-     * @throws InvalidArgumentException
2055
-     * @throws InvalidInterfaceException
2056
-     * @throws InvalidDataTypeException
2057
-     * @throws EE_Error
2058
-     */
2059
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2060
-    {
2061
-        // TODO: will not work for Term_Relationships because they have no PK!
2062
-        $primary_id_ref = self::_get_primary_key_name($classname);
2063
-        if (
2064
-            array_key_exists($primary_id_ref, $props_n_values)
2065
-            && ! empty($props_n_values[ $primary_id_ref ])
2066
-        ) {
2067
-            $id = $props_n_values[ $primary_id_ref ];
2068
-            return self::_get_model($classname)->get_from_entity_map($id);
2069
-        }
2070
-        return false;
2071
-    }
2072
-
2073
-
2074
-    /**
2075
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2076
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2077
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2078
-     * we return false.
2079
-     *
2080
-     * @param  array  $props_n_values   incoming array of properties and their values
2081
-     * @param  string $classname        the classname of the child class
2082
-     * @param null    $timezone
2083
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2084
-     *                                  date_format and the second value is the time format
2085
-     * @return mixed (EE_Base_Class|bool)
2086
-     * @throws InvalidArgumentException
2087
-     * @throws InvalidInterfaceException
2088
-     * @throws InvalidDataTypeException
2089
-     * @throws EE_Error
2090
-     * @throws ReflectionException
2091
-     * @throws ReflectionException
2092
-     * @throws ReflectionException
2093
-     */
2094
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2095
-    {
2096
-        $existing = null;
2097
-        $model = self::_get_model($classname, $timezone);
2098
-        if ($model->has_primary_key_field()) {
2099
-            $primary_id_ref = self::_get_primary_key_name($classname);
2100
-            if (
2101
-                array_key_exists($primary_id_ref, $props_n_values)
2102
-                && ! empty($props_n_values[ $primary_id_ref ])
2103
-            ) {
2104
-                $existing = $model->get_one_by_ID(
2105
-                    $props_n_values[ $primary_id_ref ]
2106
-                );
2107
-            }
2108
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2109
-            // no primary key on this model, but there's still a matching item in the DB
2110
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2111
-                self::_get_model($classname, $timezone)
2112
-                    ->get_index_primary_key_string($props_n_values)
2113
-            );
2114
-        }
2115
-        if ($existing) {
2116
-            // set date formats if present before setting values
2117
-            if (! empty($date_formats) && is_array($date_formats)) {
2118
-                $existing->set_date_format($date_formats[0]);
2119
-                $existing->set_time_format($date_formats[1]);
2120
-            } else {
2121
-                // set default formats for date and time
2122
-                $existing->set_date_format(get_option('date_format'));
2123
-                $existing->set_time_format(get_option('time_format'));
2124
-            }
2125
-            foreach ($props_n_values as $property => $field_value) {
2126
-                $existing->set($property, $field_value);
2127
-            }
2128
-            return $existing;
2129
-        }
2130
-        return false;
2131
-    }
2132
-
2133
-
2134
-    /**
2135
-     * Gets the EEM_*_Model for this class
2136
-     *
2137
-     * @access public now, as this is more convenient
2138
-     * @param      $classname
2139
-     * @param null $timezone
2140
-     * @throws ReflectionException
2141
-     * @throws InvalidArgumentException
2142
-     * @throws InvalidInterfaceException
2143
-     * @throws InvalidDataTypeException
2144
-     * @throws EE_Error
2145
-     * @return EEM_Base
2146
-     */
2147
-    protected static function _get_model($classname, $timezone = null)
2148
-    {
2149
-        // find model for this class
2150
-        if (! $classname) {
2151
-            throw new EE_Error(
2152
-                sprintf(
2153
-                    esc_html__(
2154
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2155
-                        'event_espresso'
2156
-                    ),
2157
-                    $classname
2158
-                )
2159
-            );
2160
-        }
2161
-        $modelName = self::_get_model_classname($classname);
2162
-        return self::_get_model_instance_with_name($modelName, $timezone);
2163
-    }
2164
-
2165
-
2166
-    /**
2167
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2168
-     *
2169
-     * @param string $model_classname
2170
-     * @param null   $timezone
2171
-     * @return EEM_Base
2172
-     * @throws ReflectionException
2173
-     * @throws InvalidArgumentException
2174
-     * @throws InvalidInterfaceException
2175
-     * @throws InvalidDataTypeException
2176
-     * @throws EE_Error
2177
-     */
2178
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2179
-    {
2180
-        $model_classname = str_replace('EEM_', '', $model_classname);
2181
-        $model = EE_Registry::instance()->load_model($model_classname);
2182
-        $model->set_timezone($timezone);
2183
-        return $model;
2184
-    }
2185
-
2186
-
2187
-    /**
2188
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2189
-     * Also works if a model class's classname is provided (eg EE_Registration).
2190
-     *
2191
-     * @param null $model_name
2192
-     * @return string like EEM_Attendee
2193
-     */
2194
-    private static function _get_model_classname($model_name = null)
2195
-    {
2196
-        if (strpos($model_name, 'EE_') === 0) {
2197
-            $model_classname = str_replace('EE_', 'EEM_', $model_name);
2198
-        } else {
2199
-            $model_classname = 'EEM_' . $model_name;
2200
-        }
2201
-        return $model_classname;
2202
-    }
2203
-
2204
-
2205
-    /**
2206
-     * returns the name of the primary key attribute
2207
-     *
2208
-     * @param null $classname
2209
-     * @throws ReflectionException
2210
-     * @throws InvalidArgumentException
2211
-     * @throws InvalidInterfaceException
2212
-     * @throws InvalidDataTypeException
2213
-     * @throws EE_Error
2214
-     * @return string
2215
-     */
2216
-    protected static function _get_primary_key_name($classname = null)
2217
-    {
2218
-        if (! $classname) {
2219
-            throw new EE_Error(
2220
-                sprintf(
2221
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2222
-                    $classname
2223
-                )
2224
-            );
2225
-        }
2226
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2227
-    }
2228
-
2229
-
2230
-    /**
2231
-     * Gets the value of the primary key.
2232
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2233
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2234
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2235
-     *
2236
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2237
-     * @throws ReflectionException
2238
-     * @throws InvalidArgumentException
2239
-     * @throws InvalidInterfaceException
2240
-     * @throws InvalidDataTypeException
2241
-     * @throws EE_Error
2242
-     */
2243
-    public function ID()
2244
-    {
2245
-        $model = $this->get_model();
2246
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2247
-        if ($model->has_primary_key_field()) {
2248
-            return $this->_fields[ $model->primary_key_name() ];
2249
-        }
2250
-        return $model->get_index_primary_key_string($this->_fields);
2251
-    }
2252
-
2253
-
2254
-    /**
2255
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2256
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2257
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2258
-     *
2259
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2260
-     * @param string $relationName                     eg 'Events','Question',etc.
2261
-     *                                                 an attendee to a group, you also want to specify which role they
2262
-     *                                                 will have in that group. So you would use this parameter to
2263
-     *                                                 specify array('role-column-name'=>'role-id')
2264
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2265
-     *                                                 allow you to further constrict the relation to being added.
2266
-     *                                                 However, keep in mind that the columns (keys) given must match a
2267
-     *                                                 column on the JOIN table and currently only the HABTM models
2268
-     *                                                 accept these additional conditions.  Also remember that if an
2269
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2270
-     *                                                 NEW row is created in the join table.
2271
-     * @param null   $cache_id
2272
-     * @throws ReflectionException
2273
-     * @throws InvalidArgumentException
2274
-     * @throws InvalidInterfaceException
2275
-     * @throws InvalidDataTypeException
2276
-     * @throws EE_Error
2277
-     * @return EE_Base_Class the object the relation was added to
2278
-     */
2279
-    public function _add_relation_to(
2280
-        $otherObjectModelObjectOrID,
2281
-        $relationName,
2282
-        $extra_join_model_fields_n_values = array(),
2283
-        $cache_id = null
2284
-    ) {
2285
-        $model = $this->get_model();
2286
-        // if this thing exists in the DB, save the relation to the DB
2287
-        if ($this->ID()) {
2288
-            $otherObject = $model->add_relationship_to(
2289
-                $this,
2290
-                $otherObjectModelObjectOrID,
2291
-                $relationName,
2292
-                $extra_join_model_fields_n_values
2293
-            );
2294
-            // clear cache so future get_many_related and get_first_related() return new results.
2295
-            $this->clear_cache($relationName, $otherObject, true);
2296
-            if ($otherObject instanceof EE_Base_Class) {
2297
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2298
-            }
2299
-        } else {
2300
-            // this thing doesn't exist in the DB,  so just cache it
2301
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2302
-                throw new EE_Error(
2303
-                    sprintf(
2304
-                        esc_html__(
2305
-                            'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2306
-                            'event_espresso'
2307
-                        ),
2308
-                        $otherObjectModelObjectOrID,
2309
-                        get_class($this)
2310
-                    )
2311
-                );
2312
-            }
2313
-            $otherObject = $otherObjectModelObjectOrID;
2314
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2315
-        }
2316
-        if ($otherObject instanceof EE_Base_Class) {
2317
-            // fix the reciprocal relation too
2318
-            if ($otherObject->ID()) {
2319
-                // its saved so assumed relations exist in the DB, so we can just
2320
-                // clear the cache so future queries use the updated info in the DB
2321
-                $otherObject->clear_cache(
2322
-                    $model->get_this_model_name(),
2323
-                    null,
2324
-                    true
2325
-                );
2326
-            } else {
2327
-                // it's not saved, so it caches relations like this
2328
-                $otherObject->cache($model->get_this_model_name(), $this);
2329
-            }
2330
-        }
2331
-        return $otherObject;
2332
-    }
2333
-
2334
-
2335
-    /**
2336
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2337
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2338
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2339
-     * from the cache
2340
-     *
2341
-     * @param mixed  $otherObjectModelObjectOrID
2342
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2343
-     *                to the DB yet
2344
-     * @param string $relationName
2345
-     * @param array  $where_query
2346
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2347
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2348
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2349
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2350
-     *                deleted.
2351
-     * @return EE_Base_Class the relation was removed from
2352
-     * @throws ReflectionException
2353
-     * @throws InvalidArgumentException
2354
-     * @throws InvalidInterfaceException
2355
-     * @throws InvalidDataTypeException
2356
-     * @throws EE_Error
2357
-     */
2358
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2359
-    {
2360
-        if ($this->ID()) {
2361
-            // if this exists in the DB, save the relation change to the DB too
2362
-            $otherObject = $this->get_model()->remove_relationship_to(
2363
-                $this,
2364
-                $otherObjectModelObjectOrID,
2365
-                $relationName,
2366
-                $where_query
2367
-            );
2368
-            $this->clear_cache(
2369
-                $relationName,
2370
-                $otherObject
2371
-            );
2372
-        } else {
2373
-            // this doesn't exist in the DB, just remove it from the cache
2374
-            $otherObject = $this->clear_cache(
2375
-                $relationName,
2376
-                $otherObjectModelObjectOrID
2377
-            );
2378
-        }
2379
-        if ($otherObject instanceof EE_Base_Class) {
2380
-            $otherObject->clear_cache(
2381
-                $this->get_model()->get_this_model_name(),
2382
-                $this
2383
-            );
2384
-        }
2385
-        return $otherObject;
2386
-    }
2387
-
2388
-
2389
-    /**
2390
-     * Removes ALL the related things for the $relationName.
2391
-     *
2392
-     * @param string $relationName
2393
-     * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2394
-     * @return EE_Base_Class
2395
-     * @throws ReflectionException
2396
-     * @throws InvalidArgumentException
2397
-     * @throws InvalidInterfaceException
2398
-     * @throws InvalidDataTypeException
2399
-     * @throws EE_Error
2400
-     */
2401
-    public function _remove_relations($relationName, $where_query_params = array())
2402
-    {
2403
-        if ($this->ID()) {
2404
-            // if this exists in the DB, save the relation change to the DB too
2405
-            $otherObjects = $this->get_model()->remove_relations(
2406
-                $this,
2407
-                $relationName,
2408
-                $where_query_params
2409
-            );
2410
-            $this->clear_cache(
2411
-                $relationName,
2412
-                null,
2413
-                true
2414
-            );
2415
-        } else {
2416
-            // this doesn't exist in the DB, just remove it from the cache
2417
-            $otherObjects = $this->clear_cache(
2418
-                $relationName,
2419
-                null,
2420
-                true
2421
-            );
2422
-        }
2423
-        if (is_array($otherObjects)) {
2424
-            foreach ($otherObjects as $otherObject) {
2425
-                $otherObject->clear_cache(
2426
-                    $this->get_model()->get_this_model_name(),
2427
-                    $this
2428
-                );
2429
-            }
2430
-        }
2431
-        return $otherObjects;
2432
-    }
2433
-
2434
-
2435
-    /**
2436
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2437
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2438
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2439
-     * because we want to get even deleted items etc.
2440
-     *
2441
-     * @param string $relationName key in the model's _model_relations array
2442
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2443
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2444
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2445
-     *                             results if you want IDs
2446
-     * @throws ReflectionException
2447
-     * @throws InvalidArgumentException
2448
-     * @throws InvalidInterfaceException
2449
-     * @throws InvalidDataTypeException
2450
-     * @throws EE_Error
2451
-     */
2452
-    public function get_many_related($relationName, $query_params = array())
2453
-    {
2454
-        if ($this->ID()) {
2455
-            // this exists in the DB, so get the related things from either the cache or the DB
2456
-            // if there are query parameters, forget about caching the related model objects.
2457
-            if ($query_params) {
2458
-                $related_model_objects = $this->get_model()->get_all_related(
2459
-                    $this,
2460
-                    $relationName,
2461
-                    $query_params
2462
-                );
2463
-            } else {
2464
-                // did we already cache the result of this query?
2465
-                $cached_results = $this->get_all_from_cache($relationName);
2466
-                if (! $cached_results) {
2467
-                    $related_model_objects = $this->get_model()->get_all_related(
2468
-                        $this,
2469
-                        $relationName,
2470
-                        $query_params
2471
-                    );
2472
-                    // if no query parameters were passed, then we got all the related model objects
2473
-                    // for that relation. We can cache them then.
2474
-                    foreach ($related_model_objects as $related_model_object) {
2475
-                        $this->cache($relationName, $related_model_object);
2476
-                    }
2477
-                } else {
2478
-                    $related_model_objects = $cached_results;
2479
-                }
2480
-            }
2481
-        } else {
2482
-            // this doesn't exist in the DB, so just get the related things from the cache
2483
-            $related_model_objects = $this->get_all_from_cache($relationName);
2484
-        }
2485
-        return $related_model_objects;
2486
-    }
2487
-
2488
-
2489
-    /**
2490
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2491
-     * unless otherwise specified in the $query_params
2492
-     *
2493
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2494
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2495
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2496
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2497
-     *                               that by the setting $distinct to TRUE;
2498
-     * @return int
2499
-     * @throws ReflectionException
2500
-     * @throws InvalidArgumentException
2501
-     * @throws InvalidInterfaceException
2502
-     * @throws InvalidDataTypeException
2503
-     * @throws EE_Error
2504
-     */
2505
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2506
-    {
2507
-        return $this->get_model()->count_related(
2508
-            $this,
2509
-            $relation_name,
2510
-            $query_params,
2511
-            $field_to_count,
2512
-            $distinct
2513
-        );
2514
-    }
2515
-
2516
-
2517
-    /**
2518
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2519
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2520
-     *
2521
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2522
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2523
-     * @param string $field_to_sum  name of field to count by.
2524
-     *                              By default, uses primary key
2525
-     *                              (which doesn't make much sense, so you should probably change it)
2526
-     * @return int
2527
-     * @throws ReflectionException
2528
-     * @throws InvalidArgumentException
2529
-     * @throws InvalidInterfaceException
2530
-     * @throws InvalidDataTypeException
2531
-     * @throws EE_Error
2532
-     */
2533
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2534
-    {
2535
-        return $this->get_model()->sum_related(
2536
-            $this,
2537
-            $relation_name,
2538
-            $query_params,
2539
-            $field_to_sum
2540
-        );
2541
-    }
2542
-
2543
-
2544
-    /**
2545
-     * Gets the first (ie, one) related model object of the specified type.
2546
-     *
2547
-     * @param string $relationName key in the model's _model_relations array
2548
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2549
-     * @return EE_Base_Class (not an array, a single object)
2550
-     * @throws ReflectionException
2551
-     * @throws InvalidArgumentException
2552
-     * @throws InvalidInterfaceException
2553
-     * @throws InvalidDataTypeException
2554
-     * @throws EE_Error
2555
-     */
2556
-    public function get_first_related($relationName, $query_params = array())
2557
-    {
2558
-        $model = $this->get_model();
2559
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2560
-            // if they've provided some query parameters, don't bother trying to cache the result
2561
-            // also make sure we're not caching the result of get_first_related
2562
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2563
-            if (
2564
-                $query_params
2565
-                || ! $model->related_settings_for($relationName)
2566
-                     instanceof
2567
-                     EE_Belongs_To_Relation
2568
-            ) {
2569
-                $related_model_object = $model->get_first_related(
2570
-                    $this,
2571
-                    $relationName,
2572
-                    $query_params
2573
-                );
2574
-            } else {
2575
-                // first, check if we've already cached the result of this query
2576
-                $cached_result = $this->get_one_from_cache($relationName);
2577
-                if (! $cached_result) {
2578
-                    $related_model_object = $model->get_first_related(
2579
-                        $this,
2580
-                        $relationName,
2581
-                        $query_params
2582
-                    );
2583
-                    $this->cache($relationName, $related_model_object);
2584
-                } else {
2585
-                    $related_model_object = $cached_result;
2586
-                }
2587
-            }
2588
-        } else {
2589
-            $related_model_object = null;
2590
-            // this doesn't exist in the Db,
2591
-            // but maybe the relation is of type belongs to, and so the related thing might
2592
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2593
-                $related_model_object = $model->get_first_related(
2594
-                    $this,
2595
-                    $relationName,
2596
-                    $query_params
2597
-                );
2598
-            }
2599
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2600
-            // just get what's cached on this object
2601
-            if (! $related_model_object) {
2602
-                $related_model_object = $this->get_one_from_cache($relationName);
2603
-            }
2604
-        }
2605
-        return $related_model_object;
2606
-    }
2607
-
2608
-
2609
-    /**
2610
-     * Does a delete on all related objects of type $relationName and removes
2611
-     * the current model object's relation to them. If they can't be deleted (because
2612
-     * of blocking related model objects) does nothing. If the related model objects are
2613
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2614
-     * If this model object doesn't exist yet in the DB, just removes its related things
2615
-     *
2616
-     * @param string $relationName
2617
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2618
-     * @return int how many deleted
2619
-     * @throws ReflectionException
2620
-     * @throws InvalidArgumentException
2621
-     * @throws InvalidInterfaceException
2622
-     * @throws InvalidDataTypeException
2623
-     * @throws EE_Error
2624
-     */
2625
-    public function delete_related($relationName, $query_params = array())
2626
-    {
2627
-        if ($this->ID()) {
2628
-            $count = $this->get_model()->delete_related(
2629
-                $this,
2630
-                $relationName,
2631
-                $query_params
2632
-            );
2633
-        } else {
2634
-            $count = count($this->get_all_from_cache($relationName));
2635
-            $this->clear_cache($relationName, null, true);
2636
-        }
2637
-        return $count;
2638
-    }
2639
-
2640
-
2641
-    /**
2642
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2643
-     * the current model object's relation to them. If they can't be deleted (because
2644
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2645
-     * If the related thing isn't a soft-deletable model object, this function is identical
2646
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2647
-     *
2648
-     * @param string $relationName
2649
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2650
-     * @return int how many deleted (including those soft deleted)
2651
-     * @throws ReflectionException
2652
-     * @throws InvalidArgumentException
2653
-     * @throws InvalidInterfaceException
2654
-     * @throws InvalidDataTypeException
2655
-     * @throws EE_Error
2656
-     */
2657
-    public function delete_related_permanently($relationName, $query_params = array())
2658
-    {
2659
-        if ($this->ID()) {
2660
-            $count = $this->get_model()->delete_related_permanently(
2661
-                $this,
2662
-                $relationName,
2663
-                $query_params
2664
-            );
2665
-        } else {
2666
-            $count = count($this->get_all_from_cache($relationName));
2667
-        }
2668
-        $this->clear_cache($relationName, null, true);
2669
-        return $count;
2670
-    }
2671
-
2672
-
2673
-    /**
2674
-     * is_set
2675
-     * Just a simple utility function children can use for checking if property exists
2676
-     *
2677
-     * @access  public
2678
-     * @param  string $field_name property to check
2679
-     * @return bool                              TRUE if existing,FALSE if not.
2680
-     */
2681
-    public function is_set($field_name)
2682
-    {
2683
-        return isset($this->_fields[ $field_name ]);
2684
-    }
2685
-
2686
-
2687
-    /**
2688
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2689
-     * EE_Error exception if they don't
2690
-     *
2691
-     * @param  mixed (string|array) $properties properties to check
2692
-     * @throws EE_Error
2693
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2694
-     */
2695
-    protected function _property_exists($properties)
2696
-    {
2697
-        foreach ((array) $properties as $property_name) {
2698
-            // first make sure this property exists
2699
-            if (! $this->_fields[ $property_name ]) {
2700
-                throw new EE_Error(
2701
-                    sprintf(
2702
-                        esc_html__(
2703
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2704
-                            'event_espresso'
2705
-                        ),
2706
-                        $property_name
2707
-                    )
2708
-                );
2709
-            }
2710
-        }
2711
-        return true;
2712
-    }
2713
-
2714
-
2715
-    /**
2716
-     * This simply returns an array of model fields for this object
2717
-     *
2718
-     * @return array
2719
-     * @throws ReflectionException
2720
-     * @throws InvalidArgumentException
2721
-     * @throws InvalidInterfaceException
2722
-     * @throws InvalidDataTypeException
2723
-     * @throws EE_Error
2724
-     */
2725
-    public function model_field_array()
2726
-    {
2727
-        $fields = $this->get_model()->field_settings(false);
2728
-        $properties = array();
2729
-        // remove prepended underscore
2730
-        foreach ($fields as $field_name => $settings) {
2731
-            $properties[ $field_name ] = $this->get($field_name);
2732
-        }
2733
-        return $properties;
2734
-    }
2735
-
2736
-
2737
-    /**
2738
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2739
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2740
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2741
-     * Instead of requiring a plugin to extend the EE_Base_Class
2742
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2743
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2744
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2745
-     * and accepts 2 arguments: the object on which the function was called,
2746
-     * and an array of the original arguments passed to the function.
2747
-     * Whatever their callback function returns will be returned by this function.
2748
-     * Example: in functions.php (or in a plugin):
2749
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2750
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2751
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2752
-     *          return $previousReturnValue.$returnString;
2753
-     *      }
2754
-     * require('EE_Answer.class.php');
2755
-     * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2756
-     *      ->my_callback('monkeys',100);
2757
-     * // will output "you called my_callback! and passed args:monkeys,100"
2758
-     *
2759
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2760
-     * @param array  $args       array of original arguments passed to the function
2761
-     * @throws EE_Error
2762
-     * @return mixed whatever the plugin which calls add_filter decides
2763
-     */
2764
-    public function __call($methodName, $args)
2765
-    {
2766
-        $className = get_class($this);
2767
-        $tagName = "FHEE__{$className}__{$methodName}";
2768
-        if (! has_filter($tagName)) {
2769
-            throw new EE_Error(
2770
-                sprintf(
2771
-                    esc_html__(
2772
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2773
-                        'event_espresso'
2774
-                    ),
2775
-                    $methodName,
2776
-                    $className,
2777
-                    $tagName
2778
-                )
2779
-            );
2780
-        }
2781
-        return apply_filters($tagName, null, $this, $args);
2782
-    }
2783
-
2784
-
2785
-    /**
2786
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2787
-     * A $previous_value can be specified in case there are many meta rows with the same key
2788
-     *
2789
-     * @param string $meta_key
2790
-     * @param mixed  $meta_value
2791
-     * @param mixed  $previous_value
2792
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2793
-     *                  NOTE: if the values haven't changed, returns 0
2794
-     * @throws InvalidArgumentException
2795
-     * @throws InvalidInterfaceException
2796
-     * @throws InvalidDataTypeException
2797
-     * @throws EE_Error
2798
-     * @throws ReflectionException
2799
-     */
2800
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2801
-    {
2802
-        $query_params = array(
2803
-            array(
2804
-                'EXM_key'  => $meta_key,
2805
-                'OBJ_ID'   => $this->ID(),
2806
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2807
-            ),
2808
-        );
2809
-        if ($previous_value !== null) {
2810
-            $query_params[0]['EXM_value'] = $meta_value;
2811
-        }
2812
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2813
-        if (! $existing_rows_like_that) {
2814
-            return $this->add_extra_meta($meta_key, $meta_value);
2815
-        }
2816
-        foreach ($existing_rows_like_that as $existing_row) {
2817
-            $existing_row->save(array('EXM_value' => $meta_value));
2818
-        }
2819
-        return count($existing_rows_like_that);
2820
-    }
2821
-
2822
-
2823
-    /**
2824
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2825
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2826
-     * extra meta row was entered, false if not
2827
-     *
2828
-     * @param string  $meta_key
2829
-     * @param mixed   $meta_value
2830
-     * @param boolean $unique
2831
-     * @return boolean
2832
-     * @throws InvalidArgumentException
2833
-     * @throws InvalidInterfaceException
2834
-     * @throws InvalidDataTypeException
2835
-     * @throws EE_Error
2836
-     * @throws ReflectionException
2837
-     * @throws ReflectionException
2838
-     */
2839
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2840
-    {
2841
-        if ($unique) {
2842
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2843
-                array(
2844
-                    array(
2845
-                        'EXM_key'  => $meta_key,
2846
-                        'OBJ_ID'   => $this->ID(),
2847
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2848
-                    ),
2849
-                )
2850
-            );
2851
-            if ($existing_extra_meta) {
2852
-                return false;
2853
-            }
2854
-        }
2855
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2856
-            array(
2857
-                'EXM_key'   => $meta_key,
2858
-                'EXM_value' => $meta_value,
2859
-                'OBJ_ID'    => $this->ID(),
2860
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2861
-            )
2862
-        );
2863
-        $new_extra_meta->save();
2864
-        return true;
2865
-    }
2866
-
2867
-
2868
-    /**
2869
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2870
-     * is specified, only deletes extra meta records with that value.
2871
-     *
2872
-     * @param string $meta_key
2873
-     * @param mixed  $meta_value
2874
-     * @return int number of extra meta rows deleted
2875
-     * @throws InvalidArgumentException
2876
-     * @throws InvalidInterfaceException
2877
-     * @throws InvalidDataTypeException
2878
-     * @throws EE_Error
2879
-     * @throws ReflectionException
2880
-     */
2881
-    public function delete_extra_meta($meta_key, $meta_value = null)
2882
-    {
2883
-        $query_params = array(
2884
-            array(
2885
-                'EXM_key'  => $meta_key,
2886
-                'OBJ_ID'   => $this->ID(),
2887
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2888
-            ),
2889
-        );
2890
-        if ($meta_value !== null) {
2891
-            $query_params[0]['EXM_value'] = $meta_value;
2892
-        }
2893
-        return EEM_Extra_Meta::instance()->delete($query_params);
2894
-    }
2895
-
2896
-
2897
-    /**
2898
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2899
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2900
-     * You can specify $default is case you haven't found the extra meta
2901
-     *
2902
-     * @param string  $meta_key
2903
-     * @param boolean $single
2904
-     * @param mixed   $default if we don't find anything, what should we return?
2905
-     * @return mixed single value if $single; array if ! $single
2906
-     * @throws ReflectionException
2907
-     * @throws InvalidArgumentException
2908
-     * @throws InvalidInterfaceException
2909
-     * @throws InvalidDataTypeException
2910
-     * @throws EE_Error
2911
-     */
2912
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2913
-    {
2914
-        if ($single) {
2915
-            $result = $this->get_first_related(
2916
-                'Extra_Meta',
2917
-                array(array('EXM_key' => $meta_key))
2918
-            );
2919
-            if ($result instanceof EE_Extra_Meta) {
2920
-                return $result->value();
2921
-            }
2922
-        } else {
2923
-            $results = $this->get_many_related(
2924
-                'Extra_Meta',
2925
-                array(array('EXM_key' => $meta_key))
2926
-            );
2927
-            if ($results) {
2928
-                $values = array();
2929
-                foreach ($results as $result) {
2930
-                    if ($result instanceof EE_Extra_Meta) {
2931
-                        $values[ $result->ID() ] = $result->value();
2932
-                    }
2933
-                }
2934
-                return $values;
2935
-            }
2936
-        }
2937
-        // if nothing discovered yet return default.
2938
-        return apply_filters(
2939
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2940
-            $default,
2941
-            $meta_key,
2942
-            $single,
2943
-            $this
2944
-        );
2945
-    }
2946
-
2947
-
2948
-    /**
2949
-     * Returns a simple array of all the extra meta associated with this model object.
2950
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2951
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2952
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2953
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2954
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2955
-     * finally the extra meta's value as each sub-value. (eg
2956
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2957
-     *
2958
-     * @param boolean $one_of_each_key
2959
-     * @return array
2960
-     * @throws ReflectionException
2961
-     * @throws InvalidArgumentException
2962
-     * @throws InvalidInterfaceException
2963
-     * @throws InvalidDataTypeException
2964
-     * @throws EE_Error
2965
-     */
2966
-    public function all_extra_meta_array($one_of_each_key = true)
2967
-    {
2968
-        $return_array = array();
2969
-        if ($one_of_each_key) {
2970
-            $extra_meta_objs = $this->get_many_related(
2971
-                'Extra_Meta',
2972
-                array('group_by' => 'EXM_key')
2973
-            );
2974
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2975
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2976
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2977
-                }
2978
-            }
2979
-        } else {
2980
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2981
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2982
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2983
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2984
-                        $return_array[ $extra_meta_obj->key() ] = array();
2985
-                    }
2986
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2987
-                }
2988
-            }
2989
-        }
2990
-        return $return_array;
2991
-    }
2992
-
2993
-
2994
-    /**
2995
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2996
-     *
2997
-     * @return string
2998
-     * @throws ReflectionException
2999
-     * @throws InvalidArgumentException
3000
-     * @throws InvalidInterfaceException
3001
-     * @throws InvalidDataTypeException
3002
-     * @throws EE_Error
3003
-     */
3004
-    public function name()
3005
-    {
3006
-        // find a field that's not a text field
3007
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3008
-        if ($field_we_can_use) {
3009
-            return $this->get($field_we_can_use->get_name());
3010
-        }
3011
-        $first_few_properties = $this->model_field_array();
3012
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3013
-        $name_parts = array();
3014
-        foreach ($first_few_properties as $name => $value) {
3015
-            $name_parts[] = "$name:$value";
3016
-        }
3017
-        return implode(',', $name_parts);
3018
-    }
3019
-
3020
-
3021
-    /**
3022
-     * in_entity_map
3023
-     * Checks if this model object has been proven to already be in the entity map
3024
-     *
3025
-     * @return boolean
3026
-     * @throws ReflectionException
3027
-     * @throws InvalidArgumentException
3028
-     * @throws InvalidInterfaceException
3029
-     * @throws InvalidDataTypeException
3030
-     * @throws EE_Error
3031
-     */
3032
-    public function in_entity_map()
3033
-    {
3034
-        // well, if we looked, did we find it in the entity map?
3035
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3036
-    }
3037
-
3038
-
3039
-    /**
3040
-     * refresh_from_db
3041
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3042
-     *
3043
-     * @throws ReflectionException
3044
-     * @throws InvalidArgumentException
3045
-     * @throws InvalidInterfaceException
3046
-     * @throws InvalidDataTypeException
3047
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3048
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3049
-     */
3050
-    public function refresh_from_db()
3051
-    {
3052
-        if ($this->ID() && $this->in_entity_map()) {
3053
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3054
-        } else {
3055
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3056
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3057
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3058
-            // absolutely nothing in it for this ID
3059
-            if (WP_DEBUG) {
3060
-                throw new EE_Error(
3061
-                    sprintf(
3062
-                        esc_html__(
3063
-                            'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3064
-                            'event_espresso'
3065
-                        ),
3066
-                        $this->ID(),
3067
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3068
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3069
-                    )
3070
-                );
3071
-            }
3072
-        }
3073
-    }
3074
-
3075
-
3076
-    /**
3077
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3078
-     *
3079
-     * @since 4.9.80.p
3080
-     * @param EE_Model_Field_Base[] $fields
3081
-     * @param string $new_value_sql
3082
-     *      example: 'column_name=123',
3083
-     *      or 'column_name=column_name+1',
3084
-     *      or 'column_name= CASE
3085
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3086
-     *          THEN `column_name` + 5
3087
-     *          ELSE `column_name`
3088
-     *      END'
3089
-     *      Also updates $field on this model object with the latest value from the database.
3090
-     * @return bool
3091
-     * @throws EE_Error
3092
-     * @throws InvalidArgumentException
3093
-     * @throws InvalidDataTypeException
3094
-     * @throws InvalidInterfaceException
3095
-     * @throws ReflectionException
3096
-     */
3097
-    protected function updateFieldsInDB($fields, $new_value_sql)
3098
-    {
3099
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3100
-        // if it wasn't even there to start off.
3101
-        if (! $this->ID()) {
3102
-            $this->save();
3103
-        }
3104
-        global $wpdb;
3105
-        if (empty($fields)) {
3106
-            throw new InvalidArgumentException(
3107
-                esc_html__(
3108
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3109
-                    'event_espresso'
3110
-                )
3111
-            );
3112
-        }
3113
-        $first_field = reset($fields);
3114
-        $table_alias = $first_field->get_table_alias();
3115
-        foreach ($fields as $field) {
3116
-            if ($table_alias !== $field->get_table_alias()) {
3117
-                throw new InvalidArgumentException(
3118
-                    sprintf(
3119
-                        esc_html__(
3120
-                            // @codingStandardsIgnoreStart
3121
-                            'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3122
-                            // @codingStandardsIgnoreEnd
3123
-                            'event_espresso'
3124
-                        ),
3125
-                        $table_alias,
3126
-                        $field->get_table_alias()
3127
-                    )
3128
-                );
3129
-            }
3130
-        }
3131
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3132
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3133
-        $table_pk_value = $this->ID();
3134
-        $table_name = $table_obj->get_table_name();
3135
-        if ($table_obj instanceof EE_Secondary_Table) {
3136
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3137
-        } else {
3138
-            $table_pk_field_name = $table_obj->get_pk_column();
3139
-        }
3140
-
3141
-        $query =
3142
-            "UPDATE `{$table_name}`
337
+				$this->_props_n_values_provided_in_constructor
338
+				&& $field_value
339
+				&& $field_name === $model->primary_key_name()
340
+			) {
341
+				// if so, we want all this object's fields to be filled either with
342
+				// what we've explicitly set on this model
343
+				// or what we have in the db
344
+				// echo "setting primary key!";
345
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
346
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
+				foreach ($fields_on_model as $field_obj) {
348
+					if (
349
+						! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
350
+						&& $field_obj->get_name() !== $field_name
351
+					) {
352
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
353
+					}
354
+				}
355
+				// oh this model object has an ID? well make sure its in the entity mapper
356
+				$model->add_to_entity_map($this);
357
+			}
358
+			// let's unset any cache for this field_name from the $_cached_properties property.
359
+			$this->_clear_cached_property($field_name);
360
+		} else {
361
+			throw new EE_Error(
362
+				sprintf(
363
+					esc_html__(
364
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
365
+						'event_espresso'
366
+					),
367
+					$field_name
368
+				)
369
+			);
370
+		}
371
+	}
372
+
373
+
374
+	/**
375
+	 * Set custom select values for model.
376
+	 *
377
+	 * @param array $custom_select_values
378
+	 */
379
+	public function setCustomSelectsValues(array $custom_select_values)
380
+	{
381
+		$this->custom_selection_results = $custom_select_values;
382
+	}
383
+
384
+
385
+	/**
386
+	 * Returns the custom select value for the provided alias if its set.
387
+	 * If not set, returns null.
388
+	 *
389
+	 * @param string $alias
390
+	 * @return string|int|float|null
391
+	 */
392
+	public function getCustomSelect($alias)
393
+	{
394
+		return isset($this->custom_selection_results[ $alias ])
395
+			? $this->custom_selection_results[ $alias ]
396
+			: null;
397
+	}
398
+
399
+
400
+	/**
401
+	 * This sets the field value on the db column if it exists for the given $column_name or
402
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
403
+	 *
404
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
405
+	 * @param string $field_name  Must be the exact column name.
406
+	 * @param mixed  $field_value The value to set.
407
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
+	 * @throws InvalidArgumentException
409
+	 * @throws InvalidInterfaceException
410
+	 * @throws InvalidDataTypeException
411
+	 * @throws EE_Error
412
+	 * @throws ReflectionException
413
+	 */
414
+	public function set_field_or_extra_meta($field_name, $field_value)
415
+	{
416
+		if ($this->get_model()->has_field($field_name)) {
417
+			$this->set($field_name, $field_value);
418
+			return true;
419
+		}
420
+		// ensure this object is saved first so that extra meta can be properly related.
421
+		$this->save();
422
+		return $this->update_extra_meta($field_name, $field_value);
423
+	}
424
+
425
+
426
+	/**
427
+	 * This retrieves the value of the db column set on this class or if that's not present
428
+	 * it will attempt to retrieve from extra_meta if found.
429
+	 * Example Usage:
430
+	 * Via EE_Message child class:
431
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
432
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
433
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
434
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
435
+	 * value for those extra fields dynamically via the EE_message object.
436
+	 *
437
+	 * @param  string $field_name expecting the fully qualified field name.
438
+	 * @return mixed|null  value for the field if found.  null if not found.
439
+	 * @throws ReflectionException
440
+	 * @throws InvalidArgumentException
441
+	 * @throws InvalidInterfaceException
442
+	 * @throws InvalidDataTypeException
443
+	 * @throws EE_Error
444
+	 */
445
+	public function get_field_or_extra_meta($field_name)
446
+	{
447
+		if ($this->get_model()->has_field($field_name)) {
448
+			$column_value = $this->get($field_name);
449
+		} else {
450
+			// This isn't a column in the main table, let's see if it is in the extra meta.
451
+			$column_value = $this->get_extra_meta($field_name, true, null);
452
+		}
453
+		return $column_value;
454
+	}
455
+
456
+
457
+	/**
458
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
459
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
460
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
461
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
462
+	 *
463
+	 * @access public
464
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
465
+	 * @return void
466
+	 * @throws InvalidArgumentException
467
+	 * @throws InvalidInterfaceException
468
+	 * @throws InvalidDataTypeException
469
+	 * @throws EE_Error
470
+	 * @throws ReflectionException
471
+	 */
472
+	public function set_timezone($timezone = '')
473
+	{
474
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
475
+		// make sure we clear all cached properties because they won't be relevant now
476
+		$this->_clear_cached_properties();
477
+		// make sure we update field settings and the date for all EE_Datetime_Fields
478
+		$model_fields = $this->get_model()->field_settings(false);
479
+		foreach ($model_fields as $field_name => $field_obj) {
480
+			if ($field_obj instanceof EE_Datetime_Field) {
481
+				$field_obj->set_timezone($this->_timezone);
482
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
+				}
485
+			}
486
+		}
487
+	}
488
+
489
+
490
+	/**
491
+	 * This just returns whatever is set for the current timezone.
492
+	 *
493
+	 * @access public
494
+	 * @return string timezone string
495
+	 */
496
+	public function get_timezone()
497
+	{
498
+		return $this->_timezone;
499
+	}
500
+
501
+
502
+	/**
503
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
504
+	 * internally instead of wp set date format options
505
+	 *
506
+	 * @since 4.6
507
+	 * @param string $format should be a format recognizable by PHP date() functions.
508
+	 */
509
+	public function set_date_format($format)
510
+	{
511
+		$this->_dt_frmt = $format;
512
+		// clear cached_properties because they won't be relevant now.
513
+		$this->_clear_cached_properties();
514
+	}
515
+
516
+
517
+	/**
518
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
519
+	 * class internally instead of wp set time format options.
520
+	 *
521
+	 * @since 4.6
522
+	 * @param string $format should be a format recognizable by PHP date() functions.
523
+	 */
524
+	public function set_time_format($format)
525
+	{
526
+		$this->_tm_frmt = $format;
527
+		// clear cached_properties because they won't be relevant now.
528
+		$this->_clear_cached_properties();
529
+	}
530
+
531
+
532
+	/**
533
+	 * This returns the current internal set format for the date and time formats.
534
+	 *
535
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
536
+	 *                             where the first value is the date format and the second value is the time format.
537
+	 * @return mixed string|array
538
+	 */
539
+	public function get_format($full = true)
540
+	{
541
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542
+	}
543
+
544
+
545
+	/**
546
+	 * cache
547
+	 * stores the passed model object on the current model object.
548
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
549
+	 *
550
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
551
+	 *                                       'Registration' associated with this model object
552
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
553
+	 *                                       that could be a payment or a registration)
554
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
555
+	 *                                       items which will be stored in an array on this object
556
+	 * @throws ReflectionException
557
+	 * @throws InvalidArgumentException
558
+	 * @throws InvalidInterfaceException
559
+	 * @throws InvalidDataTypeException
560
+	 * @throws EE_Error
561
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
562
+	 *                                       related thing, no array)
563
+	 */
564
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565
+	{
566
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
+		if (! $object_to_cache instanceof EE_Base_Class) {
568
+			return false;
569
+		}
570
+		// also get "how" the object is related, or throw an error
571
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572
+			throw new EE_Error(
573
+				sprintf(
574
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
575
+					$relationName,
576
+					get_class($this)
577
+				)
578
+			);
579
+		}
580
+		// how many things are related ?
581
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
582
+			// if it's a "belongs to" relationship, then there's only one related model object
583
+			// eg, if this is a registration, there's only 1 attendee for it
584
+			// so for these model objects just set it to be cached
585
+			$this->_model_relations[ $relationName ] = $object_to_cache;
586
+			$return = true;
587
+		} else {
588
+			// otherwise, this is the "many" side of a one to many relationship,
589
+			// so we'll add the object to the array of related objects for that type.
590
+			// eg: if this is an event, there are many registrations for that event,
591
+			// so we cache the registrations in an array
592
+			if (! is_array($this->_model_relations[ $relationName ])) {
593
+				// if for some reason, the cached item is a model object,
594
+				// then stick that in the array, otherwise start with an empty array
595
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
596
+														   instanceof
597
+														   EE_Base_Class
598
+					? array($this->_model_relations[ $relationName ]) : array();
599
+			}
600
+			// first check for a cache_id which is normally empty
601
+			if (! empty($cache_id)) {
602
+				// if the cache_id exists, then it means we are purposely trying to cache this
603
+				// with a known key that can then be used to retrieve the object later on
604
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
605
+				$return = $cache_id;
606
+			} elseif ($object_to_cache->ID()) {
607
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
608
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
609
+				$return = $object_to_cache->ID();
610
+			} else {
611
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
613
+				// move the internal pointer to the end of the array
614
+				end($this->_model_relations[ $relationName ]);
615
+				// and grab the key so that we can return it
616
+				$return = key($this->_model_relations[ $relationName ]);
617
+			}
618
+		}
619
+		return $return;
620
+	}
621
+
622
+
623
+	/**
624
+	 * For adding an item to the cached_properties property.
625
+	 *
626
+	 * @access protected
627
+	 * @param string      $fieldname the property item the corresponding value is for.
628
+	 * @param mixed       $value     The value we are caching.
629
+	 * @param string|null $cache_type
630
+	 * @return void
631
+	 * @throws ReflectionException
632
+	 * @throws InvalidArgumentException
633
+	 * @throws InvalidInterfaceException
634
+	 * @throws InvalidDataTypeException
635
+	 * @throws EE_Error
636
+	 */
637
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
638
+	{
639
+		// first make sure this property exists
640
+		$this->get_model()->field_settings_for($fieldname);
641
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
643
+	}
644
+
645
+
646
+	/**
647
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
648
+	 * This also SETS the cache if we return the actual property!
649
+	 *
650
+	 * @param string $fieldname        the name of the property we're trying to retrieve
651
+	 * @param bool   $pretty
652
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
653
+	 *                                 (in cases where the same property may be used for different outputs
654
+	 *                                 - i.e. datetime, money etc.)
655
+	 *                                 It can also accept certain pre-defined "schema" strings
656
+	 *                                 to define how to output the property.
657
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
658
+	 * @return mixed                   whatever the value for the property is we're retrieving
659
+	 * @throws ReflectionException
660
+	 * @throws InvalidArgumentException
661
+	 * @throws InvalidInterfaceException
662
+	 * @throws InvalidDataTypeException
663
+	 * @throws EE_Error
664
+	 */
665
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
666
+	{
667
+		// verify the field exists
668
+		$model = $this->get_model();
669
+		$model->field_settings_for($fieldname);
670
+		$cache_type = $pretty ? 'pretty' : 'standard';
671
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
+		}
675
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676
+		$this->_set_cached_property($fieldname, $value, $cache_type);
677
+		return $value;
678
+	}
679
+
680
+
681
+	/**
682
+	 * If the cache didn't fetch the needed item, this fetches it.
683
+	 *
684
+	 * @param string $fieldname
685
+	 * @param bool   $pretty
686
+	 * @param string $extra_cache_ref
687
+	 * @return mixed
688
+	 * @throws InvalidArgumentException
689
+	 * @throws InvalidInterfaceException
690
+	 * @throws InvalidDataTypeException
691
+	 * @throws EE_Error
692
+	 * @throws ReflectionException
693
+	 */
694
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
695
+	{
696
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
697
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
698
+		if ($field_obj instanceof EE_Datetime_Field) {
699
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700
+		}
701
+		if (! isset($this->_fields[ $fieldname ])) {
702
+			$this->_fields[ $fieldname ] = null;
703
+		}
704
+		$value = $pretty
705
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
707
+		return $value;
708
+	}
709
+
710
+
711
+	/**
712
+	 * set timezone, formats, and output for EE_Datetime_Field objects
713
+	 *
714
+	 * @param \EE_Datetime_Field $datetime_field
715
+	 * @param bool               $pretty
716
+	 * @param null               $date_or_time
717
+	 * @return void
718
+	 * @throws InvalidArgumentException
719
+	 * @throws InvalidInterfaceException
720
+	 * @throws InvalidDataTypeException
721
+	 * @throws EE_Error
722
+	 */
723
+	protected function _prepare_datetime_field(
724
+		EE_Datetime_Field $datetime_field,
725
+		$pretty = false,
726
+		$date_or_time = null
727
+	) {
728
+		$datetime_field->set_timezone($this->_timezone);
729
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
730
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
731
+		// set the output returned
732
+		switch ($date_or_time) {
733
+			case 'D':
734
+				$datetime_field->set_date_time_output('date');
735
+				break;
736
+			case 'T':
737
+				$datetime_field->set_date_time_output('time');
738
+				break;
739
+			default:
740
+				$datetime_field->set_date_time_output();
741
+		}
742
+	}
743
+
744
+
745
+	/**
746
+	 * This just takes care of clearing out the cached_properties
747
+	 *
748
+	 * @return void
749
+	 */
750
+	protected function _clear_cached_properties()
751
+	{
752
+		$this->_cached_properties = array();
753
+	}
754
+
755
+
756
+	/**
757
+	 * This just clears out ONE property if it exists in the cache
758
+	 *
759
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
760
+	 * @return void
761
+	 */
762
+	protected function _clear_cached_property($property_name)
763
+	{
764
+		if (isset($this->_cached_properties[ $property_name ])) {
765
+			unset($this->_cached_properties[ $property_name ]);
766
+		}
767
+	}
768
+
769
+
770
+	/**
771
+	 * Ensures that this related thing is a model object.
772
+	 *
773
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
774
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
775
+	 * @return EE_Base_Class
776
+	 * @throws ReflectionException
777
+	 * @throws InvalidArgumentException
778
+	 * @throws InvalidInterfaceException
779
+	 * @throws InvalidDataTypeException
780
+	 * @throws EE_Error
781
+	 */
782
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
783
+	{
784
+		$other_model_instance = self::_get_model_instance_with_name(
785
+			self::_get_model_classname($model_name),
786
+			$this->_timezone
787
+		);
788
+		return $other_model_instance->ensure_is_obj($object_or_id);
789
+	}
790
+
791
+
792
+	/**
793
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
794
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
795
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
796
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
797
+	 *
798
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
799
+	 *                                                     Eg 'Registration'
800
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
801
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
802
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
803
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
804
+	 *                                                     this is HasMany or HABTM.
805
+	 * @throws ReflectionException
806
+	 * @throws InvalidArgumentException
807
+	 * @throws InvalidInterfaceException
808
+	 * @throws InvalidDataTypeException
809
+	 * @throws EE_Error
810
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
811
+	 *                                                     relation from all
812
+	 */
813
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
814
+	{
815
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
816
+		$index_in_cache = '';
817
+		if (! $relationship_to_model) {
818
+			throw new EE_Error(
819
+				sprintf(
820
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
821
+					$relationName,
822
+					get_class($this)
823
+				)
824
+			);
825
+		}
826
+		if ($clear_all) {
827
+			$obj_removed = true;
828
+			$this->_model_relations[ $relationName ] = null;
829
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
830
+			$obj_removed = $this->_model_relations[ $relationName ];
831
+			$this->_model_relations[ $relationName ] = null;
832
+		} else {
833
+			if (
834
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
835
+				&& $object_to_remove_or_index_into_array->ID()
836
+			) {
837
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
838
+				if (
839
+					is_array($this->_model_relations[ $relationName ])
840
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
841
+				) {
842
+					$index_found_at = null;
843
+					// find this object in the array even though it has a different key
844
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
845
+						/** @noinspection TypeUnsafeComparisonInspection */
846
+						if (
847
+							$obj instanceof EE_Base_Class
848
+							&& (
849
+								$obj == $object_to_remove_or_index_into_array
850
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
851
+							)
852
+						) {
853
+							$index_found_at = $index;
854
+							break;
855
+						}
856
+					}
857
+					if ($index_found_at) {
858
+						$index_in_cache = $index_found_at;
859
+					} else {
860
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
861
+						// if it wasn't in it to begin with. So we're done
862
+						return $object_to_remove_or_index_into_array;
863
+					}
864
+				}
865
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
866
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
867
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
868
+					/** @noinspection TypeUnsafeComparisonInspection */
869
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
870
+						$index_in_cache = $index;
871
+					}
872
+				}
873
+			} else {
874
+				$index_in_cache = $object_to_remove_or_index_into_array;
875
+			}
876
+			// supposedly we've found it. But it could just be that the client code
877
+			// provided a bad index/object
878
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
879
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
880
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
881
+			} else {
882
+				// that thing was never cached anyways.
883
+				$obj_removed = null;
884
+			}
885
+		}
886
+		return $obj_removed;
887
+	}
888
+
889
+
890
+	/**
891
+	 * update_cache_after_object_save
892
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
893
+	 * obtained after being saved to the db
894
+	 *
895
+	 * @param string        $relationName       - the type of object that is cached
896
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
897
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
898
+	 * @return boolean TRUE on success, FALSE on fail
899
+	 * @throws ReflectionException
900
+	 * @throws InvalidArgumentException
901
+	 * @throws InvalidInterfaceException
902
+	 * @throws InvalidDataTypeException
903
+	 * @throws EE_Error
904
+	 */
905
+	public function update_cache_after_object_save(
906
+		$relationName,
907
+		EE_Base_Class $newly_saved_object,
908
+		$current_cache_id = ''
909
+	) {
910
+		// verify that incoming object is of the correct type
911
+		$obj_class = 'EE_' . $relationName;
912
+		if ($newly_saved_object instanceof $obj_class) {
913
+			/* @type EE_Base_Class $newly_saved_object */
914
+			// now get the type of relation
915
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
916
+			// if this is a 1:1 relationship
917
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
918
+				// then just replace the cached object with the newly saved object
919
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
920
+				return true;
921
+				// or if it's some kind of sordid feral polyamorous relationship...
922
+			}
923
+			if (
924
+				is_array($this->_model_relations[ $relationName ])
925
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
926
+			) {
927
+				// then remove the current cached item
928
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
929
+				// and cache the newly saved object using it's new ID
930
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
931
+				return true;
932
+			}
933
+		}
934
+		return false;
935
+	}
936
+
937
+
938
+	/**
939
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
940
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
941
+	 *
942
+	 * @param string $relationName
943
+	 * @return EE_Base_Class
944
+	 */
945
+	public function get_one_from_cache($relationName)
946
+	{
947
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
948
+			? $this->_model_relations[ $relationName ]
949
+			: null;
950
+		if (is_array($cached_array_or_object)) {
951
+			return array_shift($cached_array_or_object);
952
+		}
953
+		return $cached_array_or_object;
954
+	}
955
+
956
+
957
+	/**
958
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
959
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
960
+	 *
961
+	 * @param string $relationName
962
+	 * @throws ReflectionException
963
+	 * @throws InvalidArgumentException
964
+	 * @throws InvalidInterfaceException
965
+	 * @throws InvalidDataTypeException
966
+	 * @throws EE_Error
967
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
968
+	 */
969
+	public function get_all_from_cache($relationName)
970
+	{
971
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
972
+		// if the result is not an array, but exists, make it an array
973
+		$objects = is_array($objects) ? $objects : array($objects);
974
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
975
+		// basically, if this model object was stored in the session, and these cached model objects
976
+		// already have IDs, let's make sure they're in their model's entity mapper
977
+		// otherwise we will have duplicates next time we call
978
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
979
+		$model = EE_Registry::instance()->load_model($relationName);
980
+		foreach ($objects as $model_object) {
981
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
982
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
983
+				if ($model_object->ID()) {
984
+					$model->add_to_entity_map($model_object);
985
+				}
986
+			} else {
987
+				throw new EE_Error(
988
+					sprintf(
989
+						esc_html__(
990
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
991
+							'event_espresso'
992
+						),
993
+						$relationName,
994
+						gettype($model_object)
995
+					)
996
+				);
997
+			}
998
+		}
999
+		return $objects;
1000
+	}
1001
+
1002
+
1003
+	/**
1004
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1005
+	 * matching the given query conditions.
1006
+	 *
1007
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1008
+	 * @param int   $limit              How many objects to return.
1009
+	 * @param array $query_params       Any additional conditions on the query.
1010
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1011
+	 *                                  you can indicate just the columns you want returned
1012
+	 * @return array|EE_Base_Class[]
1013
+	 * @throws ReflectionException
1014
+	 * @throws InvalidArgumentException
1015
+	 * @throws InvalidInterfaceException
1016
+	 * @throws InvalidDataTypeException
1017
+	 * @throws EE_Error
1018
+	 */
1019
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1020
+	{
1021
+		$model = $this->get_model();
1022
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1023
+			? $model->get_primary_key_field()->get_name()
1024
+			: $field_to_order_by;
1025
+		$current_value = ! empty($field) ? $this->get($field) : null;
1026
+		if (empty($field) || empty($current_value)) {
1027
+			return array();
1028
+		}
1029
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1030
+	}
1031
+
1032
+
1033
+	/**
1034
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1035
+	 * matching the given query conditions.
1036
+	 *
1037
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1038
+	 * @param int   $limit              How many objects to return.
1039
+	 * @param array $query_params       Any additional conditions on the query.
1040
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1041
+	 *                                  you can indicate just the columns you want returned
1042
+	 * @return array|EE_Base_Class[]
1043
+	 * @throws ReflectionException
1044
+	 * @throws InvalidArgumentException
1045
+	 * @throws InvalidInterfaceException
1046
+	 * @throws InvalidDataTypeException
1047
+	 * @throws EE_Error
1048
+	 */
1049
+	public function previous_x(
1050
+		$field_to_order_by = null,
1051
+		$limit = 1,
1052
+		$query_params = array(),
1053
+		$columns_to_select = null
1054
+	) {
1055
+		$model = $this->get_model();
1056
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1057
+			? $model->get_primary_key_field()->get_name()
1058
+			: $field_to_order_by;
1059
+		$current_value = ! empty($field) ? $this->get($field) : null;
1060
+		if (empty($field) || empty($current_value)) {
1061
+			return array();
1062
+		}
1063
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1064
+	}
1065
+
1066
+
1067
+	/**
1068
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1069
+	 * matching the given query conditions.
1070
+	 *
1071
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1072
+	 * @param array $query_params       Any additional conditions on the query.
1073
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1074
+	 *                                  you can indicate just the columns you want returned
1075
+	 * @return array|EE_Base_Class
1076
+	 * @throws ReflectionException
1077
+	 * @throws InvalidArgumentException
1078
+	 * @throws InvalidInterfaceException
1079
+	 * @throws InvalidDataTypeException
1080
+	 * @throws EE_Error
1081
+	 */
1082
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1083
+	{
1084
+		$model = $this->get_model();
1085
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1086
+			? $model->get_primary_key_field()->get_name()
1087
+			: $field_to_order_by;
1088
+		$current_value = ! empty($field) ? $this->get($field) : null;
1089
+		if (empty($field) || empty($current_value)) {
1090
+			return array();
1091
+		}
1092
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1093
+	}
1094
+
1095
+
1096
+	/**
1097
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1098
+	 * matching the given query conditions.
1099
+	 *
1100
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1101
+	 * @param array $query_params       Any additional conditions on the query.
1102
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1103
+	 *                                  you can indicate just the column you want returned
1104
+	 * @return array|EE_Base_Class
1105
+	 * @throws ReflectionException
1106
+	 * @throws InvalidArgumentException
1107
+	 * @throws InvalidInterfaceException
1108
+	 * @throws InvalidDataTypeException
1109
+	 * @throws EE_Error
1110
+	 */
1111
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1112
+	{
1113
+		$model = $this->get_model();
1114
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1115
+			? $model->get_primary_key_field()->get_name()
1116
+			: $field_to_order_by;
1117
+		$current_value = ! empty($field) ? $this->get($field) : null;
1118
+		if (empty($field) || empty($current_value)) {
1119
+			return array();
1120
+		}
1121
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1122
+	}
1123
+
1124
+
1125
+	/**
1126
+	 * Overrides parent because parent expects old models.
1127
+	 * This also doesn't do any validation, and won't work for serialized arrays
1128
+	 *
1129
+	 * @param string $field_name
1130
+	 * @param mixed  $field_value_from_db
1131
+	 * @throws ReflectionException
1132
+	 * @throws InvalidArgumentException
1133
+	 * @throws InvalidInterfaceException
1134
+	 * @throws InvalidDataTypeException
1135
+	 * @throws EE_Error
1136
+	 */
1137
+	public function set_from_db($field_name, $field_value_from_db)
1138
+	{
1139
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1140
+		if ($field_obj instanceof EE_Model_Field_Base) {
1141
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
1142
+			// eg, a CPT model object could have an entry in the posts table, but no
1143
+			// entry in the meta table. Meaning that all its columns in the meta table
1144
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
1145
+			if ($field_value_from_db === null) {
1146
+				if ($field_obj->is_nullable()) {
1147
+					// if the field allows nulls, then let it be null
1148
+					$field_value = null;
1149
+				} else {
1150
+					$field_value = $field_obj->get_default_value();
1151
+				}
1152
+			} else {
1153
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1154
+			}
1155
+			$this->_fields[ $field_name ] = $field_value;
1156
+			$this->_clear_cached_property($field_name);
1157
+		}
1158
+	}
1159
+
1160
+
1161
+	/**
1162
+	 * verifies that the specified field is of the correct type
1163
+	 *
1164
+	 * @param string $field_name
1165
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1166
+	 *                                (in cases where the same property may be used for different outputs
1167
+	 *                                - i.e. datetime, money etc.)
1168
+	 * @return mixed
1169
+	 * @throws ReflectionException
1170
+	 * @throws InvalidArgumentException
1171
+	 * @throws InvalidInterfaceException
1172
+	 * @throws InvalidDataTypeException
1173
+	 * @throws EE_Error
1174
+	 */
1175
+	public function get($field_name, $extra_cache_ref = null)
1176
+	{
1177
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1183
+	 *
1184
+	 * @param  string $field_name A valid fieldname
1185
+	 * @return mixed              Whatever the raw value stored on the property is.
1186
+	 * @throws ReflectionException
1187
+	 * @throws InvalidArgumentException
1188
+	 * @throws InvalidInterfaceException
1189
+	 * @throws InvalidDataTypeException
1190
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1191
+	 */
1192
+	public function get_raw($field_name)
1193
+	{
1194
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1195
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
+			? $this->_fields[ $field_name ]->format('U')
1197
+			: $this->_fields[ $field_name ];
1198
+	}
1199
+
1200
+
1201
+	/**
1202
+	 * This is used to return the internal DateTime object used for a field that is a
1203
+	 * EE_Datetime_Field.
1204
+	 *
1205
+	 * @param string $field_name               The field name retrieving the DateTime object.
1206
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1207
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1208
+	 *                                         EE_Datetime_Field and but the field value is null, then
1209
+	 *                                         just null is returned (because that indicates that likely
1210
+	 *                                         this field is nullable).
1211
+	 * @throws InvalidArgumentException
1212
+	 * @throws InvalidDataTypeException
1213
+	 * @throws InvalidInterfaceException
1214
+	 * @throws ReflectionException
1215
+	 */
1216
+	public function get_DateTime_object($field_name)
1217
+	{
1218
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1219
+		if (! $field_settings instanceof EE_Datetime_Field) {
1220
+			EE_Error::add_error(
1221
+				sprintf(
1222
+					esc_html__(
1223
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1224
+						'event_espresso'
1225
+					),
1226
+					$field_name
1227
+				),
1228
+				__FILE__,
1229
+				__FUNCTION__,
1230
+				__LINE__
1231
+			);
1232
+			return false;
1233
+		}
1234
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
+			? clone $this->_fields[ $field_name ]
1236
+			: null;
1237
+	}
1238
+
1239
+
1240
+	/**
1241
+	 * To be used in template to immediately echo out the value, and format it for output.
1242
+	 * Eg, should call stripslashes and whatnot before echoing
1243
+	 *
1244
+	 * @param string $field_name      the name of the field as it appears in the DB
1245
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1246
+	 *                                (in cases where the same property may be used for different outputs
1247
+	 *                                - i.e. datetime, money etc.)
1248
+	 * @return void
1249
+	 * @throws ReflectionException
1250
+	 * @throws InvalidArgumentException
1251
+	 * @throws InvalidInterfaceException
1252
+	 * @throws InvalidDataTypeException
1253
+	 * @throws EE_Error
1254
+	 */
1255
+	public function e($field_name, $extra_cache_ref = null)
1256
+	{
1257
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1258
+	}
1259
+
1260
+
1261
+	/**
1262
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1263
+	 * can be easily used as the value of form input.
1264
+	 *
1265
+	 * @param string $field_name
1266
+	 * @return void
1267
+	 * @throws ReflectionException
1268
+	 * @throws InvalidArgumentException
1269
+	 * @throws InvalidInterfaceException
1270
+	 * @throws InvalidDataTypeException
1271
+	 * @throws EE_Error
1272
+	 */
1273
+	public function f($field_name)
1274
+	{
1275
+		$this->e($field_name, 'form_input');
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * Same as `f()` but just returns the value instead of echoing it
1281
+	 *
1282
+	 * @param string $field_name
1283
+	 * @return string
1284
+	 * @throws ReflectionException
1285
+	 * @throws InvalidArgumentException
1286
+	 * @throws InvalidInterfaceException
1287
+	 * @throws InvalidDataTypeException
1288
+	 * @throws EE_Error
1289
+	 */
1290
+	public function get_f($field_name)
1291
+	{
1292
+		return (string) $this->get_pretty($field_name, 'form_input');
1293
+	}
1294
+
1295
+
1296
+	/**
1297
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1298
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1299
+	 * to see what options are available.
1300
+	 *
1301
+	 * @param string $field_name
1302
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1303
+	 *                                (in cases where the same property may be used for different outputs
1304
+	 *                                - i.e. datetime, money etc.)
1305
+	 * @return mixed
1306
+	 * @throws ReflectionException
1307
+	 * @throws InvalidArgumentException
1308
+	 * @throws InvalidInterfaceException
1309
+	 * @throws InvalidDataTypeException
1310
+	 * @throws EE_Error
1311
+	 */
1312
+	public function get_pretty($field_name, $extra_cache_ref = null)
1313
+	{
1314
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1315
+	}
1316
+
1317
+
1318
+	/**
1319
+	 * This simply returns the datetime for the given field name
1320
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1321
+	 * (and the equivalent e_date, e_time, e_datetime).
1322
+	 *
1323
+	 * @access   protected
1324
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1325
+	 * @param string   $dt_frmt      valid datetime format used for date
1326
+	 *                               (if '' then we just use the default on the field,
1327
+	 *                               if NULL we use the last-used format)
1328
+	 * @param string   $tm_frmt      Same as above except this is for time format
1329
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1330
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1331
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1332
+	 *                               if field is not a valid dtt field, or void if echoing
1333
+	 * @throws ReflectionException
1334
+	 * @throws InvalidArgumentException
1335
+	 * @throws InvalidInterfaceException
1336
+	 * @throws InvalidDataTypeException
1337
+	 * @throws EE_Error
1338
+	 */
1339
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1340
+	{
1341
+		// clear cached property
1342
+		$this->_clear_cached_property($field_name);
1343
+		// reset format properties because they are used in get()
1344
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1345
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1346
+		if ($echo) {
1347
+			$this->e($field_name, $date_or_time);
1348
+			return '';
1349
+		}
1350
+		return $this->get($field_name, $date_or_time);
1351
+	}
1352
+
1353
+
1354
+	/**
1355
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1356
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1357
+	 * other echoes the pretty value for dtt)
1358
+	 *
1359
+	 * @param  string $field_name name of model object datetime field holding the value
1360
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1361
+	 * @return string            datetime value formatted
1362
+	 * @throws ReflectionException
1363
+	 * @throws InvalidArgumentException
1364
+	 * @throws InvalidInterfaceException
1365
+	 * @throws InvalidDataTypeException
1366
+	 * @throws EE_Error
1367
+	 */
1368
+	public function get_date($field_name, $format = '')
1369
+	{
1370
+		return $this->_get_datetime($field_name, $format, null, 'D');
1371
+	}
1372
+
1373
+
1374
+	/**
1375
+	 * @param        $field_name
1376
+	 * @param string $format
1377
+	 * @throws ReflectionException
1378
+	 * @throws InvalidArgumentException
1379
+	 * @throws InvalidInterfaceException
1380
+	 * @throws InvalidDataTypeException
1381
+	 * @throws EE_Error
1382
+	 */
1383
+	public function e_date($field_name, $format = '')
1384
+	{
1385
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1386
+	}
1387
+
1388
+
1389
+	/**
1390
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1391
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1392
+	 * other echoes the pretty value for dtt)
1393
+	 *
1394
+	 * @param  string $field_name name of model object datetime field holding the value
1395
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1396
+	 * @return string             datetime value formatted
1397
+	 * @throws ReflectionException
1398
+	 * @throws InvalidArgumentException
1399
+	 * @throws InvalidInterfaceException
1400
+	 * @throws InvalidDataTypeException
1401
+	 * @throws EE_Error
1402
+	 */
1403
+	public function get_time($field_name, $format = '')
1404
+	{
1405
+		return $this->_get_datetime($field_name, null, $format, 'T');
1406
+	}
1407
+
1408
+
1409
+	/**
1410
+	 * @param        $field_name
1411
+	 * @param string $format
1412
+	 * @throws ReflectionException
1413
+	 * @throws InvalidArgumentException
1414
+	 * @throws InvalidInterfaceException
1415
+	 * @throws InvalidDataTypeException
1416
+	 * @throws EE_Error
1417
+	 */
1418
+	public function e_time($field_name, $format = '')
1419
+	{
1420
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1421
+	}
1422
+
1423
+
1424
+	/**
1425
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1426
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1427
+	 * other echoes the pretty value for dtt)
1428
+	 *
1429
+	 * @param  string $field_name name of model object datetime field holding the value
1430
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1431
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1432
+	 * @return string             datetime value formatted
1433
+	 * @throws ReflectionException
1434
+	 * @throws InvalidArgumentException
1435
+	 * @throws InvalidInterfaceException
1436
+	 * @throws InvalidDataTypeException
1437
+	 * @throws EE_Error
1438
+	 */
1439
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1440
+	{
1441
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1442
+	}
1443
+
1444
+
1445
+	/**
1446
+	 * @param string $field_name
1447
+	 * @param string $dt_frmt
1448
+	 * @param string $tm_frmt
1449
+	 * @throws ReflectionException
1450
+	 * @throws InvalidArgumentException
1451
+	 * @throws InvalidInterfaceException
1452
+	 * @throws InvalidDataTypeException
1453
+	 * @throws EE_Error
1454
+	 */
1455
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1456
+	{
1457
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1458
+	}
1459
+
1460
+
1461
+	/**
1462
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1463
+	 *
1464
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1465
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1466
+	 *                           on the object will be used.
1467
+	 * @return string Date and time string in set locale or false if no field exists for the given
1468
+	 * @throws ReflectionException
1469
+	 * @throws InvalidArgumentException
1470
+	 * @throws InvalidInterfaceException
1471
+	 * @throws InvalidDataTypeException
1472
+	 * @throws EE_Error
1473
+	 *                           field name.
1474
+	 */
1475
+	public function get_i18n_datetime($field_name, $format = '')
1476
+	{
1477
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1478
+		return date_i18n(
1479
+			$format,
1480
+			EEH_DTT_Helper::get_timestamp_with_offset(
1481
+				$this->get_raw($field_name),
1482
+				$this->_timezone
1483
+			)
1484
+		);
1485
+	}
1486
+
1487
+
1488
+	/**
1489
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1490
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1491
+	 * thrown.
1492
+	 *
1493
+	 * @param  string $field_name The field name being checked
1494
+	 * @throws ReflectionException
1495
+	 * @throws InvalidArgumentException
1496
+	 * @throws InvalidInterfaceException
1497
+	 * @throws InvalidDataTypeException
1498
+	 * @throws EE_Error
1499
+	 * @return EE_Datetime_Field
1500
+	 */
1501
+	protected function _get_dtt_field_settings($field_name)
1502
+	{
1503
+		$field = $this->get_model()->field_settings_for($field_name);
1504
+		// check if field is dtt
1505
+		if ($field instanceof EE_Datetime_Field) {
1506
+			return $field;
1507
+		}
1508
+		throw new EE_Error(
1509
+			sprintf(
1510
+				esc_html__(
1511
+					'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1512
+					'event_espresso'
1513
+				),
1514
+				$field_name,
1515
+				self::_get_model_classname(get_class($this))
1516
+			)
1517
+		);
1518
+	}
1519
+
1520
+
1521
+
1522
+
1523
+	/**
1524
+	 * NOTE ABOUT BELOW:
1525
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1526
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1527
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1528
+	 * method and make sure you send the entire datetime value for setting.
1529
+	 */
1530
+	/**
1531
+	 * sets the time on a datetime property
1532
+	 *
1533
+	 * @access protected
1534
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1535
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1536
+	 * @throws ReflectionException
1537
+	 * @throws InvalidArgumentException
1538
+	 * @throws InvalidInterfaceException
1539
+	 * @throws InvalidDataTypeException
1540
+	 * @throws EE_Error
1541
+	 */
1542
+	protected function _set_time_for($time, $fieldname)
1543
+	{
1544
+		$this->_set_date_time('T', $time, $fieldname);
1545
+	}
1546
+
1547
+
1548
+	/**
1549
+	 * sets the date on a datetime property
1550
+	 *
1551
+	 * @access protected
1552
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1553
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1554
+	 * @throws ReflectionException
1555
+	 * @throws InvalidArgumentException
1556
+	 * @throws InvalidInterfaceException
1557
+	 * @throws InvalidDataTypeException
1558
+	 * @throws EE_Error
1559
+	 */
1560
+	protected function _set_date_for($date, $fieldname)
1561
+	{
1562
+		$this->_set_date_time('D', $date, $fieldname);
1563
+	}
1564
+
1565
+
1566
+	/**
1567
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1568
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1569
+	 *
1570
+	 * @access protected
1571
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1572
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1573
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1574
+	 *                                        EE_Datetime_Field property)
1575
+	 * @throws ReflectionException
1576
+	 * @throws InvalidArgumentException
1577
+	 * @throws InvalidInterfaceException
1578
+	 * @throws InvalidDataTypeException
1579
+	 * @throws EE_Error
1580
+	 */
1581
+	protected function _set_date_time($what, $datetime_value, $fieldname)
1582
+	{
1583
+		$what  = $what ?: 'T';
1584
+		$field = $this->_get_dtt_field_settings($fieldname);
1585
+		$field->set_timezone($this->_timezone);
1586
+		$field->set_date_format($this->_dt_frmt);
1587
+		$field->set_time_format($this->_tm_frmt);
1588
+		switch ($what) {
1589
+			case 'T':
1590
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1591
+					$datetime_value,
1592
+					$this->_fields[ $fieldname ]
1593
+				);
1594
+				$this->_has_changes = true;
1595
+				break;
1596
+			case 'D':
1597
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1598
+					$datetime_value,
1599
+					$this->_fields[ $fieldname ]
1600
+				);
1601
+				$this->_has_changes = true;
1602
+				break;
1603
+			case 'B':
1604
+				$this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1605
+				$this->_has_changes = true;
1606
+				break;
1607
+		}
1608
+		$this->_clear_cached_property($fieldname);
1609
+	}
1610
+
1611
+
1612
+	/**
1613
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1614
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1615
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1616
+	 * that could lead to some unexpected results!
1617
+	 *
1618
+	 * @access public
1619
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1620
+	 *                                         value being returned.
1621
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1622
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1623
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1624
+	 * @param string $append                   You can include something to append on the timestamp
1625
+	 * @throws ReflectionException
1626
+	 * @throws InvalidArgumentException
1627
+	 * @throws InvalidInterfaceException
1628
+	 * @throws InvalidDataTypeException
1629
+	 * @throws EE_Error
1630
+	 * @return string timestamp
1631
+	 */
1632
+	public function display_in_my_timezone(
1633
+		$field_name,
1634
+		$callback = 'get_datetime',
1635
+		$args = null,
1636
+		$prepend = '',
1637
+		$append = ''
1638
+	) {
1639
+		$timezone = EEH_DTT_Helper::get_timezone();
1640
+		if ($timezone === $this->_timezone) {
1641
+			return '';
1642
+		}
1643
+		$original_timezone = $this->_timezone;
1644
+		$this->set_timezone($timezone);
1645
+		$fn = (array) $field_name;
1646
+		$args = array_merge($fn, (array) $args);
1647
+		if (! method_exists($this, $callback)) {
1648
+			throw new EE_Error(
1649
+				sprintf(
1650
+					esc_html__(
1651
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1652
+						'event_espresso'
1653
+					),
1654
+					$callback
1655
+				)
1656
+			);
1657
+		}
1658
+		$args = (array) $args;
1659
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1660
+		$this->set_timezone($original_timezone);
1661
+		return $return;
1662
+	}
1663
+
1664
+
1665
+	/**
1666
+	 * Deletes this model object.
1667
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1668
+	 * override
1669
+	 * `EE_Base_Class::_delete` NOT this class.
1670
+	 *
1671
+	 * @return boolean | int
1672
+	 * @throws ReflectionException
1673
+	 * @throws InvalidArgumentException
1674
+	 * @throws InvalidInterfaceException
1675
+	 * @throws InvalidDataTypeException
1676
+	 * @throws EE_Error
1677
+	 */
1678
+	public function delete()
1679
+	{
1680
+		/**
1681
+		 * Called just before the `EE_Base_Class::_delete` method call.
1682
+		 * Note:
1683
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1684
+		 * should be aware that `_delete` may not always result in a permanent delete.
1685
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1686
+		 * soft deletes (trash) the object and does not permanently delete it.
1687
+		 *
1688
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1689
+		 */
1690
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1691
+		$result = $this->_delete();
1692
+		/**
1693
+		 * Called just after the `EE_Base_Class::_delete` method call.
1694
+		 * Note:
1695
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1696
+		 * should be aware that `_delete` may not always result in a permanent delete.
1697
+		 * For example `EE_Soft_Base_Class::_delete`
1698
+		 * soft deletes (trash) the object and does not permanently delete it.
1699
+		 *
1700
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1701
+		 * @param boolean       $result
1702
+		 */
1703
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1704
+		return $result;
1705
+	}
1706
+
1707
+
1708
+	/**
1709
+	 * Calls the specific delete method for the instantiated class.
1710
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1711
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1712
+	 * `EE_Base_Class::delete`
1713
+	 *
1714
+	 * @return bool|int
1715
+	 * @throws ReflectionException
1716
+	 * @throws InvalidArgumentException
1717
+	 * @throws InvalidInterfaceException
1718
+	 * @throws InvalidDataTypeException
1719
+	 * @throws EE_Error
1720
+	 */
1721
+	protected function _delete()
1722
+	{
1723
+		return $this->delete_permanently();
1724
+	}
1725
+
1726
+
1727
+	/**
1728
+	 * Deletes this model object permanently from db
1729
+	 * (but keep in mind related models may block the delete and return an error)
1730
+	 *
1731
+	 * @return bool | int
1732
+	 * @throws ReflectionException
1733
+	 * @throws InvalidArgumentException
1734
+	 * @throws InvalidInterfaceException
1735
+	 * @throws InvalidDataTypeException
1736
+	 * @throws EE_Error
1737
+	 */
1738
+	public function delete_permanently()
1739
+	{
1740
+		/**
1741
+		 * Called just before HARD deleting a model object
1742
+		 *
1743
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1744
+		 */
1745
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1746
+		$model = $this->get_model();
1747
+		$result = $model->delete_permanently_by_ID($this->ID());
1748
+		$this->refresh_cache_of_related_objects();
1749
+		/**
1750
+		 * Called just after HARD deleting a model object
1751
+		 *
1752
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1753
+		 * @param boolean       $result
1754
+		 */
1755
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1756
+		return $result;
1757
+	}
1758
+
1759
+
1760
+	/**
1761
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1762
+	 * related model objects
1763
+	 *
1764
+	 * @throws ReflectionException
1765
+	 * @throws InvalidArgumentException
1766
+	 * @throws InvalidInterfaceException
1767
+	 * @throws InvalidDataTypeException
1768
+	 * @throws EE_Error
1769
+	 */
1770
+	public function refresh_cache_of_related_objects()
1771
+	{
1772
+		$model = $this->get_model();
1773
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1774
+			if (! empty($this->_model_relations[ $relation_name ])) {
1775
+				$related_objects = $this->_model_relations[ $relation_name ];
1776
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1777
+					// this relation only stores a single model object, not an array
1778
+					// but let's make it consistent
1779
+					$related_objects = array($related_objects);
1780
+				}
1781
+				foreach ($related_objects as $related_object) {
1782
+					// only refresh their cache if they're in memory
1783
+					if ($related_object instanceof EE_Base_Class) {
1784
+						$related_object->clear_cache(
1785
+							$model->get_this_model_name(),
1786
+							$this
1787
+						);
1788
+					}
1789
+				}
1790
+			}
1791
+		}
1792
+	}
1793
+
1794
+
1795
+	/**
1796
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1797
+	 * object just before saving.
1798
+	 *
1799
+	 * @access public
1800
+	 * @param array $set_cols_n_values  keys are field names, values are their new values,
1801
+	 *                                  if provided during the save() method
1802
+	 *                                  (often client code will change the fields' values before calling save)
1803
+	 * @return false|int|string         1 on a successful update;
1804
+	 *                                  the ID of the new entry on insert;
1805
+	 *                                  0 on failure, or if the model object isn't allowed to persist
1806
+	 *                                  (as determined by EE_Base_Class::allow_persist())
1807
+	 * @throws InvalidInterfaceException
1808
+	 * @throws InvalidDataTypeException
1809
+	 * @throws EE_Error
1810
+	 * @throws InvalidArgumentException
1811
+	 * @throws ReflectionException
1812
+	 * @throws ReflectionException
1813
+	 * @throws ReflectionException
1814
+	 */
1815
+	public function save($set_cols_n_values = array())
1816
+	{
1817
+		$model = $this->get_model();
1818
+		/**
1819
+		 * Filters the fields we're about to save on the model object
1820
+		 *
1821
+		 * @param array         $set_cols_n_values
1822
+		 * @param EE_Base_Class $model_object
1823
+		 */
1824
+		$set_cols_n_values = (array) apply_filters(
1825
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1826
+			$set_cols_n_values,
1827
+			$this
1828
+		);
1829
+		// set attributes as provided in $set_cols_n_values
1830
+		foreach ($set_cols_n_values as $column => $value) {
1831
+			$this->set($column, $value);
1832
+		}
1833
+		// no changes ? then don't do anything
1834
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1835
+			return 0;
1836
+		}
1837
+		/**
1838
+		 * Saving a model object.
1839
+		 * Before we perform a save, this action is fired.
1840
+		 *
1841
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1842
+		 */
1843
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1844
+		if (! $this->allow_persist()) {
1845
+			return 0;
1846
+		}
1847
+		// now get current attribute values
1848
+		$save_cols_n_values = $this->_fields;
1849
+		// if the object already has an ID, update it. Otherwise, insert it
1850
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1851
+		// They have been
1852
+		$old_assumption_concerning_value_preparation = $model
1853
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1854
+		$model->assume_values_already_prepared_by_model_object(true);
1855
+		// does this model have an autoincrement PK?
1856
+		if ($model->has_primary_key_field()) {
1857
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1858
+				// ok check if it's set, if so: update; if not, insert
1859
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1860
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1861
+				} else {
1862
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1863
+					$results = $model->insert($save_cols_n_values);
1864
+					if ($results) {
1865
+						// if successful, set the primary key
1866
+						// but don't use the normal SET method, because it will check if
1867
+						// an item with the same ID exists in the mapper & db, then
1868
+						// will find it in the db (because we just added it) and THAT object
1869
+						// will get added to the mapper before we can add this one!
1870
+						// but if we just avoid using the SET method, all that headache can be avoided
1871
+						$pk_field_name = $model->primary_key_name();
1872
+						$this->_fields[ $pk_field_name ] = $results;
1873
+						$this->_clear_cached_property($pk_field_name);
1874
+						$model->add_to_entity_map($this);
1875
+						$this->_update_cached_related_model_objs_fks();
1876
+					}
1877
+				}
1878
+			} else {// PK is NOT auto-increment
1879
+				// so check if one like it already exists in the db
1880
+				if ($model->exists_by_ID($this->ID())) {
1881
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1882
+						throw new EE_Error(
1883
+							sprintf(
1884
+								esc_html__(
1885
+									'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1886
+									'event_espresso'
1887
+								),
1888
+								get_class($this),
1889
+								get_class($model) . '::instance()->add_to_entity_map()',
1890
+								get_class($model) . '::instance()->get_one_by_ID()',
1891
+								'<br />'
1892
+							)
1893
+						);
1894
+					}
1895
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1896
+				} else {
1897
+					$results = $model->insert($save_cols_n_values);
1898
+					$this->_update_cached_related_model_objs_fks();
1899
+				}
1900
+			}
1901
+		} else {// there is NO primary key
1902
+			$already_in_db = false;
1903
+			foreach ($model->unique_indexes() as $index) {
1904
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1905
+				if ($model->exists(array($uniqueness_where_params))) {
1906
+					$already_in_db = true;
1907
+				}
1908
+			}
1909
+			if ($already_in_db) {
1910
+				$combined_pk_fields_n_values = array_intersect_key(
1911
+					$save_cols_n_values,
1912
+					$model->get_combined_primary_key_fields()
1913
+				);
1914
+				$results = $model->update(
1915
+					$save_cols_n_values,
1916
+					$combined_pk_fields_n_values
1917
+				);
1918
+			} else {
1919
+				$results = $model->insert($save_cols_n_values);
1920
+			}
1921
+		}
1922
+		// restore the old assumption about values being prepared by the model object
1923
+		$model->assume_values_already_prepared_by_model_object(
1924
+			$old_assumption_concerning_value_preparation
1925
+		);
1926
+		/**
1927
+		 * After saving the model object this action is called
1928
+		 *
1929
+		 * @param EE_Base_Class $model_object which was just saved
1930
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1931
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1932
+		 */
1933
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1934
+		$this->_has_changes = false;
1935
+		return $results;
1936
+	}
1937
+
1938
+
1939
+	/**
1940
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1941
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1942
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1943
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1944
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1945
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1946
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1947
+	 *
1948
+	 * @return void
1949
+	 * @throws ReflectionException
1950
+	 * @throws InvalidArgumentException
1951
+	 * @throws InvalidInterfaceException
1952
+	 * @throws InvalidDataTypeException
1953
+	 * @throws EE_Error
1954
+	 */
1955
+	protected function _update_cached_related_model_objs_fks()
1956
+	{
1957
+		$model = $this->get_model();
1958
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1959
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1960
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1961
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1962
+						$model->get_this_model_name()
1963
+					);
1964
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1965
+					if ($related_model_obj_in_cache->ID()) {
1966
+						$related_model_obj_in_cache->save();
1967
+					}
1968
+				}
1969
+			}
1970
+		}
1971
+	}
1972
+
1973
+
1974
+	/**
1975
+	 * Saves this model object and its NEW cached relations to the database.
1976
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1977
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1978
+	 * because otherwise, there's a potential for infinite looping of saving
1979
+	 * Saves the cached related model objects, and ensures the relation between them
1980
+	 * and this object and properly setup
1981
+	 *
1982
+	 * @return int ID of new model object on save; 0 on failure+
1983
+	 * @throws ReflectionException
1984
+	 * @throws InvalidArgumentException
1985
+	 * @throws InvalidInterfaceException
1986
+	 * @throws InvalidDataTypeException
1987
+	 * @throws EE_Error
1988
+	 */
1989
+	public function save_new_cached_related_model_objs()
1990
+	{
1991
+		// make sure this has been saved
1992
+		if (! $this->ID()) {
1993
+			$id = $this->save();
1994
+		} else {
1995
+			$id = $this->ID();
1996
+		}
1997
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1998
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1999
+			if ($this->_model_relations[ $relationName ]) {
2000
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2001
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2002
+				/* @var $related_model_obj EE_Base_Class */
2003
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
2004
+					// add a relation to that relation type (which saves the appropriate thing in the process)
2005
+					// but ONLY if it DOES NOT exist in the DB
2006
+					$related_model_obj = $this->_model_relations[ $relationName ];
2007
+					// if( ! $related_model_obj->ID()){
2008
+					$this->_add_relation_to($related_model_obj, $relationName);
2009
+					$related_model_obj->save_new_cached_related_model_objs();
2010
+					// }
2011
+				} else {
2012
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2013
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2014
+						// but ONLY if it DOES NOT exist in the DB
2015
+						// if( ! $related_model_obj->ID()){
2016
+						$this->_add_relation_to($related_model_obj, $relationName);
2017
+						$related_model_obj->save_new_cached_related_model_objs();
2018
+						// }
2019
+					}
2020
+				}
2021
+			}
2022
+		}
2023
+		return $id;
2024
+	}
2025
+
2026
+
2027
+	/**
2028
+	 * for getting a model while instantiated.
2029
+	 *
2030
+	 * @return EEM_Base | EEM_CPT_Base
2031
+	 * @throws ReflectionException
2032
+	 * @throws InvalidArgumentException
2033
+	 * @throws InvalidInterfaceException
2034
+	 * @throws InvalidDataTypeException
2035
+	 * @throws EE_Error
2036
+	 */
2037
+	public function get_model()
2038
+	{
2039
+		if (! $this->_model) {
2040
+			$modelName = self::_get_model_classname(get_class($this));
2041
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2042
+		} else {
2043
+			$this->_model->set_timezone($this->_timezone);
2044
+		}
2045
+		return $this->_model;
2046
+	}
2047
+
2048
+
2049
+	/**
2050
+	 * @param $props_n_values
2051
+	 * @param $classname
2052
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2053
+	 * @throws ReflectionException
2054
+	 * @throws InvalidArgumentException
2055
+	 * @throws InvalidInterfaceException
2056
+	 * @throws InvalidDataTypeException
2057
+	 * @throws EE_Error
2058
+	 */
2059
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2060
+	{
2061
+		// TODO: will not work for Term_Relationships because they have no PK!
2062
+		$primary_id_ref = self::_get_primary_key_name($classname);
2063
+		if (
2064
+			array_key_exists($primary_id_ref, $props_n_values)
2065
+			&& ! empty($props_n_values[ $primary_id_ref ])
2066
+		) {
2067
+			$id = $props_n_values[ $primary_id_ref ];
2068
+			return self::_get_model($classname)->get_from_entity_map($id);
2069
+		}
2070
+		return false;
2071
+	}
2072
+
2073
+
2074
+	/**
2075
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2076
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2077
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2078
+	 * we return false.
2079
+	 *
2080
+	 * @param  array  $props_n_values   incoming array of properties and their values
2081
+	 * @param  string $classname        the classname of the child class
2082
+	 * @param null    $timezone
2083
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2084
+	 *                                  date_format and the second value is the time format
2085
+	 * @return mixed (EE_Base_Class|bool)
2086
+	 * @throws InvalidArgumentException
2087
+	 * @throws InvalidInterfaceException
2088
+	 * @throws InvalidDataTypeException
2089
+	 * @throws EE_Error
2090
+	 * @throws ReflectionException
2091
+	 * @throws ReflectionException
2092
+	 * @throws ReflectionException
2093
+	 */
2094
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2095
+	{
2096
+		$existing = null;
2097
+		$model = self::_get_model($classname, $timezone);
2098
+		if ($model->has_primary_key_field()) {
2099
+			$primary_id_ref = self::_get_primary_key_name($classname);
2100
+			if (
2101
+				array_key_exists($primary_id_ref, $props_n_values)
2102
+				&& ! empty($props_n_values[ $primary_id_ref ])
2103
+			) {
2104
+				$existing = $model->get_one_by_ID(
2105
+					$props_n_values[ $primary_id_ref ]
2106
+				);
2107
+			}
2108
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2109
+			// no primary key on this model, but there's still a matching item in the DB
2110
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2111
+				self::_get_model($classname, $timezone)
2112
+					->get_index_primary_key_string($props_n_values)
2113
+			);
2114
+		}
2115
+		if ($existing) {
2116
+			// set date formats if present before setting values
2117
+			if (! empty($date_formats) && is_array($date_formats)) {
2118
+				$existing->set_date_format($date_formats[0]);
2119
+				$existing->set_time_format($date_formats[1]);
2120
+			} else {
2121
+				// set default formats for date and time
2122
+				$existing->set_date_format(get_option('date_format'));
2123
+				$existing->set_time_format(get_option('time_format'));
2124
+			}
2125
+			foreach ($props_n_values as $property => $field_value) {
2126
+				$existing->set($property, $field_value);
2127
+			}
2128
+			return $existing;
2129
+		}
2130
+		return false;
2131
+	}
2132
+
2133
+
2134
+	/**
2135
+	 * Gets the EEM_*_Model for this class
2136
+	 *
2137
+	 * @access public now, as this is more convenient
2138
+	 * @param      $classname
2139
+	 * @param null $timezone
2140
+	 * @throws ReflectionException
2141
+	 * @throws InvalidArgumentException
2142
+	 * @throws InvalidInterfaceException
2143
+	 * @throws InvalidDataTypeException
2144
+	 * @throws EE_Error
2145
+	 * @return EEM_Base
2146
+	 */
2147
+	protected static function _get_model($classname, $timezone = null)
2148
+	{
2149
+		// find model for this class
2150
+		if (! $classname) {
2151
+			throw new EE_Error(
2152
+				sprintf(
2153
+					esc_html__(
2154
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2155
+						'event_espresso'
2156
+					),
2157
+					$classname
2158
+				)
2159
+			);
2160
+		}
2161
+		$modelName = self::_get_model_classname($classname);
2162
+		return self::_get_model_instance_with_name($modelName, $timezone);
2163
+	}
2164
+
2165
+
2166
+	/**
2167
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2168
+	 *
2169
+	 * @param string $model_classname
2170
+	 * @param null   $timezone
2171
+	 * @return EEM_Base
2172
+	 * @throws ReflectionException
2173
+	 * @throws InvalidArgumentException
2174
+	 * @throws InvalidInterfaceException
2175
+	 * @throws InvalidDataTypeException
2176
+	 * @throws EE_Error
2177
+	 */
2178
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2179
+	{
2180
+		$model_classname = str_replace('EEM_', '', $model_classname);
2181
+		$model = EE_Registry::instance()->load_model($model_classname);
2182
+		$model->set_timezone($timezone);
2183
+		return $model;
2184
+	}
2185
+
2186
+
2187
+	/**
2188
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2189
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2190
+	 *
2191
+	 * @param null $model_name
2192
+	 * @return string like EEM_Attendee
2193
+	 */
2194
+	private static function _get_model_classname($model_name = null)
2195
+	{
2196
+		if (strpos($model_name, 'EE_') === 0) {
2197
+			$model_classname = str_replace('EE_', 'EEM_', $model_name);
2198
+		} else {
2199
+			$model_classname = 'EEM_' . $model_name;
2200
+		}
2201
+		return $model_classname;
2202
+	}
2203
+
2204
+
2205
+	/**
2206
+	 * returns the name of the primary key attribute
2207
+	 *
2208
+	 * @param null $classname
2209
+	 * @throws ReflectionException
2210
+	 * @throws InvalidArgumentException
2211
+	 * @throws InvalidInterfaceException
2212
+	 * @throws InvalidDataTypeException
2213
+	 * @throws EE_Error
2214
+	 * @return string
2215
+	 */
2216
+	protected static function _get_primary_key_name($classname = null)
2217
+	{
2218
+		if (! $classname) {
2219
+			throw new EE_Error(
2220
+				sprintf(
2221
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2222
+					$classname
2223
+				)
2224
+			);
2225
+		}
2226
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2227
+	}
2228
+
2229
+
2230
+	/**
2231
+	 * Gets the value of the primary key.
2232
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2233
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2234
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2235
+	 *
2236
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2237
+	 * @throws ReflectionException
2238
+	 * @throws InvalidArgumentException
2239
+	 * @throws InvalidInterfaceException
2240
+	 * @throws InvalidDataTypeException
2241
+	 * @throws EE_Error
2242
+	 */
2243
+	public function ID()
2244
+	{
2245
+		$model = $this->get_model();
2246
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2247
+		if ($model->has_primary_key_field()) {
2248
+			return $this->_fields[ $model->primary_key_name() ];
2249
+		}
2250
+		return $model->get_index_primary_key_string($this->_fields);
2251
+	}
2252
+
2253
+
2254
+	/**
2255
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2256
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2257
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2258
+	 *
2259
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2260
+	 * @param string $relationName                     eg 'Events','Question',etc.
2261
+	 *                                                 an attendee to a group, you also want to specify which role they
2262
+	 *                                                 will have in that group. So you would use this parameter to
2263
+	 *                                                 specify array('role-column-name'=>'role-id')
2264
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2265
+	 *                                                 allow you to further constrict the relation to being added.
2266
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2267
+	 *                                                 column on the JOIN table and currently only the HABTM models
2268
+	 *                                                 accept these additional conditions.  Also remember that if an
2269
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2270
+	 *                                                 NEW row is created in the join table.
2271
+	 * @param null   $cache_id
2272
+	 * @throws ReflectionException
2273
+	 * @throws InvalidArgumentException
2274
+	 * @throws InvalidInterfaceException
2275
+	 * @throws InvalidDataTypeException
2276
+	 * @throws EE_Error
2277
+	 * @return EE_Base_Class the object the relation was added to
2278
+	 */
2279
+	public function _add_relation_to(
2280
+		$otherObjectModelObjectOrID,
2281
+		$relationName,
2282
+		$extra_join_model_fields_n_values = array(),
2283
+		$cache_id = null
2284
+	) {
2285
+		$model = $this->get_model();
2286
+		// if this thing exists in the DB, save the relation to the DB
2287
+		if ($this->ID()) {
2288
+			$otherObject = $model->add_relationship_to(
2289
+				$this,
2290
+				$otherObjectModelObjectOrID,
2291
+				$relationName,
2292
+				$extra_join_model_fields_n_values
2293
+			);
2294
+			// clear cache so future get_many_related and get_first_related() return new results.
2295
+			$this->clear_cache($relationName, $otherObject, true);
2296
+			if ($otherObject instanceof EE_Base_Class) {
2297
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2298
+			}
2299
+		} else {
2300
+			// this thing doesn't exist in the DB,  so just cache it
2301
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2302
+				throw new EE_Error(
2303
+					sprintf(
2304
+						esc_html__(
2305
+							'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2306
+							'event_espresso'
2307
+						),
2308
+						$otherObjectModelObjectOrID,
2309
+						get_class($this)
2310
+					)
2311
+				);
2312
+			}
2313
+			$otherObject = $otherObjectModelObjectOrID;
2314
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2315
+		}
2316
+		if ($otherObject instanceof EE_Base_Class) {
2317
+			// fix the reciprocal relation too
2318
+			if ($otherObject->ID()) {
2319
+				// its saved so assumed relations exist in the DB, so we can just
2320
+				// clear the cache so future queries use the updated info in the DB
2321
+				$otherObject->clear_cache(
2322
+					$model->get_this_model_name(),
2323
+					null,
2324
+					true
2325
+				);
2326
+			} else {
2327
+				// it's not saved, so it caches relations like this
2328
+				$otherObject->cache($model->get_this_model_name(), $this);
2329
+			}
2330
+		}
2331
+		return $otherObject;
2332
+	}
2333
+
2334
+
2335
+	/**
2336
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2337
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2338
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2339
+	 * from the cache
2340
+	 *
2341
+	 * @param mixed  $otherObjectModelObjectOrID
2342
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2343
+	 *                to the DB yet
2344
+	 * @param string $relationName
2345
+	 * @param array  $where_query
2346
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2347
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2348
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2349
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2350
+	 *                deleted.
2351
+	 * @return EE_Base_Class the relation was removed from
2352
+	 * @throws ReflectionException
2353
+	 * @throws InvalidArgumentException
2354
+	 * @throws InvalidInterfaceException
2355
+	 * @throws InvalidDataTypeException
2356
+	 * @throws EE_Error
2357
+	 */
2358
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2359
+	{
2360
+		if ($this->ID()) {
2361
+			// if this exists in the DB, save the relation change to the DB too
2362
+			$otherObject = $this->get_model()->remove_relationship_to(
2363
+				$this,
2364
+				$otherObjectModelObjectOrID,
2365
+				$relationName,
2366
+				$where_query
2367
+			);
2368
+			$this->clear_cache(
2369
+				$relationName,
2370
+				$otherObject
2371
+			);
2372
+		} else {
2373
+			// this doesn't exist in the DB, just remove it from the cache
2374
+			$otherObject = $this->clear_cache(
2375
+				$relationName,
2376
+				$otherObjectModelObjectOrID
2377
+			);
2378
+		}
2379
+		if ($otherObject instanceof EE_Base_Class) {
2380
+			$otherObject->clear_cache(
2381
+				$this->get_model()->get_this_model_name(),
2382
+				$this
2383
+			);
2384
+		}
2385
+		return $otherObject;
2386
+	}
2387
+
2388
+
2389
+	/**
2390
+	 * Removes ALL the related things for the $relationName.
2391
+	 *
2392
+	 * @param string $relationName
2393
+	 * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2394
+	 * @return EE_Base_Class
2395
+	 * @throws ReflectionException
2396
+	 * @throws InvalidArgumentException
2397
+	 * @throws InvalidInterfaceException
2398
+	 * @throws InvalidDataTypeException
2399
+	 * @throws EE_Error
2400
+	 */
2401
+	public function _remove_relations($relationName, $where_query_params = array())
2402
+	{
2403
+		if ($this->ID()) {
2404
+			// if this exists in the DB, save the relation change to the DB too
2405
+			$otherObjects = $this->get_model()->remove_relations(
2406
+				$this,
2407
+				$relationName,
2408
+				$where_query_params
2409
+			);
2410
+			$this->clear_cache(
2411
+				$relationName,
2412
+				null,
2413
+				true
2414
+			);
2415
+		} else {
2416
+			// this doesn't exist in the DB, just remove it from the cache
2417
+			$otherObjects = $this->clear_cache(
2418
+				$relationName,
2419
+				null,
2420
+				true
2421
+			);
2422
+		}
2423
+		if (is_array($otherObjects)) {
2424
+			foreach ($otherObjects as $otherObject) {
2425
+				$otherObject->clear_cache(
2426
+					$this->get_model()->get_this_model_name(),
2427
+					$this
2428
+				);
2429
+			}
2430
+		}
2431
+		return $otherObjects;
2432
+	}
2433
+
2434
+
2435
+	/**
2436
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2437
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2438
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2439
+	 * because we want to get even deleted items etc.
2440
+	 *
2441
+	 * @param string $relationName key in the model's _model_relations array
2442
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2443
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2444
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2445
+	 *                             results if you want IDs
2446
+	 * @throws ReflectionException
2447
+	 * @throws InvalidArgumentException
2448
+	 * @throws InvalidInterfaceException
2449
+	 * @throws InvalidDataTypeException
2450
+	 * @throws EE_Error
2451
+	 */
2452
+	public function get_many_related($relationName, $query_params = array())
2453
+	{
2454
+		if ($this->ID()) {
2455
+			// this exists in the DB, so get the related things from either the cache or the DB
2456
+			// if there are query parameters, forget about caching the related model objects.
2457
+			if ($query_params) {
2458
+				$related_model_objects = $this->get_model()->get_all_related(
2459
+					$this,
2460
+					$relationName,
2461
+					$query_params
2462
+				);
2463
+			} else {
2464
+				// did we already cache the result of this query?
2465
+				$cached_results = $this->get_all_from_cache($relationName);
2466
+				if (! $cached_results) {
2467
+					$related_model_objects = $this->get_model()->get_all_related(
2468
+						$this,
2469
+						$relationName,
2470
+						$query_params
2471
+					);
2472
+					// if no query parameters were passed, then we got all the related model objects
2473
+					// for that relation. We can cache them then.
2474
+					foreach ($related_model_objects as $related_model_object) {
2475
+						$this->cache($relationName, $related_model_object);
2476
+					}
2477
+				} else {
2478
+					$related_model_objects = $cached_results;
2479
+				}
2480
+			}
2481
+		} else {
2482
+			// this doesn't exist in the DB, so just get the related things from the cache
2483
+			$related_model_objects = $this->get_all_from_cache($relationName);
2484
+		}
2485
+		return $related_model_objects;
2486
+	}
2487
+
2488
+
2489
+	/**
2490
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2491
+	 * unless otherwise specified in the $query_params
2492
+	 *
2493
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2494
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2495
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2496
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2497
+	 *                               that by the setting $distinct to TRUE;
2498
+	 * @return int
2499
+	 * @throws ReflectionException
2500
+	 * @throws InvalidArgumentException
2501
+	 * @throws InvalidInterfaceException
2502
+	 * @throws InvalidDataTypeException
2503
+	 * @throws EE_Error
2504
+	 */
2505
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2506
+	{
2507
+		return $this->get_model()->count_related(
2508
+			$this,
2509
+			$relation_name,
2510
+			$query_params,
2511
+			$field_to_count,
2512
+			$distinct
2513
+		);
2514
+	}
2515
+
2516
+
2517
+	/**
2518
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2519
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2520
+	 *
2521
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2522
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2523
+	 * @param string $field_to_sum  name of field to count by.
2524
+	 *                              By default, uses primary key
2525
+	 *                              (which doesn't make much sense, so you should probably change it)
2526
+	 * @return int
2527
+	 * @throws ReflectionException
2528
+	 * @throws InvalidArgumentException
2529
+	 * @throws InvalidInterfaceException
2530
+	 * @throws InvalidDataTypeException
2531
+	 * @throws EE_Error
2532
+	 */
2533
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2534
+	{
2535
+		return $this->get_model()->sum_related(
2536
+			$this,
2537
+			$relation_name,
2538
+			$query_params,
2539
+			$field_to_sum
2540
+		);
2541
+	}
2542
+
2543
+
2544
+	/**
2545
+	 * Gets the first (ie, one) related model object of the specified type.
2546
+	 *
2547
+	 * @param string $relationName key in the model's _model_relations array
2548
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2549
+	 * @return EE_Base_Class (not an array, a single object)
2550
+	 * @throws ReflectionException
2551
+	 * @throws InvalidArgumentException
2552
+	 * @throws InvalidInterfaceException
2553
+	 * @throws InvalidDataTypeException
2554
+	 * @throws EE_Error
2555
+	 */
2556
+	public function get_first_related($relationName, $query_params = array())
2557
+	{
2558
+		$model = $this->get_model();
2559
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2560
+			// if they've provided some query parameters, don't bother trying to cache the result
2561
+			// also make sure we're not caching the result of get_first_related
2562
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2563
+			if (
2564
+				$query_params
2565
+				|| ! $model->related_settings_for($relationName)
2566
+					 instanceof
2567
+					 EE_Belongs_To_Relation
2568
+			) {
2569
+				$related_model_object = $model->get_first_related(
2570
+					$this,
2571
+					$relationName,
2572
+					$query_params
2573
+				);
2574
+			} else {
2575
+				// first, check if we've already cached the result of this query
2576
+				$cached_result = $this->get_one_from_cache($relationName);
2577
+				if (! $cached_result) {
2578
+					$related_model_object = $model->get_first_related(
2579
+						$this,
2580
+						$relationName,
2581
+						$query_params
2582
+					);
2583
+					$this->cache($relationName, $related_model_object);
2584
+				} else {
2585
+					$related_model_object = $cached_result;
2586
+				}
2587
+			}
2588
+		} else {
2589
+			$related_model_object = null;
2590
+			// this doesn't exist in the Db,
2591
+			// but maybe the relation is of type belongs to, and so the related thing might
2592
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2593
+				$related_model_object = $model->get_first_related(
2594
+					$this,
2595
+					$relationName,
2596
+					$query_params
2597
+				);
2598
+			}
2599
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2600
+			// just get what's cached on this object
2601
+			if (! $related_model_object) {
2602
+				$related_model_object = $this->get_one_from_cache($relationName);
2603
+			}
2604
+		}
2605
+		return $related_model_object;
2606
+	}
2607
+
2608
+
2609
+	/**
2610
+	 * Does a delete on all related objects of type $relationName and removes
2611
+	 * the current model object's relation to them. If they can't be deleted (because
2612
+	 * of blocking related model objects) does nothing. If the related model objects are
2613
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2614
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2615
+	 *
2616
+	 * @param string $relationName
2617
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2618
+	 * @return int how many deleted
2619
+	 * @throws ReflectionException
2620
+	 * @throws InvalidArgumentException
2621
+	 * @throws InvalidInterfaceException
2622
+	 * @throws InvalidDataTypeException
2623
+	 * @throws EE_Error
2624
+	 */
2625
+	public function delete_related($relationName, $query_params = array())
2626
+	{
2627
+		if ($this->ID()) {
2628
+			$count = $this->get_model()->delete_related(
2629
+				$this,
2630
+				$relationName,
2631
+				$query_params
2632
+			);
2633
+		} else {
2634
+			$count = count($this->get_all_from_cache($relationName));
2635
+			$this->clear_cache($relationName, null, true);
2636
+		}
2637
+		return $count;
2638
+	}
2639
+
2640
+
2641
+	/**
2642
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2643
+	 * the current model object's relation to them. If they can't be deleted (because
2644
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2645
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2646
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2647
+	 *
2648
+	 * @param string $relationName
2649
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2650
+	 * @return int how many deleted (including those soft deleted)
2651
+	 * @throws ReflectionException
2652
+	 * @throws InvalidArgumentException
2653
+	 * @throws InvalidInterfaceException
2654
+	 * @throws InvalidDataTypeException
2655
+	 * @throws EE_Error
2656
+	 */
2657
+	public function delete_related_permanently($relationName, $query_params = array())
2658
+	{
2659
+		if ($this->ID()) {
2660
+			$count = $this->get_model()->delete_related_permanently(
2661
+				$this,
2662
+				$relationName,
2663
+				$query_params
2664
+			);
2665
+		} else {
2666
+			$count = count($this->get_all_from_cache($relationName));
2667
+		}
2668
+		$this->clear_cache($relationName, null, true);
2669
+		return $count;
2670
+	}
2671
+
2672
+
2673
+	/**
2674
+	 * is_set
2675
+	 * Just a simple utility function children can use for checking if property exists
2676
+	 *
2677
+	 * @access  public
2678
+	 * @param  string $field_name property to check
2679
+	 * @return bool                              TRUE if existing,FALSE if not.
2680
+	 */
2681
+	public function is_set($field_name)
2682
+	{
2683
+		return isset($this->_fields[ $field_name ]);
2684
+	}
2685
+
2686
+
2687
+	/**
2688
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2689
+	 * EE_Error exception if they don't
2690
+	 *
2691
+	 * @param  mixed (string|array) $properties properties to check
2692
+	 * @throws EE_Error
2693
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2694
+	 */
2695
+	protected function _property_exists($properties)
2696
+	{
2697
+		foreach ((array) $properties as $property_name) {
2698
+			// first make sure this property exists
2699
+			if (! $this->_fields[ $property_name ]) {
2700
+				throw new EE_Error(
2701
+					sprintf(
2702
+						esc_html__(
2703
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2704
+							'event_espresso'
2705
+						),
2706
+						$property_name
2707
+					)
2708
+				);
2709
+			}
2710
+		}
2711
+		return true;
2712
+	}
2713
+
2714
+
2715
+	/**
2716
+	 * This simply returns an array of model fields for this object
2717
+	 *
2718
+	 * @return array
2719
+	 * @throws ReflectionException
2720
+	 * @throws InvalidArgumentException
2721
+	 * @throws InvalidInterfaceException
2722
+	 * @throws InvalidDataTypeException
2723
+	 * @throws EE_Error
2724
+	 */
2725
+	public function model_field_array()
2726
+	{
2727
+		$fields = $this->get_model()->field_settings(false);
2728
+		$properties = array();
2729
+		// remove prepended underscore
2730
+		foreach ($fields as $field_name => $settings) {
2731
+			$properties[ $field_name ] = $this->get($field_name);
2732
+		}
2733
+		return $properties;
2734
+	}
2735
+
2736
+
2737
+	/**
2738
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2739
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2740
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2741
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2742
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2743
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2744
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2745
+	 * and accepts 2 arguments: the object on which the function was called,
2746
+	 * and an array of the original arguments passed to the function.
2747
+	 * Whatever their callback function returns will be returned by this function.
2748
+	 * Example: in functions.php (or in a plugin):
2749
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2750
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2751
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2752
+	 *          return $previousReturnValue.$returnString;
2753
+	 *      }
2754
+	 * require('EE_Answer.class.php');
2755
+	 * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2756
+	 *      ->my_callback('monkeys',100);
2757
+	 * // will output "you called my_callback! and passed args:monkeys,100"
2758
+	 *
2759
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2760
+	 * @param array  $args       array of original arguments passed to the function
2761
+	 * @throws EE_Error
2762
+	 * @return mixed whatever the plugin which calls add_filter decides
2763
+	 */
2764
+	public function __call($methodName, $args)
2765
+	{
2766
+		$className = get_class($this);
2767
+		$tagName = "FHEE__{$className}__{$methodName}";
2768
+		if (! has_filter($tagName)) {
2769
+			throw new EE_Error(
2770
+				sprintf(
2771
+					esc_html__(
2772
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2773
+						'event_espresso'
2774
+					),
2775
+					$methodName,
2776
+					$className,
2777
+					$tagName
2778
+				)
2779
+			);
2780
+		}
2781
+		return apply_filters($tagName, null, $this, $args);
2782
+	}
2783
+
2784
+
2785
+	/**
2786
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2787
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2788
+	 *
2789
+	 * @param string $meta_key
2790
+	 * @param mixed  $meta_value
2791
+	 * @param mixed  $previous_value
2792
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2793
+	 *                  NOTE: if the values haven't changed, returns 0
2794
+	 * @throws InvalidArgumentException
2795
+	 * @throws InvalidInterfaceException
2796
+	 * @throws InvalidDataTypeException
2797
+	 * @throws EE_Error
2798
+	 * @throws ReflectionException
2799
+	 */
2800
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2801
+	{
2802
+		$query_params = array(
2803
+			array(
2804
+				'EXM_key'  => $meta_key,
2805
+				'OBJ_ID'   => $this->ID(),
2806
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2807
+			),
2808
+		);
2809
+		if ($previous_value !== null) {
2810
+			$query_params[0]['EXM_value'] = $meta_value;
2811
+		}
2812
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2813
+		if (! $existing_rows_like_that) {
2814
+			return $this->add_extra_meta($meta_key, $meta_value);
2815
+		}
2816
+		foreach ($existing_rows_like_that as $existing_row) {
2817
+			$existing_row->save(array('EXM_value' => $meta_value));
2818
+		}
2819
+		return count($existing_rows_like_that);
2820
+	}
2821
+
2822
+
2823
+	/**
2824
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2825
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2826
+	 * extra meta row was entered, false if not
2827
+	 *
2828
+	 * @param string  $meta_key
2829
+	 * @param mixed   $meta_value
2830
+	 * @param boolean $unique
2831
+	 * @return boolean
2832
+	 * @throws InvalidArgumentException
2833
+	 * @throws InvalidInterfaceException
2834
+	 * @throws InvalidDataTypeException
2835
+	 * @throws EE_Error
2836
+	 * @throws ReflectionException
2837
+	 * @throws ReflectionException
2838
+	 */
2839
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2840
+	{
2841
+		if ($unique) {
2842
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2843
+				array(
2844
+					array(
2845
+						'EXM_key'  => $meta_key,
2846
+						'OBJ_ID'   => $this->ID(),
2847
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2848
+					),
2849
+				)
2850
+			);
2851
+			if ($existing_extra_meta) {
2852
+				return false;
2853
+			}
2854
+		}
2855
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2856
+			array(
2857
+				'EXM_key'   => $meta_key,
2858
+				'EXM_value' => $meta_value,
2859
+				'OBJ_ID'    => $this->ID(),
2860
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2861
+			)
2862
+		);
2863
+		$new_extra_meta->save();
2864
+		return true;
2865
+	}
2866
+
2867
+
2868
+	/**
2869
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2870
+	 * is specified, only deletes extra meta records with that value.
2871
+	 *
2872
+	 * @param string $meta_key
2873
+	 * @param mixed  $meta_value
2874
+	 * @return int number of extra meta rows deleted
2875
+	 * @throws InvalidArgumentException
2876
+	 * @throws InvalidInterfaceException
2877
+	 * @throws InvalidDataTypeException
2878
+	 * @throws EE_Error
2879
+	 * @throws ReflectionException
2880
+	 */
2881
+	public function delete_extra_meta($meta_key, $meta_value = null)
2882
+	{
2883
+		$query_params = array(
2884
+			array(
2885
+				'EXM_key'  => $meta_key,
2886
+				'OBJ_ID'   => $this->ID(),
2887
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2888
+			),
2889
+		);
2890
+		if ($meta_value !== null) {
2891
+			$query_params[0]['EXM_value'] = $meta_value;
2892
+		}
2893
+		return EEM_Extra_Meta::instance()->delete($query_params);
2894
+	}
2895
+
2896
+
2897
+	/**
2898
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2899
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2900
+	 * You can specify $default is case you haven't found the extra meta
2901
+	 *
2902
+	 * @param string  $meta_key
2903
+	 * @param boolean $single
2904
+	 * @param mixed   $default if we don't find anything, what should we return?
2905
+	 * @return mixed single value if $single; array if ! $single
2906
+	 * @throws ReflectionException
2907
+	 * @throws InvalidArgumentException
2908
+	 * @throws InvalidInterfaceException
2909
+	 * @throws InvalidDataTypeException
2910
+	 * @throws EE_Error
2911
+	 */
2912
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2913
+	{
2914
+		if ($single) {
2915
+			$result = $this->get_first_related(
2916
+				'Extra_Meta',
2917
+				array(array('EXM_key' => $meta_key))
2918
+			);
2919
+			if ($result instanceof EE_Extra_Meta) {
2920
+				return $result->value();
2921
+			}
2922
+		} else {
2923
+			$results = $this->get_many_related(
2924
+				'Extra_Meta',
2925
+				array(array('EXM_key' => $meta_key))
2926
+			);
2927
+			if ($results) {
2928
+				$values = array();
2929
+				foreach ($results as $result) {
2930
+					if ($result instanceof EE_Extra_Meta) {
2931
+						$values[ $result->ID() ] = $result->value();
2932
+					}
2933
+				}
2934
+				return $values;
2935
+			}
2936
+		}
2937
+		// if nothing discovered yet return default.
2938
+		return apply_filters(
2939
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2940
+			$default,
2941
+			$meta_key,
2942
+			$single,
2943
+			$this
2944
+		);
2945
+	}
2946
+
2947
+
2948
+	/**
2949
+	 * Returns a simple array of all the extra meta associated with this model object.
2950
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2951
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2952
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2953
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2954
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2955
+	 * finally the extra meta's value as each sub-value. (eg
2956
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2957
+	 *
2958
+	 * @param boolean $one_of_each_key
2959
+	 * @return array
2960
+	 * @throws ReflectionException
2961
+	 * @throws InvalidArgumentException
2962
+	 * @throws InvalidInterfaceException
2963
+	 * @throws InvalidDataTypeException
2964
+	 * @throws EE_Error
2965
+	 */
2966
+	public function all_extra_meta_array($one_of_each_key = true)
2967
+	{
2968
+		$return_array = array();
2969
+		if ($one_of_each_key) {
2970
+			$extra_meta_objs = $this->get_many_related(
2971
+				'Extra_Meta',
2972
+				array('group_by' => 'EXM_key')
2973
+			);
2974
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2975
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2976
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2977
+				}
2978
+			}
2979
+		} else {
2980
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2981
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2982
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2983
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2984
+						$return_array[ $extra_meta_obj->key() ] = array();
2985
+					}
2986
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2987
+				}
2988
+			}
2989
+		}
2990
+		return $return_array;
2991
+	}
2992
+
2993
+
2994
+	/**
2995
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2996
+	 *
2997
+	 * @return string
2998
+	 * @throws ReflectionException
2999
+	 * @throws InvalidArgumentException
3000
+	 * @throws InvalidInterfaceException
3001
+	 * @throws InvalidDataTypeException
3002
+	 * @throws EE_Error
3003
+	 */
3004
+	public function name()
3005
+	{
3006
+		// find a field that's not a text field
3007
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3008
+		if ($field_we_can_use) {
3009
+			return $this->get($field_we_can_use->get_name());
3010
+		}
3011
+		$first_few_properties = $this->model_field_array();
3012
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3013
+		$name_parts = array();
3014
+		foreach ($first_few_properties as $name => $value) {
3015
+			$name_parts[] = "$name:$value";
3016
+		}
3017
+		return implode(',', $name_parts);
3018
+	}
3019
+
3020
+
3021
+	/**
3022
+	 * in_entity_map
3023
+	 * Checks if this model object has been proven to already be in the entity map
3024
+	 *
3025
+	 * @return boolean
3026
+	 * @throws ReflectionException
3027
+	 * @throws InvalidArgumentException
3028
+	 * @throws InvalidInterfaceException
3029
+	 * @throws InvalidDataTypeException
3030
+	 * @throws EE_Error
3031
+	 */
3032
+	public function in_entity_map()
3033
+	{
3034
+		// well, if we looked, did we find it in the entity map?
3035
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3036
+	}
3037
+
3038
+
3039
+	/**
3040
+	 * refresh_from_db
3041
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3042
+	 *
3043
+	 * @throws ReflectionException
3044
+	 * @throws InvalidArgumentException
3045
+	 * @throws InvalidInterfaceException
3046
+	 * @throws InvalidDataTypeException
3047
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3048
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3049
+	 */
3050
+	public function refresh_from_db()
3051
+	{
3052
+		if ($this->ID() && $this->in_entity_map()) {
3053
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3054
+		} else {
3055
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3056
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3057
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3058
+			// absolutely nothing in it for this ID
3059
+			if (WP_DEBUG) {
3060
+				throw new EE_Error(
3061
+					sprintf(
3062
+						esc_html__(
3063
+							'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3064
+							'event_espresso'
3065
+						),
3066
+						$this->ID(),
3067
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3068
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3069
+					)
3070
+				);
3071
+			}
3072
+		}
3073
+	}
3074
+
3075
+
3076
+	/**
3077
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3078
+	 *
3079
+	 * @since 4.9.80.p
3080
+	 * @param EE_Model_Field_Base[] $fields
3081
+	 * @param string $new_value_sql
3082
+	 *      example: 'column_name=123',
3083
+	 *      or 'column_name=column_name+1',
3084
+	 *      or 'column_name= CASE
3085
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3086
+	 *          THEN `column_name` + 5
3087
+	 *          ELSE `column_name`
3088
+	 *      END'
3089
+	 *      Also updates $field on this model object with the latest value from the database.
3090
+	 * @return bool
3091
+	 * @throws EE_Error
3092
+	 * @throws InvalidArgumentException
3093
+	 * @throws InvalidDataTypeException
3094
+	 * @throws InvalidInterfaceException
3095
+	 * @throws ReflectionException
3096
+	 */
3097
+	protected function updateFieldsInDB($fields, $new_value_sql)
3098
+	{
3099
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3100
+		// if it wasn't even there to start off.
3101
+		if (! $this->ID()) {
3102
+			$this->save();
3103
+		}
3104
+		global $wpdb;
3105
+		if (empty($fields)) {
3106
+			throw new InvalidArgumentException(
3107
+				esc_html__(
3108
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3109
+					'event_espresso'
3110
+				)
3111
+			);
3112
+		}
3113
+		$first_field = reset($fields);
3114
+		$table_alias = $first_field->get_table_alias();
3115
+		foreach ($fields as $field) {
3116
+			if ($table_alias !== $field->get_table_alias()) {
3117
+				throw new InvalidArgumentException(
3118
+					sprintf(
3119
+						esc_html__(
3120
+							// @codingStandardsIgnoreStart
3121
+							'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3122
+							// @codingStandardsIgnoreEnd
3123
+							'event_espresso'
3124
+						),
3125
+						$table_alias,
3126
+						$field->get_table_alias()
3127
+					)
3128
+				);
3129
+			}
3130
+		}
3131
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3132
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3133
+		$table_pk_value = $this->ID();
3134
+		$table_name = $table_obj->get_table_name();
3135
+		if ($table_obj instanceof EE_Secondary_Table) {
3136
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3137
+		} else {
3138
+			$table_pk_field_name = $table_obj->get_pk_column();
3139
+		}
3140
+
3141
+		$query =
3142
+			"UPDATE `{$table_name}`
3143 3143
             SET "
3144
-            . $new_value_sql
3145
-            . $wpdb->prepare(
3146
-                "
3144
+			. $new_value_sql
3145
+			. $wpdb->prepare(
3146
+				"
3147 3147
             WHERE `{$table_pk_field_name}` = %d;",
3148
-                $table_pk_value
3149
-            );
3150
-        $result = $wpdb->query($query);
3151
-        foreach ($fields as $field) {
3152
-            // If it was successful, we'd like to know the new value.
3153
-            // If it failed, we'd also like to know the new value.
3154
-            $new_value = $this->get_model()->get_var(
3155
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3156
-                    $this->get_model()->get_index_primary_key_string(
3157
-                        $this->model_field_array()
3158
-                    ),
3159
-                    array(
3160
-                        'default_where_conditions' => 'minimum',
3161
-                    )
3162
-                ),
3163
-                $field->get_name()
3164
-            );
3165
-            $this->set_from_db(
3166
-                $field->get_name(),
3167
-                $new_value
3168
-            );
3169
-        }
3170
-        return (bool) $result;
3171
-    }
3172
-
3173
-
3174
-    /**
3175
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3176
-     * Does not allow negative values, however.
3177
-     *
3178
-     * @since 4.9.80.p
3179
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3180
-     *                                   (positive or negative). One important gotcha: all these values must be
3181
-     *                                   on the same table (eg don't pass in one field for the posts table and
3182
-     *                                   another for the event meta table.)
3183
-     * @return bool
3184
-     * @throws EE_Error
3185
-     * @throws InvalidArgumentException
3186
-     * @throws InvalidDataTypeException
3187
-     * @throws InvalidInterfaceException
3188
-     * @throws ReflectionException
3189
-     */
3190
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3191
-    {
3192
-        global $wpdb;
3193
-        if (empty($fields_n_quantities)) {
3194
-            // No fields to update? Well sure, we updated them to that value just fine.
3195
-            return true;
3196
-        }
3197
-        $fields = [];
3198
-        $set_sql_statements = [];
3199
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3200
-            $field = $this->get_model()->field_settings_for($field_name, true);
3201
-            $fields[] = $field;
3202
-            $column_name = $field->get_table_column();
3203
-
3204
-            $abs_qty = absint($quantity);
3205
-            if ($quantity > 0) {
3206
-                // don't let the value be negative as often these fields are unsigned
3207
-                $set_sql_statements[] = $wpdb->prepare(
3208
-                    "`{$column_name}` = `{$column_name}` + %d",
3209
-                    $abs_qty
3210
-                );
3211
-            } else {
3212
-                $set_sql_statements[] = $wpdb->prepare(
3213
-                    "`{$column_name}` = CASE
3148
+				$table_pk_value
3149
+			);
3150
+		$result = $wpdb->query($query);
3151
+		foreach ($fields as $field) {
3152
+			// If it was successful, we'd like to know the new value.
3153
+			// If it failed, we'd also like to know the new value.
3154
+			$new_value = $this->get_model()->get_var(
3155
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3156
+					$this->get_model()->get_index_primary_key_string(
3157
+						$this->model_field_array()
3158
+					),
3159
+					array(
3160
+						'default_where_conditions' => 'minimum',
3161
+					)
3162
+				),
3163
+				$field->get_name()
3164
+			);
3165
+			$this->set_from_db(
3166
+				$field->get_name(),
3167
+				$new_value
3168
+			);
3169
+		}
3170
+		return (bool) $result;
3171
+	}
3172
+
3173
+
3174
+	/**
3175
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3176
+	 * Does not allow negative values, however.
3177
+	 *
3178
+	 * @since 4.9.80.p
3179
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3180
+	 *                                   (positive or negative). One important gotcha: all these values must be
3181
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3182
+	 *                                   another for the event meta table.)
3183
+	 * @return bool
3184
+	 * @throws EE_Error
3185
+	 * @throws InvalidArgumentException
3186
+	 * @throws InvalidDataTypeException
3187
+	 * @throws InvalidInterfaceException
3188
+	 * @throws ReflectionException
3189
+	 */
3190
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3191
+	{
3192
+		global $wpdb;
3193
+		if (empty($fields_n_quantities)) {
3194
+			// No fields to update? Well sure, we updated them to that value just fine.
3195
+			return true;
3196
+		}
3197
+		$fields = [];
3198
+		$set_sql_statements = [];
3199
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3200
+			$field = $this->get_model()->field_settings_for($field_name, true);
3201
+			$fields[] = $field;
3202
+			$column_name = $field->get_table_column();
3203
+
3204
+			$abs_qty = absint($quantity);
3205
+			if ($quantity > 0) {
3206
+				// don't let the value be negative as often these fields are unsigned
3207
+				$set_sql_statements[] = $wpdb->prepare(
3208
+					"`{$column_name}` = `{$column_name}` + %d",
3209
+					$abs_qty
3210
+				);
3211
+			} else {
3212
+				$set_sql_statements[] = $wpdb->prepare(
3213
+					"`{$column_name}` = CASE
3214 3214
                        WHEN (`{$column_name}` >= %d)
3215 3215
                        THEN `{$column_name}` - %d
3216 3216
                        ELSE 0
3217 3217
                     END",
3218
-                    $abs_qty,
3219
-                    $abs_qty
3220
-                );
3221
-            }
3222
-        }
3223
-        return $this->updateFieldsInDB(
3224
-            $fields,
3225
-            implode(', ', $set_sql_statements)
3226
-        );
3227
-    }
3228
-
3229
-
3230
-    /**
3231
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3232
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3233
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3234
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3235
-     * Otherwise returns false.
3236
-     *
3237
-     * @since 4.9.80.p
3238
-     * @param string $field_name_to_bump
3239
-     * @param string $field_name_affecting_total
3240
-     * @param string $limit_field_name
3241
-     * @param int    $quantity
3242
-     * @return bool
3243
-     * @throws EE_Error
3244
-     * @throws InvalidArgumentException
3245
-     * @throws InvalidDataTypeException
3246
-     * @throws InvalidInterfaceException
3247
-     * @throws ReflectionException
3248
-     */
3249
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3250
-    {
3251
-        global $wpdb;
3252
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3253
-        $column_name = $field->get_table_column();
3254
-
3255
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3256
-        $column_affecting_total = $field_affecting_total->get_table_column();
3257
-
3258
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3259
-        $limiting_column = $limiting_field->get_table_column();
3260
-        return $this->updateFieldsInDB(
3261
-            [$field],
3262
-            $wpdb->prepare(
3263
-                "`{$column_name}` =
3218
+					$abs_qty,
3219
+					$abs_qty
3220
+				);
3221
+			}
3222
+		}
3223
+		return $this->updateFieldsInDB(
3224
+			$fields,
3225
+			implode(', ', $set_sql_statements)
3226
+		);
3227
+	}
3228
+
3229
+
3230
+	/**
3231
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3232
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3233
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3234
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3235
+	 * Otherwise returns false.
3236
+	 *
3237
+	 * @since 4.9.80.p
3238
+	 * @param string $field_name_to_bump
3239
+	 * @param string $field_name_affecting_total
3240
+	 * @param string $limit_field_name
3241
+	 * @param int    $quantity
3242
+	 * @return bool
3243
+	 * @throws EE_Error
3244
+	 * @throws InvalidArgumentException
3245
+	 * @throws InvalidDataTypeException
3246
+	 * @throws InvalidInterfaceException
3247
+	 * @throws ReflectionException
3248
+	 */
3249
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3250
+	{
3251
+		global $wpdb;
3252
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3253
+		$column_name = $field->get_table_column();
3254
+
3255
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3256
+		$column_affecting_total = $field_affecting_total->get_table_column();
3257
+
3258
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3259
+		$limiting_column = $limiting_field->get_table_column();
3260
+		return $this->updateFieldsInDB(
3261
+			[$field],
3262
+			$wpdb->prepare(
3263
+				"`{$column_name}` =
3264 3264
             CASE
3265 3265
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3266 3266
                THEN `{$column_name}` + %d
3267 3267
                ELSE `{$column_name}`
3268 3268
             END",
3269
-                $quantity,
3270
-                EE_INF_IN_DB,
3271
-                $quantity
3272
-            )
3273
-        );
3274
-    }
3275
-
3276
-
3277
-    /**
3278
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3279
-     * (probably a bad assumption they have made, oh well)
3280
-     *
3281
-     * @return string
3282
-     */
3283
-    public function __toString()
3284
-    {
3285
-        try {
3286
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3287
-        } catch (Exception $e) {
3288
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3289
-            return '';
3290
-        }
3291
-    }
3292
-
3293
-
3294
-    /**
3295
-     * Clear related model objects if they're already in the DB, because otherwise when we
3296
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3297
-     * This means if we have made changes to those related model objects, and want to unserialize
3298
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3299
-     * Instead, those related model objects should be directly serialized and stored.
3300
-     * Eg, the following won't work:
3301
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3302
-     * $att = $reg->attendee();
3303
-     * $att->set( 'ATT_fname', 'Dirk' );
3304
-     * update_option( 'my_option', serialize( $reg ) );
3305
-     * //END REQUEST
3306
-     * //START NEXT REQUEST
3307
-     * $reg = get_option( 'my_option' );
3308
-     * $reg->attendee()->save();
3309
-     * And would need to be replace with:
3310
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3311
-     * $att = $reg->attendee();
3312
-     * $att->set( 'ATT_fname', 'Dirk' );
3313
-     * update_option( 'my_option', serialize( $reg ) );
3314
-     * //END REQUEST
3315
-     * //START NEXT REQUEST
3316
-     * $att = get_option( 'my_option' );
3317
-     * $att->save();
3318
-     *
3319
-     * @return array
3320
-     * @throws ReflectionException
3321
-     * @throws InvalidArgumentException
3322
-     * @throws InvalidInterfaceException
3323
-     * @throws InvalidDataTypeException
3324
-     * @throws EE_Error
3325
-     */
3326
-    public function __sleep()
3327
-    {
3328
-        $model = $this->get_model();
3329
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3330
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3331
-                $classname = 'EE_' . $model->get_this_model_name();
3332
-                if (
3333
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3334
-                    && $this->get_one_from_cache($relation_name)->ID()
3335
-                ) {
3336
-                    $this->clear_cache(
3337
-                        $relation_name,
3338
-                        $this->get_one_from_cache($relation_name)->ID()
3339
-                    );
3340
-                }
3341
-            }
3342
-        }
3343
-        $this->_props_n_values_provided_in_constructor = array();
3344
-        $properties_to_serialize = get_object_vars($this);
3345
-        // don't serialize the model. It's big and that risks recursion
3346
-        unset($properties_to_serialize['_model']);
3347
-        return array_keys($properties_to_serialize);
3348
-    }
3349
-
3350
-
3351
-    /**
3352
-     * restore _props_n_values_provided_in_constructor
3353
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3354
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3355
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3356
-     */
3357
-    public function __wakeup()
3358
-    {
3359
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3360
-    }
3361
-
3362
-
3363
-    /**
3364
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3365
-     * distinct with the clone host instance are also cloned.
3366
-     */
3367
-    public function __clone()
3368
-    {
3369
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3370
-        foreach ($this->_fields as $field => $value) {
3371
-            if ($value instanceof DateTime) {
3372
-                $this->_fields[ $field ] = clone $value;
3373
-            }
3374
-        }
3375
-    }
3269
+				$quantity,
3270
+				EE_INF_IN_DB,
3271
+				$quantity
3272
+			)
3273
+		);
3274
+	}
3275
+
3276
+
3277
+	/**
3278
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3279
+	 * (probably a bad assumption they have made, oh well)
3280
+	 *
3281
+	 * @return string
3282
+	 */
3283
+	public function __toString()
3284
+	{
3285
+		try {
3286
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3287
+		} catch (Exception $e) {
3288
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3289
+			return '';
3290
+		}
3291
+	}
3292
+
3293
+
3294
+	/**
3295
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3296
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3297
+	 * This means if we have made changes to those related model objects, and want to unserialize
3298
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3299
+	 * Instead, those related model objects should be directly serialized and stored.
3300
+	 * Eg, the following won't work:
3301
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3302
+	 * $att = $reg->attendee();
3303
+	 * $att->set( 'ATT_fname', 'Dirk' );
3304
+	 * update_option( 'my_option', serialize( $reg ) );
3305
+	 * //END REQUEST
3306
+	 * //START NEXT REQUEST
3307
+	 * $reg = get_option( 'my_option' );
3308
+	 * $reg->attendee()->save();
3309
+	 * And would need to be replace with:
3310
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3311
+	 * $att = $reg->attendee();
3312
+	 * $att->set( 'ATT_fname', 'Dirk' );
3313
+	 * update_option( 'my_option', serialize( $reg ) );
3314
+	 * //END REQUEST
3315
+	 * //START NEXT REQUEST
3316
+	 * $att = get_option( 'my_option' );
3317
+	 * $att->save();
3318
+	 *
3319
+	 * @return array
3320
+	 * @throws ReflectionException
3321
+	 * @throws InvalidArgumentException
3322
+	 * @throws InvalidInterfaceException
3323
+	 * @throws InvalidDataTypeException
3324
+	 * @throws EE_Error
3325
+	 */
3326
+	public function __sleep()
3327
+	{
3328
+		$model = $this->get_model();
3329
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3330
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3331
+				$classname = 'EE_' . $model->get_this_model_name();
3332
+				if (
3333
+					$this->get_one_from_cache($relation_name) instanceof $classname
3334
+					&& $this->get_one_from_cache($relation_name)->ID()
3335
+				) {
3336
+					$this->clear_cache(
3337
+						$relation_name,
3338
+						$this->get_one_from_cache($relation_name)->ID()
3339
+					);
3340
+				}
3341
+			}
3342
+		}
3343
+		$this->_props_n_values_provided_in_constructor = array();
3344
+		$properties_to_serialize = get_object_vars($this);
3345
+		// don't serialize the model. It's big and that risks recursion
3346
+		unset($properties_to_serialize['_model']);
3347
+		return array_keys($properties_to_serialize);
3348
+	}
3349
+
3350
+
3351
+	/**
3352
+	 * restore _props_n_values_provided_in_constructor
3353
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3354
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3355
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3356
+	 */
3357
+	public function __wakeup()
3358
+	{
3359
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3360
+	}
3361
+
3362
+
3363
+	/**
3364
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3365
+	 * distinct with the clone host instance are also cloned.
3366
+	 */
3367
+	public function __clone()
3368
+	{
3369
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3370
+		foreach ($this->_fields as $field => $value) {
3371
+			if ($value instanceof DateTime) {
3372
+				$this->_fields[ $field ] = clone $value;
3373
+			}
3374
+		}
3375
+	}
3376 3376
 }
Please login to merge, or discard this patch.
core/data_migration_scripts/EE_Data_Migration_Script_Base.core.php 2 patches
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
     public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
136 136
     {
137 137
         $this->_migration_stages = (array) apply_filters(
138
-            'FHEE__' . get_class($this) . '__construct__migration_stages',
138
+            'FHEE__'.get_class($this).'__construct__migration_stages',
139 139
             $this->_migration_stages
140 140
         );
141 141
         foreach ($this->_migration_stages as $migration_stage) {
@@ -170,10 +170,10 @@  discard block
 block discarded – undo
170 170
     public function set_mapping($old_table, $old_pk, $new_table, $new_pk)
171 171
     {
172 172
         // make sure it has the needed keys
173
-        if (! isset($this->_mappings[ $old_table ]) || ! isset($this->_mappings[ $old_table ][ $new_table ])) {
174
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
173
+        if ( ! isset($this->_mappings[$old_table]) || ! isset($this->_mappings[$old_table][$new_table])) {
174
+            $this->_mappings[$old_table][$new_table] = $this->_get_mapping_option($old_table, $new_table);
175 175
         }
176
-        $this->_mappings[ $old_table ][ $new_table ][ $old_pk ] = $new_pk;
176
+        $this->_mappings[$old_table][$new_table][$old_pk] = $new_pk;
177 177
     }
178 178
 
179 179
 
@@ -189,14 +189,14 @@  discard block
 block discarded – undo
189 189
     public function get_mapping_new_pk($old_table, $old_pk, $new_table)
190 190
     {
191 191
         if (
192
-            ! isset($this->_mappings[ $old_table ]) ||
193
-            ! isset($this->_mappings[ $old_table ][ $new_table ])
192
+            ! isset($this->_mappings[$old_table]) ||
193
+            ! isset($this->_mappings[$old_table][$new_table])
194 194
         ) {
195 195
             // try fetching the option
196
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
196
+            $this->_mappings[$old_table][$new_table] = $this->_get_mapping_option($old_table, $new_table);
197 197
         }
198
-        return isset($this->_mappings[ $old_table ][ $new_table ][ $old_pk ])
199
-            ? $this->_mappings[ $old_table ][ $new_table ][ $old_pk ] : null;
198
+        return isset($this->_mappings[$old_table][$new_table][$old_pk])
199
+            ? $this->_mappings[$old_table][$new_table][$old_pk] : null;
200 200
     }
201 201
 
202 202
 
@@ -212,16 +212,16 @@  discard block
 block discarded – undo
212 212
     public function get_mapping_old_pk($old_table, $new_table, $new_pk)
213 213
     {
214 214
         if (
215
-            ! isset($this->_mappings[ $old_table ]) ||
216
-            ! isset($this->_mappings[ $old_table ][ $new_table ])
215
+            ! isset($this->_mappings[$old_table]) ||
216
+            ! isset($this->_mappings[$old_table][$new_table])
217 217
         ) {
218 218
             // try fetching the option
219
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
219
+            $this->_mappings[$old_table][$new_table] = $this->_get_mapping_option($old_table, $new_table);
220 220
         }
221
-        if (isset($this->_mappings[ $old_table ][ $new_table ])) {
222
-            $new_pk_to_old_pk = array_flip($this->_mappings[ $old_table ][ $new_table ]);
223
-            if (isset($new_pk_to_old_pk[ $new_pk ])) {
224
-                return $new_pk_to_old_pk[ $new_pk ];
221
+        if (isset($this->_mappings[$old_table][$new_table])) {
222
+            $new_pk_to_old_pk = array_flip($this->_mappings[$old_table][$new_table]);
223
+            if (isset($new_pk_to_old_pk[$new_pk])) {
224
+                return $new_pk_to_old_pk[$new_pk];
225 225
             }
226 226
         }
227 227
         return null;
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
         $new_table_name_sans_wp = str_replace($wpdb->prefix, "", $new_table_name);
272 272
         $migrates_to = EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
273 273
         return substr(
274
-            EE_Data_Migration_Manager::data_migration_script_mapping_option_prefix . $migrates_to ['slug'] . '_' . $migrates_to['version'] . '_' . $old_table_name_sans_wp . '_' . $new_table_name_sans_wp,
274
+            EE_Data_Migration_Manager::data_migration_script_mapping_option_prefix.$migrates_to ['slug'].'_'.$migrates_to['version'].'_'.$old_table_name_sans_wp.'_'.$new_table_name_sans_wp,
275 275
             0,
276 276
             64
277 277
         );
@@ -343,12 +343,12 @@  discard block
 block discarded – undo
343 343
                         $num_records_to_migrate_limit - $num_records_actually_migrated
344 344
                     );
345 345
                     $num_records_actually_migrated += $records_migrated_during_stage;
346
-                    $records_migrated_per_stage[ $stage->pretty_name() ] = $records_migrated_during_stage;
346
+                    $records_migrated_per_stage[$stage->pretty_name()] = $records_migrated_during_stage;
347 347
                 } catch (Exception $e) {
348 348
                     // yes if we catch an exception here, we consider that migration stage borked.
349 349
                     $stage->set_status(EE_Data_Migration_Manager::status_fatal_error);
350 350
                     $this->set_status(EE_Data_Migration_Manager::status_fatal_error);
351
-                    $stage->add_error($e->getMessage() . ". Stack-trace:" . $e->getTraceAsString());
351
+                    $stage->add_error($e->getMessage().". Stack-trace:".$e->getTraceAsString());
352 352
                     throw $e;
353 353
                 }
354 354
                 // check that the migration stage didn't mark itself as having a fatal error
@@ -421,8 +421,8 @@  discard block
 block discarded – undo
421 421
     private function _maybe_do_schema_changes($before = true)
422 422
     {
423 423
         // so this property will be either _schema_changes_after_migration_ran or _schema_changes_before_migration_ran
424
-        $property_name = '_schema_changes_' . ($before ? 'before' : 'after') . '_migration_ran';
425
-        if (! $this->{$property_name}) {
424
+        $property_name = '_schema_changes_'.($before ? 'before' : 'after').'_migration_ran';
425
+        if ( ! $this->{$property_name}) {
426 426
             try {
427 427
                 ob_start();
428 428
                 if ($before) {
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
         try {
660 660
             EEH_Activation::create_table($table_name, $table_definition_sql, $engine_string, $drop_pre_existing_tables);
661 661
         } catch (EE_Error $e) {
662
-            $message = $e->getMessage() . '<br>Stack Trace:' . $e->getTraceAsString();
662
+            $message = $e->getMessage().'<br>Stack Trace:'.$e->getTraceAsString();
663 663
             $this->add_error($message);
664 664
             $this->_feedback_message .= $message;
665 665
         }
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
     public function get_errors()
706 706
     {
707 707
         $all_errors = $this->_errors;
708
-        if (! is_array($all_errors)) {
708
+        if ( ! is_array($all_errors)) {
709 709
             $all_errors = array();
710 710
         }
711 711
         foreach ($this->stages() as $stage) {
@@ -739,7 +739,7 @@  discard block
 block discarded – undo
739 739
      */
740 740
     protected function stages()
741 741
     {
742
-        $stages = apply_filters('FHEE__' . get_class($this) . '__stages', $this->_migration_stages);
742
+        $stages = apply_filters('FHEE__'.get_class($this).'__stages', $this->_migration_stages);
743 743
         ksort($stages);
744 744
         return $stages;
745 745
     }
@@ -768,7 +768,7 @@  discard block
 block discarded – undo
768 768
         $properties = parent::properties_as_array();
769 769
         $properties['_migration_stages'] = array();
770 770
         foreach ($this->_migration_stages as $migration_stage_priority => $migration_stage_class) {
771
-            $properties['_migration_stages'][ $migration_stage_priority ] = $migration_stage_class->properties_as_array(
771
+            $properties['_migration_stages'][$migration_stage_priority] = $migration_stage_class->properties_as_array(
772 772
             );
773 773
         }
774 774
         unset($properties['_mappings']);
Please login to merge, or discard this patch.
Indentation   +890 added lines, -890 removed lines patch added patch discarded remove patch
@@ -14,894 +14,894 @@
 block discarded – undo
14 14
  */
15 15
 abstract class EE_Data_Migration_Script_Base extends EE_Data_Migration_Class_Base
16 16
 {
17
-    /**
18
-     * Set by client code to indicate this DMS is being ran as part of a proper migration,
19
-     * instead of being used to merely setup (or verify) the database structure.
20
-     * Defaults to TRUE, so client code that's NOT using this DMS as part of a proper migration
21
-     * should call EE_Data_Migration_Script_Base::set_migrating( FALSE )
22
-     *
23
-     * @var boolean
24
-     */
25
-    protected $_migrating = true;
26
-
27
-    /**
28
-     * numerically-indexed array where each value is EE_Data_Migration_Script_Stage object
29
-     *
30
-     * @var EE_Data_Migration_Script_Stage[] $migration_functions
31
-     */
32
-    protected $_migration_stages = array();
33
-
34
-    /**
35
-     * Indicates we've already ran the schema changes that needed to happen BEFORE the data migration
36
-     *
37
-     * @var boolean
38
-     */
39
-    protected $_schema_changes_before_migration_ran = null;
40
-
41
-    /**
42
-     * Indicates we've already ran the schema changes that needed to happen AFTER the data migration
43
-     *
44
-     * @var boolean
45
-     */
46
-    protected $_schema_changes_after_migration_ran = null;
47
-
48
-    /**
49
-     * String which describes what's currently happening in this migration
50
-     *
51
-     * @var string
52
-     */
53
-    protected $_feedback_message;
54
-
55
-    /**
56
-     * Indicates the script's priority. Like wp's add_action and add_filter, lower numbers
57
-     * correspond to earlier execution
58
-     *
59
-     * @var int
60
-     */
61
-    protected $_priority = 5;
62
-
63
-    /**
64
-     * Multi-dimensional array that defines the mapping from OLD table Primary Keys
65
-     * to NEW table Primary Keys.
66
-     * Top-level array keys are OLD table names (minus the "wp_" part),
67
-     * 2nd-level array keys are NEW table names (again, minus the "wp_" part),
68
-     * 3rd-level array keys are the OLD table primary keys
69
-     * and 3rd-level array values are the NEW table primary keys
70
-     *
71
-     * @var array
72
-     */
73
-    protected $_mappings = array();
74
-
75
-    /**
76
-     * @var EE_Data_Migration_Script_Base
77
-     */
78
-    protected $previous_dms;
79
-
80
-
81
-    /**
82
-     * Returns whether or not this data migration script can operate on the given version of the database.
83
-     * Eg, if this migration script can migrate from 3.1.26 or higher (but not anything after 4.0.0), and
84
-     * it's passed a string like '3.1.38B', it should return true.
85
-     * If this DMS is to migrate data from an EE3 addon, you will probably want to use
86
-     * EventEspresso\core\services\database\TableAnalysis::tableExists() to check for old EE3 tables, and
87
-     * EE_Data_Migration_Manager::get_migration_ran() to check that core was already
88
-     * migrated from EE3 to EE4 (ie, this DMS probably relies on some migration data generated
89
-     * during the Core 4.1.0 DMS. If core didn't run that DMS, you probably don't want
90
-     * to run this DMS).
91
-     * If this DMS migrates data from a previous version of this EE4 addon, just
92
-     * comparing $current_database_state_of[ $this->slug() ] will probably suffice.
93
-     * If this DMS should never migrate data, because it's only used to define the initial
94
-     * database state, just return FALSE (and core's activation process will take care
95
-     * of calling its schema_changes_before_migration() and
96
-     * schema_changes_after_migration() for you. )
97
-     *
98
-     * @param array $current_database_state_of keys are EE plugin slugs (eg 'Core', 'Calendar', 'Mailchimp', etc)
99
-     * @return boolean
100
-     */
101
-    abstract public function can_migrate_from_version($current_database_state_of);
102
-
103
-
104
-    /**
105
-     * Performs database schema changes that need to occur BEFORE the data is migrated.
106
-     * Eg, if we were going to change user passwords from plaintext to encoded versions
107
-     * during this migration, this would probably add a new column called something like
108
-     * "encoded_password".
109
-     *
110
-     * @return boolean of success
111
-     */
112
-    abstract public function schema_changes_before_migration();
113
-
114
-
115
-    /**
116
-     * Performs the database schema changes that need to occur AFTER the data has been migrated.
117
-     * Usually this will mean we'll be removing old columns. Eg, if we were changing passwords
118
-     * from plaintext to encoded versions, and we had added a column called "encoded_password",
119
-     * this function would probably remove the old column "password" (which still holds the plaintext password)
120
-     * and possibly rename "encoded_password" to "password"
121
-     *
122
-     * @return boolean of success
123
-     */
124
-    abstract public function schema_changes_after_migration();
125
-
126
-
127
-    /**
128
-     * All children of this must call parent::__construct()
129
-     * at the end of their constructor or suffer the consequences!
130
-     *
131
-     * @param TableManager  $table_manager
132
-     * @param TableAnalysis $table_analysis
133
-     */
134
-    public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
135
-    {
136
-        $this->_migration_stages = (array) apply_filters(
137
-            'FHEE__' . get_class($this) . '__construct__migration_stages',
138
-            $this->_migration_stages
139
-        );
140
-        foreach ($this->_migration_stages as $migration_stage) {
141
-            if ($migration_stage instanceof EE_Data_Migration_Script_Stage) {
142
-                $migration_stage->_construct_finalize($this);
143
-            }
144
-        }
145
-        parent::__construct($table_manager, $table_analysis);
146
-    }
147
-
148
-
149
-    /**
150
-     * Place to add hooks and filters for tweaking the migrations page, in order
151
-     * to customize it
152
-     */
153
-    public function migration_page_hooks()
154
-    {
155
-        // by default none are added because we normally like the default look of the migration page
156
-    }
157
-
158
-
159
-    /**
160
-     * Sets the mapping from old table primary keys to new table primary keys.
161
-     * This mapping is automatically persisted as a property on the migration
162
-     *
163
-     * @param string     $old_table with wpdb prefix (wp_). Eg: wp_events_detail
164
-     * @param int|string $old_pk    old primary key. Eg events_detail.id's value
165
-     * @param string     $new_table with wpdb prefix (wp_). Eg: wp_posts
166
-     * @param int|string $new_pk    eg posts.ID
167
-     * @return void
168
-     */
169
-    public function set_mapping($old_table, $old_pk, $new_table, $new_pk)
170
-    {
171
-        // make sure it has the needed keys
172
-        if (! isset($this->_mappings[ $old_table ]) || ! isset($this->_mappings[ $old_table ][ $new_table ])) {
173
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
174
-        }
175
-        $this->_mappings[ $old_table ][ $new_table ][ $old_pk ] = $new_pk;
176
-    }
177
-
178
-
179
-    /**
180
-     * Gets the new primary key, if provided with the OLD table and the primary key
181
-     * of an item in the old table, and the new table
182
-     *
183
-     * @param string     $old_table with wpdb prefix (wp_). Eg: wp_events_detail
184
-     * @param int|string $old_pk    old primary key. Eg events_detail.id's value
185
-     * @param string     $new_table with wpdb prefix (wp_). Eg: wp_posts
186
-     * @return mixed the primary key on the new table
187
-     */
188
-    public function get_mapping_new_pk($old_table, $old_pk, $new_table)
189
-    {
190
-        if (
191
-            ! isset($this->_mappings[ $old_table ]) ||
192
-            ! isset($this->_mappings[ $old_table ][ $new_table ])
193
-        ) {
194
-            // try fetching the option
195
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
196
-        }
197
-        return isset($this->_mappings[ $old_table ][ $new_table ][ $old_pk ])
198
-            ? $this->_mappings[ $old_table ][ $new_table ][ $old_pk ] : null;
199
-    }
200
-
201
-
202
-    /**
203
-     * Gets the old primary key, if provided with the OLD table,
204
-     * and the new table and the primary key of an item in the new table
205
-     *
206
-     * @param string $old_table with wpdb prefix (wp_). Eg: wp_events_detail
207
-     * @param string $new_table with wpdb prefix (wp_). Eg: wp_posts
208
-     * @param mixed  $new_pk
209
-     * @return mixed
210
-     */
211
-    public function get_mapping_old_pk($old_table, $new_table, $new_pk)
212
-    {
213
-        if (
214
-            ! isset($this->_mappings[ $old_table ]) ||
215
-            ! isset($this->_mappings[ $old_table ][ $new_table ])
216
-        ) {
217
-            // try fetching the option
218
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
219
-        }
220
-        if (isset($this->_mappings[ $old_table ][ $new_table ])) {
221
-            $new_pk_to_old_pk = array_flip($this->_mappings[ $old_table ][ $new_table ]);
222
-            if (isset($new_pk_to_old_pk[ $new_pk ])) {
223
-                return $new_pk_to_old_pk[ $new_pk ];
224
-            }
225
-        }
226
-        return null;
227
-    }
228
-
229
-
230
-    /**
231
-     * Gets the mapping array option specified by the table names
232
-     *
233
-     * @param string $old_table_name
234
-     * @param string $new_table_name
235
-     * @return array
236
-     */
237
-    protected function _get_mapping_option($old_table_name, $new_table_name)
238
-    {
239
-        $option = get_option($this->_get_mapping_option_name($old_table_name, $new_table_name), array());
240
-        return $option;
241
-    }
242
-
243
-
244
-    /**
245
-     * Updates the mapping option specified by the table names with the array provided
246
-     *
247
-     * @param string $old_table_name
248
-     * @param string $new_table_name
249
-     * @param array  $mapping_array
250
-     * @return boolean success of updating option
251
-     */
252
-    protected function _set_mapping_option($old_table_name, $new_table_name, $mapping_array)
253
-    {
254
-        $success = update_option($this->_get_mapping_option_name($old_table_name, $new_table_name), $mapping_array, false);
255
-        return $success;
256
-    }
257
-
258
-
259
-    /**
260
-     * Gets the option name for this script to map from $old_table_name to $new_table_name
261
-     *
262
-     * @param string $old_table_name
263
-     * @param string $new_table_name
264
-     * @return string
265
-     */
266
-    protected function _get_mapping_option_name($old_table_name, $new_table_name)
267
-    {
268
-        global $wpdb;
269
-        $old_table_name_sans_wp = str_replace($wpdb->prefix, "", $old_table_name);
270
-        $new_table_name_sans_wp = str_replace($wpdb->prefix, "", $new_table_name);
271
-        $migrates_to = EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
272
-        return substr(
273
-            EE_Data_Migration_Manager::data_migration_script_mapping_option_prefix . $migrates_to ['slug'] . '_' . $migrates_to['version'] . '_' . $old_table_name_sans_wp . '_' . $new_table_name_sans_wp,
274
-            0,
275
-            64
276
-        );
277
-    }
278
-
279
-
280
-    /**
281
-     * Counts all the records that will be migrated during this data migration.
282
-     * For example, if we were changing old user passwords from plaintext to encoded versions,
283
-     * this would be a count of all users who have passwords. If we were going to also split
284
-     * attendee records into transactions, registrations, and attendee records, this would include
285
-     * the count of all attendees currently in existence in the DB (ie, users + attendees).
286
-     * If you can't determine how many records there are to migrate, just provide a guess: this
287
-     * number will only be used in calculating the percent complete. If you estimate there to be
288
-     * 100 records to migrate, and it turns out there's 120, we'll just show the migration as being at
289
-     * 99% until the function "migration_step" returns EE_Data_Migration_Script_Base::status_complete.
290
-     *
291
-     * @return int
292
-     */
293
-    protected function _count_records_to_migrate()
294
-    {
295
-        $count = 0;
296
-        foreach ($this->stages() as $stage) {
297
-            $count += $stage->count_records_to_migrate();
298
-        }
299
-        return $count;
300
-    }
301
-
302
-
303
-    /**
304
-     * Returns the number of records updated so far. Usually this is easiest to do
305
-     * by just setting a transient and updating it after each migration_step
306
-     *
307
-     * @return int
308
-     */
309
-    public function count_records_migrated()
310
-    {
311
-        $count = 0;
312
-        foreach ($this->stages() as $stage) {
313
-            $count += $stage->count_records_migrated();
314
-        }
315
-        $this->_records_migrated = $count;
316
-        return $count;
317
-    }
318
-
319
-
320
-    /**
321
-     * @param int $num_records_to_migrate_limit
322
-     * @return int
323
-     * @throws EE_Error
324
-     * @throws Exception
325
-     */
326
-    public function migration_step($num_records_to_migrate_limit)
327
-    {
328
-        // reset the feedback message
329
-        $this->_feedback_message = '';
330
-        // if we haven't yet done the 1st schema changes, do them now. buffer any output
331
-        $this->_maybe_do_schema_changes(true);
332
-
333
-        $num_records_actually_migrated = 0;
334
-        $records_migrated_per_stage = array();
335
-        // setup the 'stage' variable, which should hold the last run stage of the migration  (or none at all if nothing runs)
336
-        $stage = null;
337
-        // get the next stage that isn't complete
338
-        foreach ($this->stages() as $stage) {
339
-            if ($stage->get_status() == EE_Data_Migration_Manager::status_continue) {
340
-                try {
341
-                    $records_migrated_during_stage = $stage->migration_step(
342
-                        $num_records_to_migrate_limit - $num_records_actually_migrated
343
-                    );
344
-                    $num_records_actually_migrated += $records_migrated_during_stage;
345
-                    $records_migrated_per_stage[ $stage->pretty_name() ] = $records_migrated_during_stage;
346
-                } catch (Exception $e) {
347
-                    // yes if we catch an exception here, we consider that migration stage borked.
348
-                    $stage->set_status(EE_Data_Migration_Manager::status_fatal_error);
349
-                    $this->set_status(EE_Data_Migration_Manager::status_fatal_error);
350
-                    $stage->add_error($e->getMessage() . ". Stack-trace:" . $e->getTraceAsString());
351
-                    throw $e;
352
-                }
353
-                // check that the migration stage didn't mark itself as having a fatal error
354
-                if ($stage->is_broken()) {
355
-                    $this->set_broken();
356
-                    throw new EE_Error($stage->get_last_error());
357
-                }
358
-            }
359
-            // once we've migrated all the number we intended to (possibly from different stages), stop migrating
360
-            // or if we had a fatal error
361
-            // or if the current script stopped early- its not done, but it's done all it thinks we should do on this step
362
-            if (
363
-                $num_records_actually_migrated >= $num_records_to_migrate_limit
364
-                || $stage->is_broken()
365
-                || $stage->has_more_to_do()
366
-            ) {
367
-                break;
368
-            }
369
-        }
370
-        // check if we're all done this data migration...
371
-        // which is indicated by being done early AND the last stage claims to be done
372
-        if ($stage == null) {
373
-            // this migration script apparently has NO stages... which is super weird, but whatever
374
-            $this->set_completed();
375
-            $this->_maybe_do_schema_changes(false);
376
-        } elseif ($num_records_actually_migrated < $num_records_to_migrate_limit && ! $stage->has_more_to_do()) {
377
-            // apparently we're done, because we couldn't migrate the number we intended to
378
-            $this->set_completed();
379
-            $this->_update_feedback_message(array_reverse($records_migrated_per_stage));
380
-            // do schema changes for after the migration now
381
-            // first double-check we haven't already done this
382
-            $this->_maybe_do_schema_changes(false);
383
-        } else {
384
-            // update feedback message, keeping in mind that we show them with the most recent at the top
385
-            $this->_update_feedback_message(array_reverse($records_migrated_per_stage));
386
-        }
387
-        return $num_records_actually_migrated;
388
-    }
389
-
390
-
391
-    /**
392
-     * Updates the feedback message according to what was done during this migration stage.
393
-     *
394
-     * @param array $records_migrated_per_stage KEYS are pretty names for each stage; values are the count of records
395
-     *                                          migrated from that stage
396
-     * @return void
397
-     */
398
-    private function _update_feedback_message($records_migrated_per_stage)
399
-    {
400
-        $feedback_message_array = array();
401
-        foreach ($records_migrated_per_stage as $migration_stage_name => $num_records_migrated) {
402
-            $feedback_message_array[] = sprintf(
403
-                esc_html__("Migrated %d records successfully during %s", "event_espresso"),
404
-                $num_records_migrated,
405
-                $migration_stage_name
406
-            );
407
-        }
408
-        $this->_feedback_message .= implode("<br>", $feedback_message_array);
409
-    }
410
-
411
-
412
-    /**
413
-     * Calls either schema_changes_before_migration() (if $before==true) or schema_changes_after_migration
414
-     * (if $before==false). Buffers their outputs and stores them on the class.
415
-     *
416
-     * @param boolean $before
417
-     * @throws Exception
418
-     * @return void
419
-     */
420
-    private function _maybe_do_schema_changes($before = true)
421
-    {
422
-        // so this property will be either _schema_changes_after_migration_ran or _schema_changes_before_migration_ran
423
-        $property_name = '_schema_changes_' . ($before ? 'before' : 'after') . '_migration_ran';
424
-        if (! $this->{$property_name}) {
425
-            try {
426
-                ob_start();
427
-                if ($before) {
428
-                    $this->schema_changes_before_migration();
429
-                } else {
430
-                    $this->schema_changes_after_migration();
431
-                }
432
-                $output = ob_get_contents();
433
-                ob_end_clean();
434
-            } catch (Exception $e) {
435
-                $this->set_status(EE_Data_Migration_Manager::status_fatal_error);
436
-                throw $e;
437
-            }
438
-            // record that we've done these schema changes
439
-            $this->{$property_name} = true;
440
-            // if there were any warnings etc, record them as non-fatal errors
441
-            if ($output) {
442
-                // there were some warnings
443
-                $this->_errors[] = $output;
444
-            }
445
-        }
446
-    }
447
-
448
-
449
-    /**
450
-     * Wrapper for EEH_Activation::create_table. However, takes into account the request type when
451
-     * deciding what to pass for its 4th arg, $drop_pre_existing_tables. Using this function, instead
452
-     * of _table_should_exist_previously, indicates that this table should be new to the EE version being migrated to
453
-     * or
454
-     * activated currently. If this is a brand new activation or a migration, and we're indicating this table should
455
-     * not
456
-     * previously exist, then we want to set $drop_pre_existing_tables to TRUE (ie, we shouldn't discover that this
457
-     * table exists in the DB in EEH_Activation::create_table- if it DOES exist, something's wrong and the old table
458
-     * should be nuked.
459
-     *
460
-     * Just for a bit of context, the migration script's db_schema_changes_* methods
461
-     * are called basically in 3 cases: on brand new activation of EE4 (ie no previous version of EE existed and the
462
-     * plugin is being activated and we want to add all the brand new tables), upon reactivation of EE4 (it was
463
-     * deactivated and then reactivated, in which case we want to just verify the DB structure is ok) that table should
464
-     * be dropped), and during a migration when we're moving the DB to the state of the migration script
465
-     *
466
-     * @param string $table_name
467
-     * @param string $table_definition_sql
468
-     * @param string $engine_string
469
-     */
470
-    protected function _table_is_new_in_this_version(
471
-        $table_name,
472
-        $table_definition_sql,
473
-        $engine_string = 'ENGINE=InnoDB '
474
-    ) {
475
-        $this->_create_table_and_catch_errors(
476
-            $table_name,
477
-            $table_definition_sql,
478
-            $engine_string,
479
-            $this->_pre_existing_table_should_be_dropped(true)
480
-        );
481
-    }
482
-
483
-    /**
484
-     * Like _table_is_new_in_this_version and _table_should_exist_previously, this function verifies the given table
485
-     * exists. But we understand that this table has CHANGED in this version since the previous version. So it's not
486
-     * completely new, but it's different. So we need to treat it like a new table in terms of verifying it's schema is
487
-     * correct on activations, migrations, upgrades; but if it exists when it shouldn't, we need to be as lenient as
488
-     * _table_should_exist_previously.
489
-     * 8656]{Assumes only this plugin could have added this table (ie, if its a new activation of this plugin, the
490
-     * table shouldn't exist).
491
-     *
492
-     * @param string $table_name
493
-     * @param string $table_definition_sql
494
-     * @param string $engine_string
495
-     */
496
-    protected function _table_is_changed_in_this_version(
497
-        $table_name,
498
-        $table_definition_sql,
499
-        $engine_string = 'ENGINE=MyISAM'
500
-    ) {
501
-        $this->_create_table_and_catch_errors(
502
-            $table_name,
503
-            $table_definition_sql,
504
-            $engine_string,
505
-            $this->_pre_existing_table_should_be_dropped(false)
506
-        );
507
-    }
508
-
509
-
510
-    /**
511
-     * _old_table_exists
512
-     * returns TRUE if the requested table exists in the current database
513
-     *
514
-     * @param string $table_name
515
-     * @return boolean
516
-     */
517
-    protected function _old_table_exists($table_name)
518
-    {
519
-        return $this->_get_table_analysis()->tableExists($table_name);
520
-    }
521
-
522
-
523
-    /**
524
-     * _delete_table_if_empty
525
-     * returns TRUE if the requested table was empty and successfully empty
526
-     *
527
-     * @param string $table_name
528
-     * @return boolean
529
-     */
530
-    protected function _delete_table_if_empty($table_name)
531
-    {
532
-        return EEH_Activation::delete_db_table_if_empty($table_name);
533
-    }
534
-
535
-
536
-    /**
537
-     * It is preferred to use _table_has_not_changed_since_previous or _table_is_changed_in_this_version
538
-     * as these are significantly more efficient or explicit.
539
-     * Please see description of _table_is_new_in_this_version. This function will only set
540
-     * EEH_Activation::create_table's $drop_pre_existing_tables to TRUE if it's a brand
541
-     * new activation. ie, a more accurate name for this method would be "_table_added_previously_by_this_plugin"
542
-     * because the table will be cleared out if this is a new activation (ie, if its a new activation, it actually
543
-     * should exist previously). Otherwise, we'll always set $drop_pre_existing_tables to FALSE because the table
544
-     * should have existed. Note, if the table is being MODIFIED in this version being activated or migrated to, then
545
-     * you want _table_is_changed_in_this_version NOT this one. We don't check this table's structure during migrations
546
-     * because apparently it hasn't changed since the previous one, right?
547
-     *
548
-     * @param string $table_name
549
-     * @param string $table_definition_sql
550
-     * @param string $engine_string
551
-     */
552
-    protected function _table_should_exist_previously(
553
-        $table_name,
554
-        $table_definition_sql,
555
-        $engine_string = 'ENGINE=MyISAM'
556
-    ) {
557
-        $this->_create_table_and_catch_errors(
558
-            $table_name,
559
-            $table_definition_sql,
560
-            $engine_string,
561
-            $this->_pre_existing_table_should_be_dropped(false)
562
-        );
563
-    }
564
-
565
-    /**
566
-     * Exactly the same as _table_should_exist_previously(), except if this migration script is currently doing
567
-     * a migration, we skip checking this table's structure in the database and just assume it's correct.
568
-     * So this is useful only to improve efficiency when doing migrations (not a big deal for single site installs,
569
-     * but important for multisite where migrations can take a very long time otherwise).
570
-     * If the table is known to have changed since previous version, use _table_is_changed_in_this_version().
571
-     * Assumes only this plugin could have added this table (ie, if its a new activation of this plugin, the table
572
-     * shouldn't exist).
573
-     *
574
-     * @param string $table_name
575
-     * @param string $table_definition_sql
576
-     * @param string $engine_string
577
-     */
578
-    protected function _table_has_not_changed_since_previous(
579
-        $table_name,
580
-        $table_definition_sql,
581
-        $engine_string = 'ENGINE=MyISAM'
582
-    ) {
583
-        if ($this->_currently_migrating()) {
584
-            // if we're doing a migration, and this table apparently already exists, then we don't need do anything right?
585
-            return;
586
-        }
587
-        $this->_create_table_and_catch_errors(
588
-            $table_name,
589
-            $table_definition_sql,
590
-            $engine_string,
591
-            $this->_pre_existing_table_should_be_dropped(false)
592
-        );
593
-    }
594
-
595
-    /**
596
-     * Returns whether or not this migration script is being used as part of an actual migration
597
-     *
598
-     * @return boolean
599
-     */
600
-    protected function _currently_migrating()
601
-    {
602
-        // we want to know if we are currently performing a migration. We could just believe what was set on the _migrating property, but let's double-check (ie the script should apply and we should be in MM)
603
-        return $this->_migrating &&
604
-               $this->can_migrate_from_version(
605
-                   EE_Data_Migration_Manager::instance()->ensure_current_database_state_is_set()
606
-               ) &&
607
-               EE_Maintenance_Mode::instance()->real_level() == EE_Maintenance_Mode::level_2_complete_maintenance;
608
-    }
609
-
610
-    /**
611
-     * Determines if a table should be dropped, based on whether it's reported to be new in $table_is_new,
612
-     * and the plugin's request type.
613
-     * Assumes only this plugin could have added the table (ie, if its a new activation of this plugin, the table
614
-     * shouldn't exist no matter what).
615
-     *
616
-     * @param boolean $table_is_new
617
-     * @return boolean
618
-     */
619
-    protected function _pre_existing_table_should_be_dropped($table_is_new)
620
-    {
621
-        if ($table_is_new) {
622
-            if (
623
-                $this->_get_req_type_for_plugin_corresponding_to_this_dms() == EE_System::req_type_new_activation
624
-                || $this->_currently_migrating()
625
-            ) {
626
-                return true;
627
-            } else {
628
-                return false;
629
-            }
630
-        } else {
631
-            if (
632
-                in_array(
633
-                    $this->_get_req_type_for_plugin_corresponding_to_this_dms(),
634
-                    array(EE_System::req_type_new_activation)
635
-                )
636
-            ) {
637
-                return true;
638
-            } else {
639
-                return false;
640
-            }
641
-        }
642
-    }
643
-
644
-    /**
645
-     * Just wraps EEH_Activation::create_table, but catches any errors it may throw and adds them as errors on the DMS
646
-     *
647
-     * @param string  $table_name
648
-     * @param string  $table_definition_sql
649
-     * @param string  $engine_string
650
-     * @param boolean $drop_pre_existing_tables
651
-     */
652
-    private function _create_table_and_catch_errors(
653
-        $table_name,
654
-        $table_definition_sql,
655
-        $engine_string = 'ENGINE=MyISAM',
656
-        $drop_pre_existing_tables = false
657
-    ) {
658
-        try {
659
-            EEH_Activation::create_table($table_name, $table_definition_sql, $engine_string, $drop_pre_existing_tables);
660
-        } catch (EE_Error $e) {
661
-            $message = $e->getMessage() . '<br>Stack Trace:' . $e->getTraceAsString();
662
-            $this->add_error($message);
663
-            $this->_feedback_message .= $message;
664
-        }
665
-    }
666
-
667
-
668
-    /**
669
-     * Gets the request type for the plugin (core or addon) that corresponds to this DMS
670
-     *
671
-     * @return int one of EE_System::_req_type_* constants
672
-     * @throws EE_Error
673
-     */
674
-    private function _get_req_type_for_plugin_corresponding_to_this_dms()
675
-    {
676
-        if ($this->slug() == 'Core') {
677
-            return EE_System::instance()->detect_req_type();
678
-        } else {// it must be for an addon
679
-            $addon_name = $this->slug();
680
-            if (EE_Registry::instance()->get_addon_by_name($addon_name)) {
681
-                return EE_Registry::instance()->get_addon_by_name($addon_name)->detect_req_type();
682
-            } else {
683
-                throw new EE_Error(
684
-                    sprintf(
685
-                        esc_html__(
686
-                            "The DMS slug '%s' should correspond to the addon's name, which should also be '%s', but no such addon was registered. These are the registered addons' names: %s",
687
-                            "event_espresso"
688
-                        ),
689
-                        $this->slug(),
690
-                        $addon_name,
691
-                        implode(",", array_keys(EE_Registry::instance()->get_addons_by_name()))
692
-                    )
693
-                );
694
-            }
695
-        }
696
-    }
697
-
698
-
699
-    /**
700
-     * returns an array of strings describing errors by all the script's stages
701
-     *
702
-     * @return array
703
-     */
704
-    public function get_errors()
705
-    {
706
-        $all_errors = $this->_errors;
707
-        if (! is_array($all_errors)) {
708
-            $all_errors = array();
709
-        }
710
-        foreach ($this->stages() as $stage) {
711
-            $all_errors = array_merge($stage->get_errors(), $all_errors);
712
-        }
713
-        return $all_errors;
714
-    }
715
-
716
-
717
-    /**
718
-     * Indicates whether or not this migration script should continue
719
-     *
720
-     * @return boolean
721
-     */
722
-    public function can_continue()
723
-    {
724
-        return in_array(
725
-            $this->get_status(),
726
-            EE_Data_Migration_Manager::instance()->stati_that_indicate_to_continue_single_migration_script
727
-        );
728
-    }
729
-
730
-
731
-    /**
732
-     * Gets all the data migration stages associated with this script. Note:
733
-     * addons can filter this list to add their own stages, and because the list is
734
-     * numerically-indexed, they can insert their stage wherever they like and it will
735
-     * get ordered by the indexes
736
-     *
737
-     * @return EE_Data_Migration_Script_Stage[]
738
-     */
739
-    protected function stages()
740
-    {
741
-        $stages = apply_filters('FHEE__' . get_class($this) . '__stages', $this->_migration_stages);
742
-        ksort($stages);
743
-        return $stages;
744
-    }
745
-
746
-
747
-    /**
748
-     * Gets a string which should describe what's going on currently with this migration, which
749
-     * can be displayed to the user
750
-     *
751
-     * @return string
752
-     */
753
-    public function get_feedback_message()
754
-    {
755
-        return $this->_feedback_message;
756
-    }
757
-
758
-
759
-    /**
760
-     * A lot like "__sleep()" magic method in purpose, this is meant for persisting this class'
761
-     * properties to the DB. However, we don't want to use __sleep() because its quite
762
-     * possible that this class is defined when it goes to sleep, but NOT available when it
763
-     * awakes (eg, this class is part of an addon that is deactivated at some point).
764
-     */
765
-    public function properties_as_array()
766
-    {
767
-        $properties = parent::properties_as_array();
768
-        $properties['_migration_stages'] = array();
769
-        foreach ($this->_migration_stages as $migration_stage_priority => $migration_stage_class) {
770
-            $properties['_migration_stages'][ $migration_stage_priority ] = $migration_stage_class->properties_as_array(
771
-            );
772
-        }
773
-        unset($properties['_mappings']);
774
-        unset($properties['previous_dms']);
775
-
776
-        foreach ($this->_mappings as $old_table_name => $mapping_to_new_table) {
777
-            foreach ($mapping_to_new_table as $new_table_name => $mapping) {
778
-                $this->_set_mapping_option($old_table_name, $new_table_name, $mapping);
779
-            }
780
-        }
781
-        return $properties;
782
-    }
783
-
784
-
785
-    /**
786
-     * Sets all of the properties of this script stage to match what's in the array, which is assumed
787
-     * to have been made from the properties_as_array() function.
788
-     *
789
-     * @param array $array_of_properties like what's produced from properties_as_array() method
790
-     * @return void
791
-     */
792
-    public function instantiate_from_array_of_properties($array_of_properties)
793
-    {
794
-        $stages_properties_arrays = $array_of_properties['_migration_stages'];
795
-        unset($array_of_properties['_migration_stages']);
796
-        unset($array_of_properties['class']);
797
-        foreach ($array_of_properties as $property_name => $property_value) {
798
-            $this->{$property_name} = $property_value;
799
-        }
800
-        // _migration_stages are already instantiated, but have only default data
801
-        foreach ($this->_migration_stages as $stage) {
802
-            $stage_data = $this->_find_migration_stage_data_with_classname(
803
-                get_class($stage),
804
-                $stages_properties_arrays
805
-            );
806
-            // SO, if we found the stage data that was saved, use it. Otherwise, I guess the stage is new? (maybe added by
807
-            // an addon? Unlikely... not sure why it wouldn't exist, but if it doesn't just treat it like it was never started yet)
808
-            if ($stage_data) {
809
-                $stage->instantiate_from_array_of_properties($stage_data);
810
-            }
811
-        }
812
-    }
813
-
814
-
815
-    /**
816
-     * Gets the migration data from the array $migration_stage_data_arrays (which is an array of arrays, each of which
817
-     * is pretty well identical to EE_Data_Migration_Stage objects except all their properties are array indexes)
818
-     * for the given classname
819
-     *
820
-     * @param string $classname
821
-     * @param array  $migration_stage_data_arrays
822
-     * @return null
823
-     */
824
-    private function _find_migration_stage_data_with_classname($classname, $migration_stage_data_arrays)
825
-    {
826
-        foreach ($migration_stage_data_arrays as $migration_stage_data_array) {
827
-            if (isset($migration_stage_data_array['class']) && $migration_stage_data_array['class'] == $classname) {
828
-                return $migration_stage_data_array;
829
-            }
830
-        }
831
-        return null;
832
-    }
833
-
834
-
835
-    /**
836
-     * Returns the version that this script migrates to, based on the script's name.
837
-     * Cannot be overwritten because lots of code needs to know which version a script
838
-     * migrates to knowing only its name.
839
-     *
840
-     * @return array where the first key is the plugin's slug, the 2nd is the version of that plugin
841
-     * that will be updated to. Eg array('Core','4.1.0')
842
-     */
843
-    final public function migrates_to_version()
844
-    {
845
-        return EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
846
-    }
847
-
848
-
849
-    /**
850
-     * Gets this addon's slug as it would appear in the current_db_state wp option,
851
-     * and if this migration script is for an addon, it SHOULD match the addon's slug
852
-     * (and also the addon's classname, minus the 'EE_' prefix.). Eg, 'Calendar' for the EE_Calendar addon.
853
-     * Or 'Core' for core (non-addon).
854
-     *
855
-     * @return string
856
-     */
857
-    public function slug()
858
-    {
859
-        $migrates_to_version_info = $this->migrates_to_version();
860
-        // the slug is the first part of the array
861
-        return $migrates_to_version_info['slug'];
862
-    }
863
-
864
-
865
-    /**
866
-     * Returns the script's priority relative to DMSs from other addons. However, when
867
-     * two DMSs from the same addon/core apply, this is ignored (and instead the version that
868
-     * the script migrates to is used to determine which to run first). The default is 5, but all core DMSs
869
-     * normally have priority 10. (So if you want a DMS "A" to run before DMS "B", both of which are from addons,
870
-     * and both of which CAN run at the same time (ie, "B" doesn't depend on "A" to set
871
-     * the database up so it can run), then you can set "A" to priority 3 or something.
872
-     *
873
-     * @return int
874
-     */
875
-    public function priority()
876
-    {
877
-        return $this->_priority;
878
-    }
879
-
880
-
881
-    /**
882
-     * Sets whether or not this DMS is being ran as part of a migration, instead of
883
-     * just being used to setup (or verify) the current database structure matches
884
-     * what the latest DMS indicates it should be
885
-     *
886
-     * @param boolean $migrating
887
-     * @return void
888
-     */
889
-    public function set_migrating($migrating = true)
890
-    {
891
-        $this->_migrating = $migrating;
892
-    }
893
-
894
-    /**
895
-     * Marks that we think this migration class can continue to migrate
896
-     */
897
-    public function reattempt()
898
-    {
899
-        parent::reattempt();
900
-        // also, we want to reattempt any stages that were marked as borked
901
-        foreach ($this->stages() as $stage) {
902
-            if ($stage->is_broken()) {
903
-                $stage->reattempt();
904
-            }
905
-        }
906
-    }
17
+	/**
18
+	 * Set by client code to indicate this DMS is being ran as part of a proper migration,
19
+	 * instead of being used to merely setup (or verify) the database structure.
20
+	 * Defaults to TRUE, so client code that's NOT using this DMS as part of a proper migration
21
+	 * should call EE_Data_Migration_Script_Base::set_migrating( FALSE )
22
+	 *
23
+	 * @var boolean
24
+	 */
25
+	protected $_migrating = true;
26
+
27
+	/**
28
+	 * numerically-indexed array where each value is EE_Data_Migration_Script_Stage object
29
+	 *
30
+	 * @var EE_Data_Migration_Script_Stage[] $migration_functions
31
+	 */
32
+	protected $_migration_stages = array();
33
+
34
+	/**
35
+	 * Indicates we've already ran the schema changes that needed to happen BEFORE the data migration
36
+	 *
37
+	 * @var boolean
38
+	 */
39
+	protected $_schema_changes_before_migration_ran = null;
40
+
41
+	/**
42
+	 * Indicates we've already ran the schema changes that needed to happen AFTER the data migration
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	protected $_schema_changes_after_migration_ran = null;
47
+
48
+	/**
49
+	 * String which describes what's currently happening in this migration
50
+	 *
51
+	 * @var string
52
+	 */
53
+	protected $_feedback_message;
54
+
55
+	/**
56
+	 * Indicates the script's priority. Like wp's add_action and add_filter, lower numbers
57
+	 * correspond to earlier execution
58
+	 *
59
+	 * @var int
60
+	 */
61
+	protected $_priority = 5;
62
+
63
+	/**
64
+	 * Multi-dimensional array that defines the mapping from OLD table Primary Keys
65
+	 * to NEW table Primary Keys.
66
+	 * Top-level array keys are OLD table names (minus the "wp_" part),
67
+	 * 2nd-level array keys are NEW table names (again, minus the "wp_" part),
68
+	 * 3rd-level array keys are the OLD table primary keys
69
+	 * and 3rd-level array values are the NEW table primary keys
70
+	 *
71
+	 * @var array
72
+	 */
73
+	protected $_mappings = array();
74
+
75
+	/**
76
+	 * @var EE_Data_Migration_Script_Base
77
+	 */
78
+	protected $previous_dms;
79
+
80
+
81
+	/**
82
+	 * Returns whether or not this data migration script can operate on the given version of the database.
83
+	 * Eg, if this migration script can migrate from 3.1.26 or higher (but not anything after 4.0.0), and
84
+	 * it's passed a string like '3.1.38B', it should return true.
85
+	 * If this DMS is to migrate data from an EE3 addon, you will probably want to use
86
+	 * EventEspresso\core\services\database\TableAnalysis::tableExists() to check for old EE3 tables, and
87
+	 * EE_Data_Migration_Manager::get_migration_ran() to check that core was already
88
+	 * migrated from EE3 to EE4 (ie, this DMS probably relies on some migration data generated
89
+	 * during the Core 4.1.0 DMS. If core didn't run that DMS, you probably don't want
90
+	 * to run this DMS).
91
+	 * If this DMS migrates data from a previous version of this EE4 addon, just
92
+	 * comparing $current_database_state_of[ $this->slug() ] will probably suffice.
93
+	 * If this DMS should never migrate data, because it's only used to define the initial
94
+	 * database state, just return FALSE (and core's activation process will take care
95
+	 * of calling its schema_changes_before_migration() and
96
+	 * schema_changes_after_migration() for you. )
97
+	 *
98
+	 * @param array $current_database_state_of keys are EE plugin slugs (eg 'Core', 'Calendar', 'Mailchimp', etc)
99
+	 * @return boolean
100
+	 */
101
+	abstract public function can_migrate_from_version($current_database_state_of);
102
+
103
+
104
+	/**
105
+	 * Performs database schema changes that need to occur BEFORE the data is migrated.
106
+	 * Eg, if we were going to change user passwords from plaintext to encoded versions
107
+	 * during this migration, this would probably add a new column called something like
108
+	 * "encoded_password".
109
+	 *
110
+	 * @return boolean of success
111
+	 */
112
+	abstract public function schema_changes_before_migration();
113
+
114
+
115
+	/**
116
+	 * Performs the database schema changes that need to occur AFTER the data has been migrated.
117
+	 * Usually this will mean we'll be removing old columns. Eg, if we were changing passwords
118
+	 * from plaintext to encoded versions, and we had added a column called "encoded_password",
119
+	 * this function would probably remove the old column "password" (which still holds the plaintext password)
120
+	 * and possibly rename "encoded_password" to "password"
121
+	 *
122
+	 * @return boolean of success
123
+	 */
124
+	abstract public function schema_changes_after_migration();
125
+
126
+
127
+	/**
128
+	 * All children of this must call parent::__construct()
129
+	 * at the end of their constructor or suffer the consequences!
130
+	 *
131
+	 * @param TableManager  $table_manager
132
+	 * @param TableAnalysis $table_analysis
133
+	 */
134
+	public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
135
+	{
136
+		$this->_migration_stages = (array) apply_filters(
137
+			'FHEE__' . get_class($this) . '__construct__migration_stages',
138
+			$this->_migration_stages
139
+		);
140
+		foreach ($this->_migration_stages as $migration_stage) {
141
+			if ($migration_stage instanceof EE_Data_Migration_Script_Stage) {
142
+				$migration_stage->_construct_finalize($this);
143
+			}
144
+		}
145
+		parent::__construct($table_manager, $table_analysis);
146
+	}
147
+
148
+
149
+	/**
150
+	 * Place to add hooks and filters for tweaking the migrations page, in order
151
+	 * to customize it
152
+	 */
153
+	public function migration_page_hooks()
154
+	{
155
+		// by default none are added because we normally like the default look of the migration page
156
+	}
157
+
158
+
159
+	/**
160
+	 * Sets the mapping from old table primary keys to new table primary keys.
161
+	 * This mapping is automatically persisted as a property on the migration
162
+	 *
163
+	 * @param string     $old_table with wpdb prefix (wp_). Eg: wp_events_detail
164
+	 * @param int|string $old_pk    old primary key. Eg events_detail.id's value
165
+	 * @param string     $new_table with wpdb prefix (wp_). Eg: wp_posts
166
+	 * @param int|string $new_pk    eg posts.ID
167
+	 * @return void
168
+	 */
169
+	public function set_mapping($old_table, $old_pk, $new_table, $new_pk)
170
+	{
171
+		// make sure it has the needed keys
172
+		if (! isset($this->_mappings[ $old_table ]) || ! isset($this->_mappings[ $old_table ][ $new_table ])) {
173
+			$this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
174
+		}
175
+		$this->_mappings[ $old_table ][ $new_table ][ $old_pk ] = $new_pk;
176
+	}
177
+
178
+
179
+	/**
180
+	 * Gets the new primary key, if provided with the OLD table and the primary key
181
+	 * of an item in the old table, and the new table
182
+	 *
183
+	 * @param string     $old_table with wpdb prefix (wp_). Eg: wp_events_detail
184
+	 * @param int|string $old_pk    old primary key. Eg events_detail.id's value
185
+	 * @param string     $new_table with wpdb prefix (wp_). Eg: wp_posts
186
+	 * @return mixed the primary key on the new table
187
+	 */
188
+	public function get_mapping_new_pk($old_table, $old_pk, $new_table)
189
+	{
190
+		if (
191
+			! isset($this->_mappings[ $old_table ]) ||
192
+			! isset($this->_mappings[ $old_table ][ $new_table ])
193
+		) {
194
+			// try fetching the option
195
+			$this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
196
+		}
197
+		return isset($this->_mappings[ $old_table ][ $new_table ][ $old_pk ])
198
+			? $this->_mappings[ $old_table ][ $new_table ][ $old_pk ] : null;
199
+	}
200
+
201
+
202
+	/**
203
+	 * Gets the old primary key, if provided with the OLD table,
204
+	 * and the new table and the primary key of an item in the new table
205
+	 *
206
+	 * @param string $old_table with wpdb prefix (wp_). Eg: wp_events_detail
207
+	 * @param string $new_table with wpdb prefix (wp_). Eg: wp_posts
208
+	 * @param mixed  $new_pk
209
+	 * @return mixed
210
+	 */
211
+	public function get_mapping_old_pk($old_table, $new_table, $new_pk)
212
+	{
213
+		if (
214
+			! isset($this->_mappings[ $old_table ]) ||
215
+			! isset($this->_mappings[ $old_table ][ $new_table ])
216
+		) {
217
+			// try fetching the option
218
+			$this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
219
+		}
220
+		if (isset($this->_mappings[ $old_table ][ $new_table ])) {
221
+			$new_pk_to_old_pk = array_flip($this->_mappings[ $old_table ][ $new_table ]);
222
+			if (isset($new_pk_to_old_pk[ $new_pk ])) {
223
+				return $new_pk_to_old_pk[ $new_pk ];
224
+			}
225
+		}
226
+		return null;
227
+	}
228
+
229
+
230
+	/**
231
+	 * Gets the mapping array option specified by the table names
232
+	 *
233
+	 * @param string $old_table_name
234
+	 * @param string $new_table_name
235
+	 * @return array
236
+	 */
237
+	protected function _get_mapping_option($old_table_name, $new_table_name)
238
+	{
239
+		$option = get_option($this->_get_mapping_option_name($old_table_name, $new_table_name), array());
240
+		return $option;
241
+	}
242
+
243
+
244
+	/**
245
+	 * Updates the mapping option specified by the table names with the array provided
246
+	 *
247
+	 * @param string $old_table_name
248
+	 * @param string $new_table_name
249
+	 * @param array  $mapping_array
250
+	 * @return boolean success of updating option
251
+	 */
252
+	protected function _set_mapping_option($old_table_name, $new_table_name, $mapping_array)
253
+	{
254
+		$success = update_option($this->_get_mapping_option_name($old_table_name, $new_table_name), $mapping_array, false);
255
+		return $success;
256
+	}
257
+
258
+
259
+	/**
260
+	 * Gets the option name for this script to map from $old_table_name to $new_table_name
261
+	 *
262
+	 * @param string $old_table_name
263
+	 * @param string $new_table_name
264
+	 * @return string
265
+	 */
266
+	protected function _get_mapping_option_name($old_table_name, $new_table_name)
267
+	{
268
+		global $wpdb;
269
+		$old_table_name_sans_wp = str_replace($wpdb->prefix, "", $old_table_name);
270
+		$new_table_name_sans_wp = str_replace($wpdb->prefix, "", $new_table_name);
271
+		$migrates_to = EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
272
+		return substr(
273
+			EE_Data_Migration_Manager::data_migration_script_mapping_option_prefix . $migrates_to ['slug'] . '_' . $migrates_to['version'] . '_' . $old_table_name_sans_wp . '_' . $new_table_name_sans_wp,
274
+			0,
275
+			64
276
+		);
277
+	}
278
+
279
+
280
+	/**
281
+	 * Counts all the records that will be migrated during this data migration.
282
+	 * For example, if we were changing old user passwords from plaintext to encoded versions,
283
+	 * this would be a count of all users who have passwords. If we were going to also split
284
+	 * attendee records into transactions, registrations, and attendee records, this would include
285
+	 * the count of all attendees currently in existence in the DB (ie, users + attendees).
286
+	 * If you can't determine how many records there are to migrate, just provide a guess: this
287
+	 * number will only be used in calculating the percent complete. If you estimate there to be
288
+	 * 100 records to migrate, and it turns out there's 120, we'll just show the migration as being at
289
+	 * 99% until the function "migration_step" returns EE_Data_Migration_Script_Base::status_complete.
290
+	 *
291
+	 * @return int
292
+	 */
293
+	protected function _count_records_to_migrate()
294
+	{
295
+		$count = 0;
296
+		foreach ($this->stages() as $stage) {
297
+			$count += $stage->count_records_to_migrate();
298
+		}
299
+		return $count;
300
+	}
301
+
302
+
303
+	/**
304
+	 * Returns the number of records updated so far. Usually this is easiest to do
305
+	 * by just setting a transient and updating it after each migration_step
306
+	 *
307
+	 * @return int
308
+	 */
309
+	public function count_records_migrated()
310
+	{
311
+		$count = 0;
312
+		foreach ($this->stages() as $stage) {
313
+			$count += $stage->count_records_migrated();
314
+		}
315
+		$this->_records_migrated = $count;
316
+		return $count;
317
+	}
318
+
319
+
320
+	/**
321
+	 * @param int $num_records_to_migrate_limit
322
+	 * @return int
323
+	 * @throws EE_Error
324
+	 * @throws Exception
325
+	 */
326
+	public function migration_step($num_records_to_migrate_limit)
327
+	{
328
+		// reset the feedback message
329
+		$this->_feedback_message = '';
330
+		// if we haven't yet done the 1st schema changes, do them now. buffer any output
331
+		$this->_maybe_do_schema_changes(true);
332
+
333
+		$num_records_actually_migrated = 0;
334
+		$records_migrated_per_stage = array();
335
+		// setup the 'stage' variable, which should hold the last run stage of the migration  (or none at all if nothing runs)
336
+		$stage = null;
337
+		// get the next stage that isn't complete
338
+		foreach ($this->stages() as $stage) {
339
+			if ($stage->get_status() == EE_Data_Migration_Manager::status_continue) {
340
+				try {
341
+					$records_migrated_during_stage = $stage->migration_step(
342
+						$num_records_to_migrate_limit - $num_records_actually_migrated
343
+					);
344
+					$num_records_actually_migrated += $records_migrated_during_stage;
345
+					$records_migrated_per_stage[ $stage->pretty_name() ] = $records_migrated_during_stage;
346
+				} catch (Exception $e) {
347
+					// yes if we catch an exception here, we consider that migration stage borked.
348
+					$stage->set_status(EE_Data_Migration_Manager::status_fatal_error);
349
+					$this->set_status(EE_Data_Migration_Manager::status_fatal_error);
350
+					$stage->add_error($e->getMessage() . ". Stack-trace:" . $e->getTraceAsString());
351
+					throw $e;
352
+				}
353
+				// check that the migration stage didn't mark itself as having a fatal error
354
+				if ($stage->is_broken()) {
355
+					$this->set_broken();
356
+					throw new EE_Error($stage->get_last_error());
357
+				}
358
+			}
359
+			// once we've migrated all the number we intended to (possibly from different stages), stop migrating
360
+			// or if we had a fatal error
361
+			// or if the current script stopped early- its not done, but it's done all it thinks we should do on this step
362
+			if (
363
+				$num_records_actually_migrated >= $num_records_to_migrate_limit
364
+				|| $stage->is_broken()
365
+				|| $stage->has_more_to_do()
366
+			) {
367
+				break;
368
+			}
369
+		}
370
+		// check if we're all done this data migration...
371
+		// which is indicated by being done early AND the last stage claims to be done
372
+		if ($stage == null) {
373
+			// this migration script apparently has NO stages... which is super weird, but whatever
374
+			$this->set_completed();
375
+			$this->_maybe_do_schema_changes(false);
376
+		} elseif ($num_records_actually_migrated < $num_records_to_migrate_limit && ! $stage->has_more_to_do()) {
377
+			// apparently we're done, because we couldn't migrate the number we intended to
378
+			$this->set_completed();
379
+			$this->_update_feedback_message(array_reverse($records_migrated_per_stage));
380
+			// do schema changes for after the migration now
381
+			// first double-check we haven't already done this
382
+			$this->_maybe_do_schema_changes(false);
383
+		} else {
384
+			// update feedback message, keeping in mind that we show them with the most recent at the top
385
+			$this->_update_feedback_message(array_reverse($records_migrated_per_stage));
386
+		}
387
+		return $num_records_actually_migrated;
388
+	}
389
+
390
+
391
+	/**
392
+	 * Updates the feedback message according to what was done during this migration stage.
393
+	 *
394
+	 * @param array $records_migrated_per_stage KEYS are pretty names for each stage; values are the count of records
395
+	 *                                          migrated from that stage
396
+	 * @return void
397
+	 */
398
+	private function _update_feedback_message($records_migrated_per_stage)
399
+	{
400
+		$feedback_message_array = array();
401
+		foreach ($records_migrated_per_stage as $migration_stage_name => $num_records_migrated) {
402
+			$feedback_message_array[] = sprintf(
403
+				esc_html__("Migrated %d records successfully during %s", "event_espresso"),
404
+				$num_records_migrated,
405
+				$migration_stage_name
406
+			);
407
+		}
408
+		$this->_feedback_message .= implode("<br>", $feedback_message_array);
409
+	}
410
+
411
+
412
+	/**
413
+	 * Calls either schema_changes_before_migration() (if $before==true) or schema_changes_after_migration
414
+	 * (if $before==false). Buffers their outputs and stores them on the class.
415
+	 *
416
+	 * @param boolean $before
417
+	 * @throws Exception
418
+	 * @return void
419
+	 */
420
+	private function _maybe_do_schema_changes($before = true)
421
+	{
422
+		// so this property will be either _schema_changes_after_migration_ran or _schema_changes_before_migration_ran
423
+		$property_name = '_schema_changes_' . ($before ? 'before' : 'after') . '_migration_ran';
424
+		if (! $this->{$property_name}) {
425
+			try {
426
+				ob_start();
427
+				if ($before) {
428
+					$this->schema_changes_before_migration();
429
+				} else {
430
+					$this->schema_changes_after_migration();
431
+				}
432
+				$output = ob_get_contents();
433
+				ob_end_clean();
434
+			} catch (Exception $e) {
435
+				$this->set_status(EE_Data_Migration_Manager::status_fatal_error);
436
+				throw $e;
437
+			}
438
+			// record that we've done these schema changes
439
+			$this->{$property_name} = true;
440
+			// if there were any warnings etc, record them as non-fatal errors
441
+			if ($output) {
442
+				// there were some warnings
443
+				$this->_errors[] = $output;
444
+			}
445
+		}
446
+	}
447
+
448
+
449
+	/**
450
+	 * Wrapper for EEH_Activation::create_table. However, takes into account the request type when
451
+	 * deciding what to pass for its 4th arg, $drop_pre_existing_tables. Using this function, instead
452
+	 * of _table_should_exist_previously, indicates that this table should be new to the EE version being migrated to
453
+	 * or
454
+	 * activated currently. If this is a brand new activation or a migration, and we're indicating this table should
455
+	 * not
456
+	 * previously exist, then we want to set $drop_pre_existing_tables to TRUE (ie, we shouldn't discover that this
457
+	 * table exists in the DB in EEH_Activation::create_table- if it DOES exist, something's wrong and the old table
458
+	 * should be nuked.
459
+	 *
460
+	 * Just for a bit of context, the migration script's db_schema_changes_* methods
461
+	 * are called basically in 3 cases: on brand new activation of EE4 (ie no previous version of EE existed and the
462
+	 * plugin is being activated and we want to add all the brand new tables), upon reactivation of EE4 (it was
463
+	 * deactivated and then reactivated, in which case we want to just verify the DB structure is ok) that table should
464
+	 * be dropped), and during a migration when we're moving the DB to the state of the migration script
465
+	 *
466
+	 * @param string $table_name
467
+	 * @param string $table_definition_sql
468
+	 * @param string $engine_string
469
+	 */
470
+	protected function _table_is_new_in_this_version(
471
+		$table_name,
472
+		$table_definition_sql,
473
+		$engine_string = 'ENGINE=InnoDB '
474
+	) {
475
+		$this->_create_table_and_catch_errors(
476
+			$table_name,
477
+			$table_definition_sql,
478
+			$engine_string,
479
+			$this->_pre_existing_table_should_be_dropped(true)
480
+		);
481
+	}
482
+
483
+	/**
484
+	 * Like _table_is_new_in_this_version and _table_should_exist_previously, this function verifies the given table
485
+	 * exists. But we understand that this table has CHANGED in this version since the previous version. So it's not
486
+	 * completely new, but it's different. So we need to treat it like a new table in terms of verifying it's schema is
487
+	 * correct on activations, migrations, upgrades; but if it exists when it shouldn't, we need to be as lenient as
488
+	 * _table_should_exist_previously.
489
+	 * 8656]{Assumes only this plugin could have added this table (ie, if its a new activation of this plugin, the
490
+	 * table shouldn't exist).
491
+	 *
492
+	 * @param string $table_name
493
+	 * @param string $table_definition_sql
494
+	 * @param string $engine_string
495
+	 */
496
+	protected function _table_is_changed_in_this_version(
497
+		$table_name,
498
+		$table_definition_sql,
499
+		$engine_string = 'ENGINE=MyISAM'
500
+	) {
501
+		$this->_create_table_and_catch_errors(
502
+			$table_name,
503
+			$table_definition_sql,
504
+			$engine_string,
505
+			$this->_pre_existing_table_should_be_dropped(false)
506
+		);
507
+	}
508
+
509
+
510
+	/**
511
+	 * _old_table_exists
512
+	 * returns TRUE if the requested table exists in the current database
513
+	 *
514
+	 * @param string $table_name
515
+	 * @return boolean
516
+	 */
517
+	protected function _old_table_exists($table_name)
518
+	{
519
+		return $this->_get_table_analysis()->tableExists($table_name);
520
+	}
521
+
522
+
523
+	/**
524
+	 * _delete_table_if_empty
525
+	 * returns TRUE if the requested table was empty and successfully empty
526
+	 *
527
+	 * @param string $table_name
528
+	 * @return boolean
529
+	 */
530
+	protected function _delete_table_if_empty($table_name)
531
+	{
532
+		return EEH_Activation::delete_db_table_if_empty($table_name);
533
+	}
534
+
535
+
536
+	/**
537
+	 * It is preferred to use _table_has_not_changed_since_previous or _table_is_changed_in_this_version
538
+	 * as these are significantly more efficient or explicit.
539
+	 * Please see description of _table_is_new_in_this_version. This function will only set
540
+	 * EEH_Activation::create_table's $drop_pre_existing_tables to TRUE if it's a brand
541
+	 * new activation. ie, a more accurate name for this method would be "_table_added_previously_by_this_plugin"
542
+	 * because the table will be cleared out if this is a new activation (ie, if its a new activation, it actually
543
+	 * should exist previously). Otherwise, we'll always set $drop_pre_existing_tables to FALSE because the table
544
+	 * should have existed. Note, if the table is being MODIFIED in this version being activated or migrated to, then
545
+	 * you want _table_is_changed_in_this_version NOT this one. We don't check this table's structure during migrations
546
+	 * because apparently it hasn't changed since the previous one, right?
547
+	 *
548
+	 * @param string $table_name
549
+	 * @param string $table_definition_sql
550
+	 * @param string $engine_string
551
+	 */
552
+	protected function _table_should_exist_previously(
553
+		$table_name,
554
+		$table_definition_sql,
555
+		$engine_string = 'ENGINE=MyISAM'
556
+	) {
557
+		$this->_create_table_and_catch_errors(
558
+			$table_name,
559
+			$table_definition_sql,
560
+			$engine_string,
561
+			$this->_pre_existing_table_should_be_dropped(false)
562
+		);
563
+	}
564
+
565
+	/**
566
+	 * Exactly the same as _table_should_exist_previously(), except if this migration script is currently doing
567
+	 * a migration, we skip checking this table's structure in the database and just assume it's correct.
568
+	 * So this is useful only to improve efficiency when doing migrations (not a big deal for single site installs,
569
+	 * but important for multisite where migrations can take a very long time otherwise).
570
+	 * If the table is known to have changed since previous version, use _table_is_changed_in_this_version().
571
+	 * Assumes only this plugin could have added this table (ie, if its a new activation of this plugin, the table
572
+	 * shouldn't exist).
573
+	 *
574
+	 * @param string $table_name
575
+	 * @param string $table_definition_sql
576
+	 * @param string $engine_string
577
+	 */
578
+	protected function _table_has_not_changed_since_previous(
579
+		$table_name,
580
+		$table_definition_sql,
581
+		$engine_string = 'ENGINE=MyISAM'
582
+	) {
583
+		if ($this->_currently_migrating()) {
584
+			// if we're doing a migration, and this table apparently already exists, then we don't need do anything right?
585
+			return;
586
+		}
587
+		$this->_create_table_and_catch_errors(
588
+			$table_name,
589
+			$table_definition_sql,
590
+			$engine_string,
591
+			$this->_pre_existing_table_should_be_dropped(false)
592
+		);
593
+	}
594
+
595
+	/**
596
+	 * Returns whether or not this migration script is being used as part of an actual migration
597
+	 *
598
+	 * @return boolean
599
+	 */
600
+	protected function _currently_migrating()
601
+	{
602
+		// we want to know if we are currently performing a migration. We could just believe what was set on the _migrating property, but let's double-check (ie the script should apply and we should be in MM)
603
+		return $this->_migrating &&
604
+			   $this->can_migrate_from_version(
605
+				   EE_Data_Migration_Manager::instance()->ensure_current_database_state_is_set()
606
+			   ) &&
607
+			   EE_Maintenance_Mode::instance()->real_level() == EE_Maintenance_Mode::level_2_complete_maintenance;
608
+	}
609
+
610
+	/**
611
+	 * Determines if a table should be dropped, based on whether it's reported to be new in $table_is_new,
612
+	 * and the plugin's request type.
613
+	 * Assumes only this plugin could have added the table (ie, if its a new activation of this plugin, the table
614
+	 * shouldn't exist no matter what).
615
+	 *
616
+	 * @param boolean $table_is_new
617
+	 * @return boolean
618
+	 */
619
+	protected function _pre_existing_table_should_be_dropped($table_is_new)
620
+	{
621
+		if ($table_is_new) {
622
+			if (
623
+				$this->_get_req_type_for_plugin_corresponding_to_this_dms() == EE_System::req_type_new_activation
624
+				|| $this->_currently_migrating()
625
+			) {
626
+				return true;
627
+			} else {
628
+				return false;
629
+			}
630
+		} else {
631
+			if (
632
+				in_array(
633
+					$this->_get_req_type_for_plugin_corresponding_to_this_dms(),
634
+					array(EE_System::req_type_new_activation)
635
+				)
636
+			) {
637
+				return true;
638
+			} else {
639
+				return false;
640
+			}
641
+		}
642
+	}
643
+
644
+	/**
645
+	 * Just wraps EEH_Activation::create_table, but catches any errors it may throw and adds them as errors on the DMS
646
+	 *
647
+	 * @param string  $table_name
648
+	 * @param string  $table_definition_sql
649
+	 * @param string  $engine_string
650
+	 * @param boolean $drop_pre_existing_tables
651
+	 */
652
+	private function _create_table_and_catch_errors(
653
+		$table_name,
654
+		$table_definition_sql,
655
+		$engine_string = 'ENGINE=MyISAM',
656
+		$drop_pre_existing_tables = false
657
+	) {
658
+		try {
659
+			EEH_Activation::create_table($table_name, $table_definition_sql, $engine_string, $drop_pre_existing_tables);
660
+		} catch (EE_Error $e) {
661
+			$message = $e->getMessage() . '<br>Stack Trace:' . $e->getTraceAsString();
662
+			$this->add_error($message);
663
+			$this->_feedback_message .= $message;
664
+		}
665
+	}
666
+
667
+
668
+	/**
669
+	 * Gets the request type for the plugin (core or addon) that corresponds to this DMS
670
+	 *
671
+	 * @return int one of EE_System::_req_type_* constants
672
+	 * @throws EE_Error
673
+	 */
674
+	private function _get_req_type_for_plugin_corresponding_to_this_dms()
675
+	{
676
+		if ($this->slug() == 'Core') {
677
+			return EE_System::instance()->detect_req_type();
678
+		} else {// it must be for an addon
679
+			$addon_name = $this->slug();
680
+			if (EE_Registry::instance()->get_addon_by_name($addon_name)) {
681
+				return EE_Registry::instance()->get_addon_by_name($addon_name)->detect_req_type();
682
+			} else {
683
+				throw new EE_Error(
684
+					sprintf(
685
+						esc_html__(
686
+							"The DMS slug '%s' should correspond to the addon's name, which should also be '%s', but no such addon was registered. These are the registered addons' names: %s",
687
+							"event_espresso"
688
+						),
689
+						$this->slug(),
690
+						$addon_name,
691
+						implode(",", array_keys(EE_Registry::instance()->get_addons_by_name()))
692
+					)
693
+				);
694
+			}
695
+		}
696
+	}
697
+
698
+
699
+	/**
700
+	 * returns an array of strings describing errors by all the script's stages
701
+	 *
702
+	 * @return array
703
+	 */
704
+	public function get_errors()
705
+	{
706
+		$all_errors = $this->_errors;
707
+		if (! is_array($all_errors)) {
708
+			$all_errors = array();
709
+		}
710
+		foreach ($this->stages() as $stage) {
711
+			$all_errors = array_merge($stage->get_errors(), $all_errors);
712
+		}
713
+		return $all_errors;
714
+	}
715
+
716
+
717
+	/**
718
+	 * Indicates whether or not this migration script should continue
719
+	 *
720
+	 * @return boolean
721
+	 */
722
+	public function can_continue()
723
+	{
724
+		return in_array(
725
+			$this->get_status(),
726
+			EE_Data_Migration_Manager::instance()->stati_that_indicate_to_continue_single_migration_script
727
+		);
728
+	}
729
+
730
+
731
+	/**
732
+	 * Gets all the data migration stages associated with this script. Note:
733
+	 * addons can filter this list to add their own stages, and because the list is
734
+	 * numerically-indexed, they can insert their stage wherever they like and it will
735
+	 * get ordered by the indexes
736
+	 *
737
+	 * @return EE_Data_Migration_Script_Stage[]
738
+	 */
739
+	protected function stages()
740
+	{
741
+		$stages = apply_filters('FHEE__' . get_class($this) . '__stages', $this->_migration_stages);
742
+		ksort($stages);
743
+		return $stages;
744
+	}
745
+
746
+
747
+	/**
748
+	 * Gets a string which should describe what's going on currently with this migration, which
749
+	 * can be displayed to the user
750
+	 *
751
+	 * @return string
752
+	 */
753
+	public function get_feedback_message()
754
+	{
755
+		return $this->_feedback_message;
756
+	}
757
+
758
+
759
+	/**
760
+	 * A lot like "__sleep()" magic method in purpose, this is meant for persisting this class'
761
+	 * properties to the DB. However, we don't want to use __sleep() because its quite
762
+	 * possible that this class is defined when it goes to sleep, but NOT available when it
763
+	 * awakes (eg, this class is part of an addon that is deactivated at some point).
764
+	 */
765
+	public function properties_as_array()
766
+	{
767
+		$properties = parent::properties_as_array();
768
+		$properties['_migration_stages'] = array();
769
+		foreach ($this->_migration_stages as $migration_stage_priority => $migration_stage_class) {
770
+			$properties['_migration_stages'][ $migration_stage_priority ] = $migration_stage_class->properties_as_array(
771
+			);
772
+		}
773
+		unset($properties['_mappings']);
774
+		unset($properties['previous_dms']);
775
+
776
+		foreach ($this->_mappings as $old_table_name => $mapping_to_new_table) {
777
+			foreach ($mapping_to_new_table as $new_table_name => $mapping) {
778
+				$this->_set_mapping_option($old_table_name, $new_table_name, $mapping);
779
+			}
780
+		}
781
+		return $properties;
782
+	}
783
+
784
+
785
+	/**
786
+	 * Sets all of the properties of this script stage to match what's in the array, which is assumed
787
+	 * to have been made from the properties_as_array() function.
788
+	 *
789
+	 * @param array $array_of_properties like what's produced from properties_as_array() method
790
+	 * @return void
791
+	 */
792
+	public function instantiate_from_array_of_properties($array_of_properties)
793
+	{
794
+		$stages_properties_arrays = $array_of_properties['_migration_stages'];
795
+		unset($array_of_properties['_migration_stages']);
796
+		unset($array_of_properties['class']);
797
+		foreach ($array_of_properties as $property_name => $property_value) {
798
+			$this->{$property_name} = $property_value;
799
+		}
800
+		// _migration_stages are already instantiated, but have only default data
801
+		foreach ($this->_migration_stages as $stage) {
802
+			$stage_data = $this->_find_migration_stage_data_with_classname(
803
+				get_class($stage),
804
+				$stages_properties_arrays
805
+			);
806
+			// SO, if we found the stage data that was saved, use it. Otherwise, I guess the stage is new? (maybe added by
807
+			// an addon? Unlikely... not sure why it wouldn't exist, but if it doesn't just treat it like it was never started yet)
808
+			if ($stage_data) {
809
+				$stage->instantiate_from_array_of_properties($stage_data);
810
+			}
811
+		}
812
+	}
813
+
814
+
815
+	/**
816
+	 * Gets the migration data from the array $migration_stage_data_arrays (which is an array of arrays, each of which
817
+	 * is pretty well identical to EE_Data_Migration_Stage objects except all their properties are array indexes)
818
+	 * for the given classname
819
+	 *
820
+	 * @param string $classname
821
+	 * @param array  $migration_stage_data_arrays
822
+	 * @return null
823
+	 */
824
+	private function _find_migration_stage_data_with_classname($classname, $migration_stage_data_arrays)
825
+	{
826
+		foreach ($migration_stage_data_arrays as $migration_stage_data_array) {
827
+			if (isset($migration_stage_data_array['class']) && $migration_stage_data_array['class'] == $classname) {
828
+				return $migration_stage_data_array;
829
+			}
830
+		}
831
+		return null;
832
+	}
833
+
834
+
835
+	/**
836
+	 * Returns the version that this script migrates to, based on the script's name.
837
+	 * Cannot be overwritten because lots of code needs to know which version a script
838
+	 * migrates to knowing only its name.
839
+	 *
840
+	 * @return array where the first key is the plugin's slug, the 2nd is the version of that plugin
841
+	 * that will be updated to. Eg array('Core','4.1.0')
842
+	 */
843
+	final public function migrates_to_version()
844
+	{
845
+		return EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
846
+	}
847
+
848
+
849
+	/**
850
+	 * Gets this addon's slug as it would appear in the current_db_state wp option,
851
+	 * and if this migration script is for an addon, it SHOULD match the addon's slug
852
+	 * (and also the addon's classname, minus the 'EE_' prefix.). Eg, 'Calendar' for the EE_Calendar addon.
853
+	 * Or 'Core' for core (non-addon).
854
+	 *
855
+	 * @return string
856
+	 */
857
+	public function slug()
858
+	{
859
+		$migrates_to_version_info = $this->migrates_to_version();
860
+		// the slug is the first part of the array
861
+		return $migrates_to_version_info['slug'];
862
+	}
863
+
864
+
865
+	/**
866
+	 * Returns the script's priority relative to DMSs from other addons. However, when
867
+	 * two DMSs from the same addon/core apply, this is ignored (and instead the version that
868
+	 * the script migrates to is used to determine which to run first). The default is 5, but all core DMSs
869
+	 * normally have priority 10. (So if you want a DMS "A" to run before DMS "B", both of which are from addons,
870
+	 * and both of which CAN run at the same time (ie, "B" doesn't depend on "A" to set
871
+	 * the database up so it can run), then you can set "A" to priority 3 or something.
872
+	 *
873
+	 * @return int
874
+	 */
875
+	public function priority()
876
+	{
877
+		return $this->_priority;
878
+	}
879
+
880
+
881
+	/**
882
+	 * Sets whether or not this DMS is being ran as part of a migration, instead of
883
+	 * just being used to setup (or verify) the current database structure matches
884
+	 * what the latest DMS indicates it should be
885
+	 *
886
+	 * @param boolean $migrating
887
+	 * @return void
888
+	 */
889
+	public function set_migrating($migrating = true)
890
+	{
891
+		$this->_migrating = $migrating;
892
+	}
893
+
894
+	/**
895
+	 * Marks that we think this migration class can continue to migrate
896
+	 */
897
+	public function reattempt()
898
+	{
899
+		parent::reattempt();
900
+		// also, we want to reattempt any stages that were marked as borked
901
+		foreach ($this->stages() as $stage) {
902
+			if ($stage->is_broken()) {
903
+				$stage->reattempt();
904
+			}
905
+		}
906
+	}
907 907
 }
Please login to merge, or discard this patch.
data_migration_scripts/4_1_0_stages/EE_DMS_4_1_0_shortcodes.dmsstage.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
     {
19 19
         $new_post_content = $this->_change_event_list_shortcode($old_row['post_content']);
20 20
         global $wpdb;
21
-        $wpdb->query($wpdb->prepare("UPDATE " . $this->_old_table . " SET post_content=%s WHERE ID=%d", $new_post_content, $old_row['ID']));
21
+        $wpdb->query($wpdb->prepare("UPDATE ".$this->_old_table." SET post_content=%s WHERE ID=%d", $new_post_content, $old_row['ID']));
22 22
     }
23 23
 
24 24
     /**
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
     public function _count_records_to_migrate()
49 49
     {
50 50
         global $wpdb;
51
-        $count = $wpdb->get_var("SELECT COUNT(id) FROM " . $this->_old_table . $this->_sql_to_only_select_non_drafts());
51
+        $count = $wpdb->get_var("SELECT COUNT(id) FROM ".$this->_old_table.$this->_sql_to_only_select_non_drafts());
52 52
         return $count;
53 53
     }
54 54
 
Please login to merge, or discard this patch.
Indentation   +47 added lines, -48 removed lines patch added patch discarded remove patch
@@ -2,58 +2,57 @@
 block discarded – undo
2 2
 
3 3
 /**
4 4
  * Goes through all the posts and pages, and converts old shortcodes to new ones
5
-
6
-*/
5
+ */
7 6
 
8 7
 class EE_DMS_4_1_0_shortcodes extends EE_Data_Migration_Script_Stage
9 8
 {
10
-    public function __construct()
11
-    {
12
-        global $wpdb;
13
-        $this->_pretty_name = esc_html__("Shortcodes", "event_espresso");
14
-        $this->_old_table = $wpdb->posts;
15
-        parent::__construct();
16
-    }
17
-    protected function _migrate_old_row($old_row)
18
-    {
19
-        $new_post_content = $this->_change_event_list_shortcode($old_row['post_content']);
20
-        global $wpdb;
21
-        $wpdb->query($wpdb->prepare("UPDATE " . $this->_old_table . " SET post_content=%s WHERE ID=%d", $new_post_content, $old_row['ID']));
22
-    }
9
+	public function __construct()
10
+	{
11
+		global $wpdb;
12
+		$this->_pretty_name = esc_html__("Shortcodes", "event_espresso");
13
+		$this->_old_table = $wpdb->posts;
14
+		parent::__construct();
15
+	}
16
+	protected function _migrate_old_row($old_row)
17
+	{
18
+		$new_post_content = $this->_change_event_list_shortcode($old_row['post_content']);
19
+		global $wpdb;
20
+		$wpdb->query($wpdb->prepare("UPDATE " . $this->_old_table . " SET post_content=%s WHERE ID=%d", $new_post_content, $old_row['ID']));
21
+	}
23 22
 
24
-    /**
25
-     * replaces [EVENT_LIST... with [ESPRESSO_EVENTS...]
26
-     * @param string $old_content
27
-     */
28
-    private function _change_event_list_shortcode($old_content)
29
-    {
30
-        return str_replace("[EVENT_LIST", "[ESPRESSO_EVENTS", $old_content);
31
-    }
23
+	/**
24
+	 * replaces [EVENT_LIST... with [ESPRESSO_EVENTS...]
25
+	 * @param string $old_content
26
+	 */
27
+	private function _change_event_list_shortcode($old_content)
28
+	{
29
+		return str_replace("[EVENT_LIST", "[ESPRESSO_EVENTS", $old_content);
30
+	}
32 31
 
33
-    public function _migration_step($num_items = 50)
34
-    {
35
-        global $wpdb;
36
-        $start_at_record = $this->count_records_migrated();
37
-        $rows = $wpdb->get_results($wpdb->prepare("SELECT * FROM $this->_old_table {$this->_sql_to_only_select_non_drafts()} LIMIT %d,%d", $start_at_record, $num_items), ARRAY_A);
38
-        $items_actually_migrated = 0;
39
-        foreach ($rows as $old_row) {
40
-            $this->_migrate_old_row($old_row);
41
-            $items_actually_migrated++;
42
-        }
43
-        if ($this->count_records_migrated() + $items_actually_migrated >= $this->count_records_to_migrate()) {
44
-            $this->set_completed();
45
-        }
46
-        return $items_actually_migrated;
47
-    }
48
-    public function _count_records_to_migrate()
49
-    {
50
-        global $wpdb;
51
-        $count = $wpdb->get_var("SELECT COUNT(id) FROM " . $this->_old_table . $this->_sql_to_only_select_non_drafts());
52
-        return $count;
53
-    }
32
+	public function _migration_step($num_items = 50)
33
+	{
34
+		global $wpdb;
35
+		$start_at_record = $this->count_records_migrated();
36
+		$rows = $wpdb->get_results($wpdb->prepare("SELECT * FROM $this->_old_table {$this->_sql_to_only_select_non_drafts()} LIMIT %d,%d", $start_at_record, $num_items), ARRAY_A);
37
+		$items_actually_migrated = 0;
38
+		foreach ($rows as $old_row) {
39
+			$this->_migrate_old_row($old_row);
40
+			$items_actually_migrated++;
41
+		}
42
+		if ($this->count_records_migrated() + $items_actually_migrated >= $this->count_records_to_migrate()) {
43
+			$this->set_completed();
44
+		}
45
+		return $items_actually_migrated;
46
+	}
47
+	public function _count_records_to_migrate()
48
+	{
49
+		global $wpdb;
50
+		$count = $wpdb->get_var("SELECT COUNT(id) FROM " . $this->_old_table . $this->_sql_to_only_select_non_drafts());
51
+		return $count;
52
+	}
54 53
 
55
-    private function _sql_to_only_select_non_drafts()
56
-    {
57
-        return " WHERE post_type NOT IN ('revision','auto-draft','attachment','nav_menu_item') ";
58
-    }
54
+	private function _sql_to_only_select_non_drafts()
55
+	{
56
+		return " WHERE post_type NOT IN ('revision','auto-draft','attachment','nav_menu_item') ";
57
+	}
59 58
 }
Please login to merge, or discard this patch.
core/data_migration_scripts/4_1_0_stages/EE_DMS_4_1_0_checkins.dmsstage.php 2 patches
Indentation   +142 added lines, -142 removed lines patch added patch discarded remove patch
@@ -26,160 +26,160 @@
 block discarded – undo
26 26
 
27 27
 class EE_DMS_4_1_0_checkins extends EE_Data_Migration_Script_Stage_Table
28 28
 {
29
-    private $_new_table;
30
-    public function __construct()
31
-    {
32
-        global $wpdb;
33
-        $this->_pretty_name = esc_html__('Checkins', 'event_espresso');
34
-        $this->_old_table = $wpdb->prefix . "events_attendee";
35
-        $this->select_expression = 'att.*, e.event_status';
36
-        $this->_extra_where_sql = 'AS att
29
+	private $_new_table;
30
+	public function __construct()
31
+	{
32
+		global $wpdb;
33
+		$this->_pretty_name = esc_html__('Checkins', 'event_espresso');
34
+		$this->_old_table = $wpdb->prefix . "events_attendee";
35
+		$this->select_expression = 'att.*, e.event_status';
36
+		$this->_extra_where_sql = 'AS att
37 37
             INNER JOIN ' . $wpdb->prefix . 'events_detail AS e ON att.event_id=e.id
38 38
             WHERE e.event_status!="D"';
39
-        $this->_new_table = $wpdb->prefix . "esp_checkin";
40
-        parent::__construct();
41
-    }
42
-    protected function _migrate_old_row($old_row)
43
-    {
44
-        global $wpdb;
45
-        $new_reg_table = $wpdb->prefix . "esp_registration";
39
+		$this->_new_table = $wpdb->prefix . "esp_checkin";
40
+		parent::__construct();
41
+	}
42
+	protected function _migrate_old_row($old_row)
43
+	{
44
+		global $wpdb;
45
+		$new_reg_table = $wpdb->prefix . "esp_registration";
46 46
 
47
-        $num_to_checkin_at_this_time = max(array(intval($old_row['checked_in_quantity']),intval($old_row['checked_in']))) ;
47
+		$num_to_checkin_at_this_time = max(array(intval($old_row['checked_in_quantity']),intval($old_row['checked_in']))) ;
48 48
 
49
-        $new_registrations_for_attendee = $this->get_migration_script()->get_mapping_new_pk($this->_old_table, $old_row['id'], $new_reg_table);
50
-        if (! $new_registrations_for_attendee) {
51
-            $new_registrations_for_attendee = array();
52
-        }
53
-        $new_datetime = $this->_try_to_find_datetime($old_row);
49
+		$new_registrations_for_attendee = $this->get_migration_script()->get_mapping_new_pk($this->_old_table, $old_row['id'], $new_reg_table);
50
+		if (! $new_registrations_for_attendee) {
51
+			$new_registrations_for_attendee = array();
52
+		}
53
+		$new_datetime = $this->_try_to_find_datetime($old_row);
54 54
 
55
-        // make sure registrations array is numerically indexed starting at 0 (it probably already is)
56
-        $new_registrations_for_attendee = array_values($new_registrations_for_attendee);
57
-        $new_checkin_ids = array();
58
-        for ($i = 0; $i < abs($num_to_checkin_at_this_time); $i++) {
59
-            $new_reg_id = $new_registrations_for_attendee[ $i ];
60
-            if (! $new_reg_id) {
61
-                $this->add_error(sprintf(
62
-                    esc_html__(
63
-                        /* translators: %1$s database row represented in JSON, %2$s number of registrations to check-in
55
+		// make sure registrations array is numerically indexed starting at 0 (it probably already is)
56
+		$new_registrations_for_attendee = array_values($new_registrations_for_attendee);
57
+		$new_checkin_ids = array();
58
+		for ($i = 0; $i < abs($num_to_checkin_at_this_time); $i++) {
59
+			$new_reg_id = $new_registrations_for_attendee[ $i ];
60
+			if (! $new_reg_id) {
61
+				$this->add_error(sprintf(
62
+					esc_html__(
63
+						/* translators: %1$s database row represented in JSON, %2$s number of registrations to check-in
64 64
                         *  %3$s number of registrations for the attendee, %4$s new registration rows represented in JSON
65 65
                         */
66
-                        // @codingStandardsIgnoreStart
67
-                        'It appears we wanted to check-in more registrations than actually exist. The old attendee record (%1$s) indicated we should check-in %2$d registrations, but there are only %3$d registrations for that attendee (%4$s)',
68
-                        // @codingStandardsIgnoreEnd
69
-                        'event_espresso'
70
-                    ),
71
-                    $this->_json_encode($old_row),
72
-                    abs($num_to_checkin_at_this_time),
73
-                    count($new_registrations_for_attendee),
74
-                    $this->_json_encode($new_registrations_for_attendee)
75
-                ));
76
-                break;
77
-            }
78
-            $existing_checkin_record = $wpdb->get_var(
79
-                $wpdb->prepare(
80
-                    "SELECT CHK_ID FROM $this->_new_table WHERE REG_ID = %d ORDER BY CHK_ID DESC LIMIT 1",
81
-                    $new_reg_id
82
-                )
83
-            );
84
-            if (! $existing_checkin_record) {
85
-                $new_id = $this->_insert_checkin_record($new_reg_id, $new_datetime);
86
-                if ($new_id) {
87
-                    $new_checkin_ids[] = $new_id;
88
-                }
89
-            }
90
-        }
91
-        if ($new_checkin_ids) {
92
-            $this->get_migration_script()->set_mapping(
93
-                $this->_old_table,
94
-                $old_row['id'],
95
-                $this->_new_table,
96
-                $new_checkin_ids
97
-            );
98
-        }
99
-    }
66
+						// @codingStandardsIgnoreStart
67
+						'It appears we wanted to check-in more registrations than actually exist. The old attendee record (%1$s) indicated we should check-in %2$d registrations, but there are only %3$d registrations for that attendee (%4$s)',
68
+						// @codingStandardsIgnoreEnd
69
+						'event_espresso'
70
+					),
71
+					$this->_json_encode($old_row),
72
+					abs($num_to_checkin_at_this_time),
73
+					count($new_registrations_for_attendee),
74
+					$this->_json_encode($new_registrations_for_attendee)
75
+				));
76
+				break;
77
+			}
78
+			$existing_checkin_record = $wpdb->get_var(
79
+				$wpdb->prepare(
80
+					"SELECT CHK_ID FROM $this->_new_table WHERE REG_ID = %d ORDER BY CHK_ID DESC LIMIT 1",
81
+					$new_reg_id
82
+				)
83
+			);
84
+			if (! $existing_checkin_record) {
85
+				$new_id = $this->_insert_checkin_record($new_reg_id, $new_datetime);
86
+				if ($new_id) {
87
+					$new_checkin_ids[] = $new_id;
88
+				}
89
+			}
90
+		}
91
+		if ($new_checkin_ids) {
92
+			$this->get_migration_script()->set_mapping(
93
+				$this->_old_table,
94
+				$old_row['id'],
95
+				$this->_new_table,
96
+				$new_checkin_ids
97
+			);
98
+		}
99
+	}
100 100
 
101 101
 
102
-    /**
103
-     * Tries to find the new datetime the Check-in was for, based on the attendee row
104
-     * (because we know the attendee was for an event as a specific time, and we know
105
-     * the event's OLD ID...)
106
-     * @global type $wpdb
107
-     * @param array $old_attendee_row
108
-     * @return array row of datetime from DB
109
-     */
110
-    private function _try_to_find_datetime($old_attendee)
111
-    {
112
-        global $wpdb;
102
+	/**
103
+	 * Tries to find the new datetime the Check-in was for, based on the attendee row
104
+	 * (because we know the attendee was for an event as a specific time, and we know
105
+	 * the event's OLD ID...)
106
+	 * @global type $wpdb
107
+	 * @param array $old_attendee_row
108
+	 * @return array row of datetime from DB
109
+	 */
110
+	private function _try_to_find_datetime($old_attendee)
111
+	{
112
+		global $wpdb;
113 113
 
114
-        $new_event_id = $this->get_migration_script()->get_mapping_new_pk($wpdb->prefix . "events_detail", $old_attendee['event_id'], $wpdb->posts);
115
-        if (! $new_event_id) {
116
-            $this->add_error(
117
-                sprintf(
118
-                    esc_html__(
119
-                        /* translators: 1: original event ID, 2: original attendee database row */
120
-                        // @codingStandardsIgnoreStart
121
-                        'Could not find new event ID with old event ID %1$d, on attendee row %2$s; and because of that couldn\'t find the correct datetime for Check-in',
122
-                        // @codingStandardsIgnoreEnd
123
-                        'event_espresso'
124
-                    ),
125
-                    $old_attendee['event_id'],
126
-                    $this->_json_encode($old_attendee)
127
-                )
128
-            );
129
-            return 0;
130
-        }
131
-        $old_att_start_date = $old_attendee['start_date'];
132
-        $old_att_start_time = $this->get_migration_script()->convertTimeFromAMPM($old_attendee['event_time']);
133
-        $old_att_datetime = $this->get_migration_script()->convert_date_string_to_utc($this, $old_attendee, "$old_att_start_date $old_att_start_time:00");
114
+		$new_event_id = $this->get_migration_script()->get_mapping_new_pk($wpdb->prefix . "events_detail", $old_attendee['event_id'], $wpdb->posts);
115
+		if (! $new_event_id) {
116
+			$this->add_error(
117
+				sprintf(
118
+					esc_html__(
119
+						/* translators: 1: original event ID, 2: original attendee database row */
120
+						// @codingStandardsIgnoreStart
121
+						'Could not find new event ID with old event ID %1$d, on attendee row %2$s; and because of that couldn\'t find the correct datetime for Check-in',
122
+						// @codingStandardsIgnoreEnd
123
+						'event_espresso'
124
+					),
125
+					$old_attendee['event_id'],
126
+					$this->_json_encode($old_attendee)
127
+				)
128
+			);
129
+			return 0;
130
+		}
131
+		$old_att_start_date = $old_attendee['start_date'];
132
+		$old_att_start_time = $this->get_migration_script()->convertTimeFromAMPM($old_attendee['event_time']);
133
+		$old_att_datetime = $this->get_migration_script()->convert_date_string_to_utc($this, $old_attendee, "$old_att_start_date $old_att_start_time:00");
134 134
 
135
-        $datetime_table = $wpdb->prefix . "esp_datetime";
136
-        // add all conditions to an array from which we can SHIFT conditions off in order to widen our search
137
-        // the most important condition should be last, as it will be array_shift'ed off last
138
-        $conditions = array(
139
-            $wpdb->prepare("$datetime_table.DTT_EVT_start = %s", $old_att_datetime),// times match?
140
-            $wpdb->prepare("$datetime_table.EVT_ID = %d", $new_event_id),// events match?
141
-        );
142
-        // start running queries, widening search each time by removing a condition
143
-        $datetime_found = null;
144
-        do {
145
-            $full_query = "SELECT * FROM $datetime_table WHERE " . implode(" AND ", $conditions) . " LIMIT 1";
146
-            $datetime_found = $wpdb->get_row($full_query, ARRAY_A);
147
-            array_shift($conditions);
148
-        } while (! $datetime_found && $conditions);
149
-        return $datetime_found;
150
-    }
135
+		$datetime_table = $wpdb->prefix . "esp_datetime";
136
+		// add all conditions to an array from which we can SHIFT conditions off in order to widen our search
137
+		// the most important condition should be last, as it will be array_shift'ed off last
138
+		$conditions = array(
139
+			$wpdb->prepare("$datetime_table.DTT_EVT_start = %s", $old_att_datetime),// times match?
140
+			$wpdb->prepare("$datetime_table.EVT_ID = %d", $new_event_id),// events match?
141
+		);
142
+		// start running queries, widening search each time by removing a condition
143
+		$datetime_found = null;
144
+		do {
145
+			$full_query = "SELECT * FROM $datetime_table WHERE " . implode(" AND ", $conditions) . " LIMIT 1";
146
+			$datetime_found = $wpdb->get_row($full_query, ARRAY_A);
147
+			array_shift($conditions);
148
+		} while (! $datetime_found && $conditions);
149
+		return $datetime_found;
150
+	}
151 151
 
152
-    /**
153
-     * Adds a new Check-in/checkout record according for $new_reg_id,$new_datetime_id,$checking_in, and $timestmap
154
-     * @param int $new_reg_id
155
-     * @param int $new_datetime_id
156
-     * @param string $timestamp mysql datetime
157
-     * @return int new Check-in id
158
-     */
159
-    private function _insert_checkin_record($new_reg_id, $new_datetime)
160
-    {
161
-        global $wpdb;
152
+	/**
153
+	 * Adds a new Check-in/checkout record according for $new_reg_id,$new_datetime_id,$checking_in, and $timestmap
154
+	 * @param int $new_reg_id
155
+	 * @param int $new_datetime_id
156
+	 * @param string $timestamp mysql datetime
157
+	 * @return int new Check-in id
158
+	 */
159
+	private function _insert_checkin_record($new_reg_id, $new_datetime)
160
+	{
161
+		global $wpdb;
162 162
 
163 163
 
164
-        // ok we can actually do what we set out to do: add a checkin/checkout record
165
-        $cols_n_values = array(
166
-            'REG_ID' => $new_reg_id,
167
-            'DTT_ID' => $new_datetime['DTT_ID'],
168
-            'CHK_in' => true,
169
-            'CHK_timestamp' => $new_datetime['DTT_EVT_start']
170
-        );
171
-        $datatypes = array(
172
-            '%d',// REG_ID
173
-            '%d',// DTT_ID
174
-            '%d',// CHK_in
175
-            '%s',// CHK_timestamp
176
-        );
177
-        $success = $wpdb->insert($this->_new_table, $cols_n_values, $datatypes);
178
-        if (! $success) {
179
-            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_checkin, $this->_new_table, $cols_n_values, $datatypes));
180
-            return 0;
181
-        }
182
-        $new_id = $wpdb->insert_id;
183
-        return $new_id;
184
-    }
164
+		// ok we can actually do what we set out to do: add a checkin/checkout record
165
+		$cols_n_values = array(
166
+			'REG_ID' => $new_reg_id,
167
+			'DTT_ID' => $new_datetime['DTT_ID'],
168
+			'CHK_in' => true,
169
+			'CHK_timestamp' => $new_datetime['DTT_EVT_start']
170
+		);
171
+		$datatypes = array(
172
+			'%d',// REG_ID
173
+			'%d',// DTT_ID
174
+			'%d',// CHK_in
175
+			'%s',// CHK_timestamp
176
+		);
177
+		$success = $wpdb->insert($this->_new_table, $cols_n_values, $datatypes);
178
+		if (! $success) {
179
+			$this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_checkin, $this->_new_table, $cols_n_values, $datatypes));
180
+			return 0;
181
+		}
182
+		$new_id = $wpdb->insert_id;
183
+		return $new_id;
184
+	}
185 185
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -31,23 +31,23 @@  discard block
 block discarded – undo
31 31
     {
32 32
         global $wpdb;
33 33
         $this->_pretty_name = esc_html__('Checkins', 'event_espresso');
34
-        $this->_old_table = $wpdb->prefix . "events_attendee";
34
+        $this->_old_table = $wpdb->prefix."events_attendee";
35 35
         $this->select_expression = 'att.*, e.event_status';
36 36
         $this->_extra_where_sql = 'AS att
37
-            INNER JOIN ' . $wpdb->prefix . 'events_detail AS e ON att.event_id=e.id
37
+            INNER JOIN ' . $wpdb->prefix.'events_detail AS e ON att.event_id=e.id
38 38
             WHERE e.event_status!="D"';
39
-        $this->_new_table = $wpdb->prefix . "esp_checkin";
39
+        $this->_new_table = $wpdb->prefix."esp_checkin";
40 40
         parent::__construct();
41 41
     }
42 42
     protected function _migrate_old_row($old_row)
43 43
     {
44 44
         global $wpdb;
45
-        $new_reg_table = $wpdb->prefix . "esp_registration";
45
+        $new_reg_table = $wpdb->prefix."esp_registration";
46 46
 
47
-        $num_to_checkin_at_this_time = max(array(intval($old_row['checked_in_quantity']),intval($old_row['checked_in']))) ;
47
+        $num_to_checkin_at_this_time = max(array(intval($old_row['checked_in_quantity']), intval($old_row['checked_in'])));
48 48
 
49 49
         $new_registrations_for_attendee = $this->get_migration_script()->get_mapping_new_pk($this->_old_table, $old_row['id'], $new_reg_table);
50
-        if (! $new_registrations_for_attendee) {
50
+        if ( ! $new_registrations_for_attendee) {
51 51
             $new_registrations_for_attendee = array();
52 52
         }
53 53
         $new_datetime = $this->_try_to_find_datetime($old_row);
@@ -56,8 +56,8 @@  discard block
 block discarded – undo
56 56
         $new_registrations_for_attendee = array_values($new_registrations_for_attendee);
57 57
         $new_checkin_ids = array();
58 58
         for ($i = 0; $i < abs($num_to_checkin_at_this_time); $i++) {
59
-            $new_reg_id = $new_registrations_for_attendee[ $i ];
60
-            if (! $new_reg_id) {
59
+            $new_reg_id = $new_registrations_for_attendee[$i];
60
+            if ( ! $new_reg_id) {
61 61
                 $this->add_error(sprintf(
62 62
                     esc_html__(
63 63
                         /* translators: %1$s database row represented in JSON, %2$s number of registrations to check-in
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
                     $new_reg_id
82 82
                 )
83 83
             );
84
-            if (! $existing_checkin_record) {
84
+            if ( ! $existing_checkin_record) {
85 85
                 $new_id = $this->_insert_checkin_record($new_reg_id, $new_datetime);
86 86
                 if ($new_id) {
87 87
                     $new_checkin_ids[] = $new_id;
@@ -111,8 +111,8 @@  discard block
 block discarded – undo
111 111
     {
112 112
         global $wpdb;
113 113
 
114
-        $new_event_id = $this->get_migration_script()->get_mapping_new_pk($wpdb->prefix . "events_detail", $old_attendee['event_id'], $wpdb->posts);
115
-        if (! $new_event_id) {
114
+        $new_event_id = $this->get_migration_script()->get_mapping_new_pk($wpdb->prefix."events_detail", $old_attendee['event_id'], $wpdb->posts);
115
+        if ( ! $new_event_id) {
116 116
             $this->add_error(
117 117
                 sprintf(
118 118
                     esc_html__(
@@ -132,20 +132,20 @@  discard block
 block discarded – undo
132 132
         $old_att_start_time = $this->get_migration_script()->convertTimeFromAMPM($old_attendee['event_time']);
133 133
         $old_att_datetime = $this->get_migration_script()->convert_date_string_to_utc($this, $old_attendee, "$old_att_start_date $old_att_start_time:00");
134 134
 
135
-        $datetime_table = $wpdb->prefix . "esp_datetime";
135
+        $datetime_table = $wpdb->prefix."esp_datetime";
136 136
         // add all conditions to an array from which we can SHIFT conditions off in order to widen our search
137 137
         // the most important condition should be last, as it will be array_shift'ed off last
138 138
         $conditions = array(
139
-            $wpdb->prepare("$datetime_table.DTT_EVT_start = %s", $old_att_datetime),// times match?
140
-            $wpdb->prepare("$datetime_table.EVT_ID = %d", $new_event_id),// events match?
139
+            $wpdb->prepare("$datetime_table.DTT_EVT_start = %s", $old_att_datetime), // times match?
140
+            $wpdb->prepare("$datetime_table.EVT_ID = %d", $new_event_id), // events match?
141 141
         );
142 142
         // start running queries, widening search each time by removing a condition
143 143
         $datetime_found = null;
144 144
         do {
145
-            $full_query = "SELECT * FROM $datetime_table WHERE " . implode(" AND ", $conditions) . " LIMIT 1";
145
+            $full_query = "SELECT * FROM $datetime_table WHERE ".implode(" AND ", $conditions)." LIMIT 1";
146 146
             $datetime_found = $wpdb->get_row($full_query, ARRAY_A);
147 147
             array_shift($conditions);
148
-        } while (! $datetime_found && $conditions);
148
+        }while ( ! $datetime_found && $conditions);
149 149
         return $datetime_found;
150 150
     }
151 151
 
@@ -169,13 +169,13 @@  discard block
 block discarded – undo
169 169
             'CHK_timestamp' => $new_datetime['DTT_EVT_start']
170 170
         );
171 171
         $datatypes = array(
172
-            '%d',// REG_ID
173
-            '%d',// DTT_ID
174
-            '%d',// CHK_in
175
-            '%s',// CHK_timestamp
172
+            '%d', // REG_ID
173
+            '%d', // DTT_ID
174
+            '%d', // CHK_in
175
+            '%s', // CHK_timestamp
176 176
         );
177 177
         $success = $wpdb->insert($this->_new_table, $cols_n_values, $datatypes);
178
-        if (! $success) {
178
+        if ( ! $success) {
179 179
             $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_checkin, $this->_new_table, $cols_n_values, $datatypes));
180 180
             return 0;
181 181
         }
Please login to merge, or discard this patch.
core/data_migration_scripts/EE_DMS_Core_4_9_0.dms.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -9,12 +9,12 @@  discard block
 block discarded – undo
9 9
 // unfortunately, this needs to be done upon INCLUSION of this file,
10 10
 // instead of construction, because it only gets constructed on first page load
11 11
 // (all other times it gets resurrected from a wordpress option)
12
-$stages = glob(EE_CORE . 'data_migration_scripts/4_9_0_stages/*');
12
+$stages = glob(EE_CORE.'data_migration_scripts/4_9_0_stages/*');
13 13
 $class_to_filepath = array();
14 14
 foreach ($stages as $filepath) {
15 15
     $matches = array();
16 16
     preg_match('~4_9_0_stages/(.*).dmsstage.php~', $filepath, $matches);
17
-    $class_to_filepath[ $matches[1] ] = $filepath;
17
+    $class_to_filepath[$matches[1]] = $filepath;
18 18
 }
19 19
 // give addons a chance to autoload their stages too
20 20
 $class_to_filepath = apply_filters('FHEE__EE_DMS_4_9_0__autoloaded_stages', $class_to_filepath);
@@ -65,10 +65,10 @@  discard block
 block discarded – undo
65 65
         if (version_compare($version_string, '4.9.0.decaf', '<') && version_compare($version_string, '4.8.0.decaf', '>=')) {
66 66
             //          echo "$version_string can be migrated from";
67 67
             return true;
68
-        } elseif (! $version_string) {
68
+        } elseif ( ! $version_string) {
69 69
             //          echo "no version string provided: $version_string";
70 70
             // no version string provided... this must be pre 4.3
71
-            return false;// changed mind. dont want people thinking they should migrate yet because they cant
71
+            return false; // changed mind. dont want people thinking they should migrate yet because they cant
72 72
         } else {
73 73
             //          echo "$version_string doesnt apply";
74 74
             return false;
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
      */
83 83
     public function schema_changes_before_migration()
84 84
     {
85
-        require_once(EE_HELPERS . 'EEH_Activation.helper.php');
85
+        require_once(EE_HELPERS.'EEH_Activation.helper.php');
86 86
         $now_in_mysql = current_time('mysql', true);
87 87
         $table_name = 'esp_answer';
88 88
         $sql = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
Please login to merge, or discard this patch.
Indentation   +310 added lines, -310 removed lines patch added patch discarded remove patch
@@ -12,9 +12,9 @@  discard block
 block discarded – undo
12 12
 $stages = glob(EE_CORE . 'data_migration_scripts/4_9_0_stages/*');
13 13
 $class_to_filepath = array();
14 14
 foreach ($stages as $filepath) {
15
-    $matches = array();
16
-    preg_match('~4_9_0_stages/(.*).dmsstage.php~', $filepath, $matches);
17
-    $class_to_filepath[ $matches[1] ] = $filepath;
15
+	$matches = array();
16
+	preg_match('~4_9_0_stages/(.*).dmsstage.php~', $filepath, $matches);
17
+	$class_to_filepath[ $matches[1] ] = $filepath;
18 18
 }
19 19
 // give addons a chance to autoload their stages too
20 20
 $class_to_filepath = apply_filters('FHEE__EE_DMS_4_9_0__autoloaded_stages', $class_to_filepath);
@@ -33,68 +33,68 @@  discard block
 block discarded – undo
33 33
  */
34 34
 class EE_DMS_Core_4_9_0 extends EE_Data_Migration_Script_Base
35 35
 {
36
-    /**
37
-     * return EE_DMS_Core_4_9_0
38
-     *
39
-     * @param TableManager  $table_manager
40
-     * @param TableAnalysis $table_analysis
41
-     */
42
-    public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
43
-    {
44
-        $this->_pretty_name = esc_html__("Data Update to Event Espresso 4.9.0", "event_espresso");
45
-        $this->_priority = 10;
46
-        $this->_migration_stages = array(
47
-            new EE_DMS_4_9_0_Email_System_Question(),
48
-            new EE_DMS_4_9_0_Answers_With_No_Registration(),
49
-        );
50
-        parent::__construct($table_manager, $table_analysis);
51
-    }
36
+	/**
37
+	 * return EE_DMS_Core_4_9_0
38
+	 *
39
+	 * @param TableManager  $table_manager
40
+	 * @param TableAnalysis $table_analysis
41
+	 */
42
+	public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
43
+	{
44
+		$this->_pretty_name = esc_html__("Data Update to Event Espresso 4.9.0", "event_espresso");
45
+		$this->_priority = 10;
46
+		$this->_migration_stages = array(
47
+			new EE_DMS_4_9_0_Email_System_Question(),
48
+			new EE_DMS_4_9_0_Answers_With_No_Registration(),
49
+		);
50
+		parent::__construct($table_manager, $table_analysis);
51
+	}
52 52
 
53 53
 
54 54
 
55
-    /**
56
-     * Whether to migrate or not.
57
-     *
58
-     * @param array $version_array
59
-     * @return bool
60
-     */
61
-    public function can_migrate_from_version($version_array)
62
-    {
63
-        $version_string = $version_array['Core'];
64
-        if (version_compare($version_string, '4.9.0.decaf', '<') && version_compare($version_string, '4.8.0.decaf', '>=')) {
65
-            //          echo "$version_string can be migrated from";
66
-            return true;
67
-        } elseif (! $version_string) {
68
-            //          echo "no version string provided: $version_string";
69
-            // no version string provided... this must be pre 4.3
70
-            return false;// changed mind. dont want people thinking they should migrate yet because they cant
71
-        } else {
72
-            //          echo "$version_string doesnt apply";
73
-            return false;
74
-        }
75
-    }
55
+	/**
56
+	 * Whether to migrate or not.
57
+	 *
58
+	 * @param array $version_array
59
+	 * @return bool
60
+	 */
61
+	public function can_migrate_from_version($version_array)
62
+	{
63
+		$version_string = $version_array['Core'];
64
+		if (version_compare($version_string, '4.9.0.decaf', '<') && version_compare($version_string, '4.8.0.decaf', '>=')) {
65
+			//          echo "$version_string can be migrated from";
66
+			return true;
67
+		} elseif (! $version_string) {
68
+			//          echo "no version string provided: $version_string";
69
+			// no version string provided... this must be pre 4.3
70
+			return false;// changed mind. dont want people thinking they should migrate yet because they cant
71
+		} else {
72
+			//          echo "$version_string doesnt apply";
73
+			return false;
74
+		}
75
+	}
76 76
 
77 77
 
78 78
 
79
-    /**
80
-     * @return bool
81
-     */
82
-    public function schema_changes_before_migration()
83
-    {
84
-        require_once(EE_HELPERS . 'EEH_Activation.helper.php');
85
-        $now_in_mysql = current_time('mysql', true);
86
-        $table_name = 'esp_answer';
87
-        $sql = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
79
+	/**
80
+	 * @return bool
81
+	 */
82
+	public function schema_changes_before_migration()
83
+	{
84
+		require_once(EE_HELPERS . 'EEH_Activation.helper.php');
85
+		$now_in_mysql = current_time('mysql', true);
86
+		$table_name = 'esp_answer';
87
+		$sql = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
88 88
 					REG_ID int(10) unsigned NOT NULL,
89 89
 					QST_ID int(10) unsigned NOT NULL,
90 90
 					ANS_value text NOT NULL,
91 91
 					PRIMARY KEY  (ANS_ID),
92 92
 					KEY REG_ID (REG_ID),
93 93
 					KEY QST_ID (QST_ID)";
94
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
95
-        $table_name = 'esp_attendee_meta';
96
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'ATT_email');
97
-        $sql = "ATTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
94
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
95
+		$table_name = 'esp_attendee_meta';
96
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'ATT_email');
97
+		$sql = "ATTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
98 98
 				ATT_ID bigint(20) unsigned NOT NULL,
99 99
 				ATT_fname varchar(45) NOT NULL,
100 100
 				ATT_lname varchar(45) NOT NULL,
@@ -111,9 +111,9 @@  discard block
 block discarded – undo
111 111
 				KEY ATT_email (ATT_email(191)),
112 112
 				KEY ATT_lname (ATT_lname),
113 113
 				KEY ATT_fname (ATT_fname)";
114
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
115
-        $table_name = 'esp_checkin';
116
-        $sql = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
114
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
115
+		$table_name = 'esp_checkin';
116
+		$sql = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
117 117
 				REG_ID int(10) unsigned NOT NULL,
118 118
 				DTT_ID int(10) unsigned NOT NULL,
119 119
 				CHK_in tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -121,9 +121,9 @@  discard block
 block discarded – undo
121 121
 				PRIMARY KEY  (CHK_ID),
122 122
 				KEY REG_ID (REG_ID),
123 123
 				KEY DTT_ID (DTT_ID)";
124
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
125
-        $table_name = 'esp_country';
126
-        $sql = "CNT_ISO varchar(2) NOT NULL,
124
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
125
+		$table_name = 'esp_country';
126
+		$sql = "CNT_ISO varchar(2) NOT NULL,
127 127
 				CNT_ISO3 varchar(3) NOT NULL,
128 128
 				RGN_ID tinyint(3) unsigned DEFAULT NULL,
129 129
 				CNT_name varchar(45) NOT NULL,
@@ -139,29 +139,29 @@  discard block
 block discarded – undo
139 139
 				CNT_is_EU tinyint(1) DEFAULT '0',
140 140
 				CNT_active tinyint(1) DEFAULT '0',
141 141
 				PRIMARY KEY  (CNT_ISO)";
142
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
143
-        $table_name = 'esp_currency';
144
-        $sql = "CUR_code varchar(6) NOT NULL,
142
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
143
+		$table_name = 'esp_currency';
144
+		$sql = "CUR_code varchar(6) NOT NULL,
145 145
 				CUR_single varchar(45) DEFAULT 'dollar',
146 146
 				CUR_plural varchar(45) DEFAULT 'dollars',
147 147
 				CUR_sign varchar(45) DEFAULT '$',
148 148
 				CUR_dec_plc varchar(1) NOT NULL DEFAULT '2',
149 149
 				CUR_active tinyint(1) DEFAULT '0',
150 150
 				PRIMARY KEY  (CUR_code)";
151
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
152
-        // note: although this table is no longer in use,
153
-        // it hasn't been removed because then queries to the model will have errors.
154
-        // but you should expect this table and its corresponding model to be removed in
155
-        // the next few months
156
-        $table_name = 'esp_currency_payment_method';
157
-        $sql = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
151
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
152
+		// note: although this table is no longer in use,
153
+		// it hasn't been removed because then queries to the model will have errors.
154
+		// but you should expect this table and its corresponding model to be removed in
155
+		// the next few months
156
+		$table_name = 'esp_currency_payment_method';
157
+		$sql = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
158 158
 				CUR_code varchar(6) NOT NULL,
159 159
 				PMD_ID int(11) NOT NULL,
160 160
 				PRIMARY KEY  (CPM_ID),
161 161
 				KEY PMD_ID (PMD_ID)";
162
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
163
-        $table_name = 'esp_datetime';
164
-        $sql = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
162
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
163
+		$table_name = 'esp_datetime';
164
+		$sql = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
165 165
 				EVT_ID bigint(20) unsigned NOT NULL,
166 166
 				DTT_name varchar(255) NOT NULL DEFAULT '',
167 167
 				DTT_description text NOT NULL,
@@ -178,25 +178,25 @@  discard block
 block discarded – undo
178 178
 				KEY DTT_EVT_start (DTT_EVT_start),
179 179
 				KEY EVT_ID (EVT_ID),
180 180
 				KEY DTT_is_primary (DTT_is_primary)";
181
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
182
-        $table_name = "esp_datetime_ticket";
183
-        $sql = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
181
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
182
+		$table_name = "esp_datetime_ticket";
183
+		$sql = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
184 184
 				DTT_ID int(10) unsigned NOT NULL,
185 185
 				TKT_ID int(10) unsigned NOT NULL,
186 186
 				PRIMARY KEY  (DTK_ID),
187 187
 				KEY DTT_ID (DTT_ID),
188 188
 				KEY TKT_ID (TKT_ID)";
189
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
190
-        $table_name = 'esp_event_message_template';
191
-        $sql = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
189
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
190
+		$table_name = 'esp_event_message_template';
191
+		$sql = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
192 192
 				EVT_ID bigint(20) unsigned NOT NULL DEFAULT 0,
193 193
 				GRP_ID int(10) unsigned NOT NULL DEFAULT 0,
194 194
 				PRIMARY KEY  (EMT_ID),
195 195
 				KEY EVT_ID (EVT_ID),
196 196
 				KEY GRP_ID (GRP_ID)";
197
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
198
-        $table_name = 'esp_event_meta';
199
-        $sql = "EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
197
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
198
+		$table_name = 'esp_event_meta';
199
+		$sql = "EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
200 200
 				EVT_ID bigint(20) unsigned NOT NULL,
201 201
 				EVT_display_desc tinyint(1) unsigned NOT NULL DEFAULT 1,
202 202
 				EVT_display_ticket_selector tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -211,34 +211,34 @@  discard block
 block discarded – undo
211 211
 				EVT_donations tinyint(1) NULL,
212 212
 				PRIMARY KEY  (EVTM_ID),
213 213
 				KEY EVT_ID (EVT_ID)";
214
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
215
-        $table_name = 'esp_event_question_group';
216
-        $sql = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
214
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
215
+		$table_name = 'esp_event_question_group';
216
+		$sql = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
217 217
 				EVT_ID bigint(20) unsigned NOT NULL,
218 218
 				QSG_ID int(10) unsigned NOT NULL,
219 219
 				EQG_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
220 220
 				PRIMARY KEY  (EQG_ID),
221 221
 				KEY EVT_ID (EVT_ID),
222 222
 				KEY QSG_ID (QSG_ID)";
223
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
224
-        $table_name = 'esp_event_venue';
225
-        $sql = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
223
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
224
+		$table_name = 'esp_event_venue';
225
+		$sql = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
226 226
 				EVT_ID bigint(20) unsigned NOT NULL,
227 227
 				VNU_ID bigint(20) unsigned NOT NULL,
228 228
 				EVV_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
229 229
 				PRIMARY KEY  (EVV_ID)";
230
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
231
-        $table_name = 'esp_extra_meta';
232
-        $sql = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
230
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
231
+		$table_name = 'esp_extra_meta';
232
+		$sql = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
233 233
 				OBJ_ID int(11) DEFAULT NULL,
234 234
 				EXM_type varchar(45) DEFAULT NULL,
235 235
 				EXM_key varchar(45) DEFAULT NULL,
236 236
 				EXM_value text,
237 237
 				PRIMARY KEY  (EXM_ID),
238 238
 				KEY EXM_type (EXM_type,OBJ_ID,EXM_key)";
239
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
240
-        $table_name = 'esp_extra_join';
241
-        $sql = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
239
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
240
+		$table_name = 'esp_extra_join';
241
+		$sql = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
242 242
 				EXJ_first_model_id varchar(6) NOT NULL,
243 243
 				EXJ_first_model_name varchar(20) NOT NULL,
244 244
 				EXJ_second_model_id varchar(6) NOT NULL,
@@ -246,9 +246,9 @@  discard block
 block discarded – undo
246 246
 				PRIMARY KEY  (EXJ_ID),
247 247
 				KEY first_model (EXJ_first_model_name,EXJ_first_model_id),
248 248
 				KEY second_model (EXJ_second_model_name,EXJ_second_model_id)";
249
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
250
-        $table_name = 'esp_line_item';
251
-        $sql = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
249
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
250
+		$table_name = 'esp_line_item';
251
+		$sql = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
252 252
 				LIN_code varchar(245) NOT NULL DEFAULT '',
253 253
 				TXN_ID int(11) DEFAULT NULL,
254 254
 				LIN_name varchar(245) NOT NULL DEFAULT '',
@@ -269,11 +269,11 @@  discard block
 block discarded – undo
269 269
 				KEY txn_type_timestamp (TXN_ID,LIN_type,LIN_timestamp),
270 270
 				KEY txn_obj_id_obj_type (TXN_ID,OBJ_ID,OBJ_type),
271 271
 				KEY obj_id_obj_type (OBJ_ID,OBJ_type)";
272
-        $this->_get_table_manager()->dropIndex('esp_line_item', 'TXN_ID');
273
-        $this->_get_table_manager()->dropIndex('esp_line_item', 'LIN_code');
274
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
275
-        $table_name = 'esp_log';
276
-        $sql = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
272
+		$this->_get_table_manager()->dropIndex('esp_line_item', 'TXN_ID');
273
+		$this->_get_table_manager()->dropIndex('esp_line_item', 'LIN_code');
274
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
275
+		$table_name = 'esp_log';
276
+		$sql = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
277 277
 				LOG_time datetime DEFAULT NULL,
278 278
 				OBJ_ID varchar(45) DEFAULT NULL,
279 279
 				OBJ_type varchar(45) DEFAULT NULL,
@@ -284,12 +284,12 @@  discard block
 block discarded – undo
284 284
 				KEY LOG_time (LOG_time),
285 285
 				KEY OBJ (OBJ_type,OBJ_ID),
286 286
 				KEY LOG_type (LOG_type)";
287
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
288
-        $table_name = 'esp_message';
289
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_to');
290
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_from');
291
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_subject');
292
-        $sql = "MSG_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
287
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
288
+		$table_name = 'esp_message';
289
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_to');
290
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_from');
291
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_subject');
292
+		$sql = "MSG_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
293 293
 				GRP_ID int(10) unsigned NULL,
294 294
 				MSG_token varchar(255) NULL,
295 295
 				TXN_ID int(10) unsigned NULL,
@@ -321,18 +321,18 @@  discard block
 block discarded – undo
321 321
 				KEY STS_ID (STS_ID),
322 322
 				KEY MSG_created (MSG_created),
323 323
 				KEY MSG_modified (MSG_modified)";
324
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
325
-        $table_name = 'esp_message_template';
326
-        $sql = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
324
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
325
+		$table_name = 'esp_message_template';
326
+		$sql = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
327 327
 				GRP_ID int(10) unsigned NOT NULL,
328 328
 				MTP_context varchar(50) NOT NULL,
329 329
 				MTP_template_field varchar(30) NOT NULL,
330 330
 				MTP_content text NOT NULL,
331 331
 				PRIMARY KEY  (MTP_ID),
332 332
 				KEY GRP_ID (GRP_ID)";
333
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
334
-        $table_name = 'esp_message_template_group';
335
-        $sql = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
333
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
334
+		$table_name = 'esp_message_template_group';
335
+		$sql = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
336 336
 				MTP_user_id int(10) NOT NULL DEFAULT '1',
337 337
 				MTP_name varchar(245) NOT NULL DEFAULT '',
338 338
 				MTP_description varchar(245) NOT NULL DEFAULT '',
@@ -344,9 +344,9 @@  discard block
 block discarded – undo
344 344
 				MTP_is_active tinyint(1) NOT NULL DEFAULT '1',
345 345
 				PRIMARY KEY  (GRP_ID),
346 346
 				KEY MTP_user_id (MTP_user_id)";
347
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
348
-        $table_name = 'esp_payment';
349
-        $sql = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
347
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
348
+		$table_name = 'esp_payment';
349
+		$sql = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
350 350
 				TXN_ID int(10) unsigned DEFAULT NULL,
351 351
 				STS_ID varchar(3) DEFAULT NULL,
352 352
 				PAY_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -363,9 +363,9 @@  discard block
 block discarded – undo
363 363
 				PRIMARY KEY  (PAY_ID),
364 364
 				KEY PAY_timestamp (PAY_timestamp),
365 365
 				KEY TXN_ID (TXN_ID)";
366
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
367
-        $table_name = 'esp_payment_method';
368
-        $sql = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
366
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
367
+		$table_name = 'esp_payment_method';
368
+		$sql = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
369 369
 				PMD_type varchar(124) DEFAULT NULL,
370 370
 				PMD_name varchar(255) DEFAULT NULL,
371 371
 				PMD_desc text,
@@ -381,24 +381,24 @@  discard block
 block discarded – undo
381 381
 				PRIMARY KEY  (PMD_ID),
382 382
 				UNIQUE KEY PMD_slug_UNIQUE (PMD_slug),
383 383
 				KEY PMD_type (PMD_type)";
384
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
385
-        $table_name = "esp_ticket_price";
386
-        $sql = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
384
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
385
+		$table_name = "esp_ticket_price";
386
+		$sql = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
387 387
 				TKT_ID int(10) unsigned NOT NULL,
388 388
 				PRC_ID int(10) unsigned NOT NULL,
389 389
 				PRIMARY KEY  (TKP_ID),
390 390
 				KEY TKT_ID (TKT_ID),
391 391
 				KEY PRC_ID (PRC_ID)";
392
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
393
-        $table_name = "esp_ticket_template";
394
-        $sql = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
392
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
393
+		$table_name = "esp_ticket_template";
394
+		$sql = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
395 395
 				TTM_name varchar(45) NOT NULL,
396 396
 				TTM_description text,
397 397
 				TTM_file varchar(45),
398 398
 				PRIMARY KEY  (TTM_ID)";
399
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
400
-        $table_name = 'esp_question';
401
-        $sql = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
399
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
400
+		$table_name = 'esp_question';
401
+		$sql = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
402 402
 				QST_display_text text NOT NULL,
403 403
 				QST_admin_label varchar(255) NOT NULL,
404 404
 				QST_system varchar(25) DEFAULT NULL,
@@ -412,18 +412,18 @@  discard block
 block discarded – undo
412 412
 				QST_deleted tinyint(2) unsigned NOT NULL DEFAULT 0,
413 413
 				PRIMARY KEY  (QST_ID),
414 414
 				KEY QST_order (QST_order)';
415
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
416
-        $table_name = 'esp_question_group_question';
417
-        $sql = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
415
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
416
+		$table_name = 'esp_question_group_question';
417
+		$sql = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
418 418
 				QSG_ID int(10) unsigned NOT NULL,
419 419
 				QST_ID int(10) unsigned NOT NULL,
420 420
 				QGQ_order int(10) unsigned NOT NULL DEFAULT 0,
421 421
 				PRIMARY KEY  (QGQ_ID),
422 422
 				KEY QST_ID (QST_ID),
423 423
 				KEY QSG_ID_order (QSG_ID,QGQ_order)";
424
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
425
-        $table_name = 'esp_question_option';
426
-        $sql = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
424
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
425
+		$table_name = 'esp_question_option';
426
+		$sql = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
427 427
 				QSO_value varchar(255) NOT NULL,
428 428
 				QSO_desc text NOT NULL,
429 429
 				QST_ID int(10) unsigned NOT NULL,
@@ -433,9 +433,9 @@  discard block
 block discarded – undo
433 433
 				PRIMARY KEY  (QSO_ID),
434 434
 				KEY QST_ID (QST_ID),
435 435
 				KEY QSO_order (QSO_order)";
436
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
437
-        $table_name = 'esp_registration';
438
-        $sql = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
436
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
437
+		$table_name = 'esp_registration';
438
+		$sql = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
439 439
 				EVT_ID bigint(20) unsigned NOT NULL,
440 440
 				ATT_ID bigint(20) unsigned NOT NULL,
441 441
 				TXN_ID int(10) unsigned NOT NULL,
@@ -459,18 +459,18 @@  discard block
 block discarded – undo
459 459
 				KEY TKT_ID (TKT_ID),
460 460
 				KEY EVT_ID (EVT_ID),
461 461
 				KEY STS_ID (STS_ID)";
462
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
463
-        $table_name = 'esp_registration_payment';
464
-        $sql = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
462
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
463
+		$table_name = 'esp_registration_payment';
464
+		$sql = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
465 465
 					  REG_ID int(10) unsigned NOT NULL,
466 466
 					  PAY_ID int(10) unsigned NULL,
467 467
 					  RPY_amount decimal(12,3) NOT NULL DEFAULT '0.00',
468 468
 					  PRIMARY KEY  (RPY_ID),
469 469
 					  KEY REG_ID (REG_ID),
470 470
 					  KEY PAY_ID (PAY_ID)";
471
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
472
-        $table_name = 'esp_state';
473
-        $sql = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
471
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
472
+		$table_name = 'esp_state';
473
+		$sql = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
474 474
 				CNT_ISO varchar(2) NOT NULL,
475 475
 				STA_abbrev varchar(24) NOT NULL,
476 476
 				STA_name varchar(100) NOT NULL,
@@ -478,9 +478,9 @@  discard block
 block discarded – undo
478 478
 				PRIMARY KEY  (STA_ID),
479 479
 				KEY STA_abbrev (STA_abbrev),
480 480
 				KEY CNT_ISO (CNT_ISO)";
481
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
482
-        $table_name = 'esp_status';
483
-        $sql = "STS_ID varchar(3) NOT NULL,
481
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
482
+		$table_name = 'esp_status';
483
+		$sql = "STS_ID varchar(3) NOT NULL,
484 484
 				STS_code varchar(45) NOT NULL,
485 485
 				STS_type varchar(45) NOT NULL,
486 486
 				STS_can_edit tinyint(1) NOT NULL DEFAULT 0,
@@ -488,9 +488,9 @@  discard block
 block discarded – undo
488 488
 				STS_open tinyint(1) NOT NULL DEFAULT 1,
489 489
 				UNIQUE KEY STS_ID_UNIQUE (STS_ID),
490 490
 				KEY STS_type (STS_type)";
491
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
492
-        $table_name = 'esp_transaction';
493
-        $sql = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
491
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
492
+		$table_name = 'esp_transaction';
493
+		$sql = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
494 494
 				TXN_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
495 495
 				TXN_total decimal(12,3) DEFAULT '0.00',
496 496
 				TXN_paid decimal(12,3) NOT NULL DEFAULT '0.00',
@@ -502,9 +502,9 @@  discard block
 block discarded – undo
502 502
 				PRIMARY KEY  (TXN_ID),
503 503
 				KEY TXN_timestamp (TXN_timestamp),
504 504
 				KEY STS_ID (STS_ID)";
505
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
506
-        $table_name = 'esp_venue_meta';
507
-        $sql = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
505
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
506
+		$table_name = 'esp_venue_meta';
507
+		$sql = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
508 508
 			VNU_ID bigint(20) unsigned NOT NULL DEFAULT 0,
509 509
 			VNU_address varchar(255) DEFAULT NULL,
510 510
 			VNU_address2 varchar(255) DEFAULT NULL,
@@ -523,10 +523,10 @@  discard block
 block discarded – undo
523 523
 			KEY VNU_ID (VNU_ID),
524 524
 			KEY STA_ID (STA_ID),
525 525
 			KEY CNT_ISO (CNT_ISO)";
526
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
527
-        // modified tables
528
-        $table_name = "esp_price";
529
-        $sql = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
526
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
527
+		// modified tables
528
+		$table_name = "esp_price";
529
+		$sql = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
530 530
 				PRT_ID tinyint(3) unsigned NOT NULL,
531 531
 				PRC_amount decimal(12,3) NOT NULL DEFAULT '0.00',
532 532
 				PRC_name varchar(245) NOT NULL,
@@ -539,9 +539,9 @@  discard block
 block discarded – undo
539 539
 				PRC_parent int(10) unsigned DEFAULT 0,
540 540
 				PRIMARY KEY  (PRC_ID),
541 541
 				KEY PRT_ID (PRT_ID)";
542
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
543
-        $table_name = "esp_price_type";
544
-        $sql = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
542
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
543
+		$table_name = "esp_price_type";
544
+		$sql = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
545 545
 				PRT_name varchar(45) NOT NULL,
546 546
 				PBT_ID tinyint(3) unsigned NOT NULL DEFAULT '1',
547 547
 				PRT_is_percent tinyint(1) NOT NULL DEFAULT '0',
@@ -550,9 +550,9 @@  discard block
 block discarded – undo
550 550
 				PRT_deleted tinyint(1) NOT NULL DEFAULT '0',
551 551
 				UNIQUE KEY PRT_name_UNIQUE (PRT_name),
552 552
 				PRIMARY KEY  (PRT_ID)";
553
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
554
-        $table_name = "esp_ticket";
555
-        $sql = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
553
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
554
+		$table_name = "esp_ticket";
555
+		$sql = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
556 556
 				TTM_ID int(10) unsigned NOT NULL,
557 557
 				TKT_name varchar(245) NOT NULL DEFAULT '',
558 558
 				TKT_description text NOT NULL,
@@ -575,9 +575,9 @@  discard block
 block discarded – undo
575 575
 				TKT_deleted tinyint(1) NOT NULL DEFAULT '0',
576 576
 				PRIMARY KEY  (TKT_ID),
577 577
 				KEY TKT_start_date (TKT_start_date)";
578
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
579
-        $table_name = 'esp_question_group';
580
-        $sql = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
578
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
579
+		$table_name = 'esp_question_group';
580
+		$sql = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
581 581
 				QSG_name varchar(255) NOT NULL,
582 582
 				QSG_identifier varchar(100) NOT NULL,
583 583
 				QSG_desc text NULL,
@@ -590,165 +590,165 @@  discard block
 block discarded – undo
590 590
 				PRIMARY KEY  (QSG_ID),
591 591
 				UNIQUE KEY QSG_identifier_UNIQUE (QSG_identifier),
592 592
 				KEY QSG_order (QSG_order)';
593
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
594
-        $this->insert_default_data();
595
-        return true;
596
-    }
593
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
594
+		$this->insert_default_data();
595
+		return true;
596
+	}
597 597
 
598
-    /**
599
-     * Inserts default data after parent was called.
600
-     * @since 4.10.0.p
601
-     * @throws EE_Error
602
-     * @throws InvalidArgumentException
603
-     * @throws ReflectionException
604
-     * @throws InvalidDataTypeException
605
-     * @throws InvalidInterfaceException
606
-     */
607
-    public function insert_default_data()
608
-    {
609
-        /** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
610
-        $script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
611
-        // (because many need to convert old string states to foreign keys into the states table)
612
-        $script_4_1_defaults->insert_default_states();
613
-        $script_4_1_defaults->insert_default_countries();
614
-        /** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
615
-        $script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
616
-        $script_4_5_defaults->insert_default_price_types();
617
-        $script_4_5_defaults->insert_default_prices();
618
-        $script_4_5_defaults->insert_default_tickets();
619
-        /** @var EE_DMS_Core_4_6_0 $script_4_6_defaults */
620
-        $script_4_6_defaults = EE_Registry::instance()->load_dms('Core_4_6_0');
621
-        $script_4_6_defaults->add_default_admin_only_payments();
622
-        $script_4_6_defaults->insert_default_currencies();
623
-        /** @var EE_DMS_Core_4_8_0 $script_4_8_defaults */
624
-        $script_4_8_defaults = EE_Registry::instance()->load_dms('Core_4_8_0');
625
-        $script_4_8_defaults->verify_new_countries();
626
-        $script_4_8_defaults->verify_new_currencies();
627
-        $this->verify_db_collations();
628
-        $this->verify_db_collations_again();
629
-    }
598
+	/**
599
+	 * Inserts default data after parent was called.
600
+	 * @since 4.10.0.p
601
+	 * @throws EE_Error
602
+	 * @throws InvalidArgumentException
603
+	 * @throws ReflectionException
604
+	 * @throws InvalidDataTypeException
605
+	 * @throws InvalidInterfaceException
606
+	 */
607
+	public function insert_default_data()
608
+	{
609
+		/** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
610
+		$script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
611
+		// (because many need to convert old string states to foreign keys into the states table)
612
+		$script_4_1_defaults->insert_default_states();
613
+		$script_4_1_defaults->insert_default_countries();
614
+		/** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
615
+		$script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
616
+		$script_4_5_defaults->insert_default_price_types();
617
+		$script_4_5_defaults->insert_default_prices();
618
+		$script_4_5_defaults->insert_default_tickets();
619
+		/** @var EE_DMS_Core_4_6_0 $script_4_6_defaults */
620
+		$script_4_6_defaults = EE_Registry::instance()->load_dms('Core_4_6_0');
621
+		$script_4_6_defaults->add_default_admin_only_payments();
622
+		$script_4_6_defaults->insert_default_currencies();
623
+		/** @var EE_DMS_Core_4_8_0 $script_4_8_defaults */
624
+		$script_4_8_defaults = EE_Registry::instance()->load_dms('Core_4_8_0');
625
+		$script_4_8_defaults->verify_new_countries();
626
+		$script_4_8_defaults->verify_new_currencies();
627
+		$this->verify_db_collations();
628
+		$this->verify_db_collations_again();
629
+	}
630 630
 
631 631
 
632 632
 
633
-    /**
634
-     * @return boolean
635
-     */
636
-    public function schema_changes_after_migration()
637
-    {
638
-        return true;
639
-    }
633
+	/**
634
+	 * @return boolean
635
+	 */
636
+	public function schema_changes_after_migration()
637
+	{
638
+		return true;
639
+	}
640 640
 
641 641
 
642 642
 
643
-    public function migration_page_hooks()
644
-    {
645
-    }
643
+	public function migration_page_hooks()
644
+	{
645
+	}
646 646
 
647 647
 
648 648
 
649
-    /**
650
-     * Verify all EE4 models' tables use utf8mb4 collation
651
-     *
652
-     * @return void
653
-     */
654
-    public function verify_db_collations()
655
-    {
656
-        global $wpdb;
657
-        // double-check we haven't already done it or that that the DB doesn't support utf8mb4
658
-        if (
659
-            'utf8mb4' !== $wpdb->charset
660
-            || get_option('ee_verified_db_collations', false)
661
-        ) {
662
-            return;
663
-        }
664
-        // grab tables from each model
665
-        $tables_to_check = array();
666
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
667
-            if (method_exists($model_name, 'instance')) {
668
-                $model_obj = call_user_func(array($model_name, 'instance'));
669
-                if ($model_obj instanceof EEM_Base) {
670
-                    foreach ($model_obj->get_tables() as $table) {
671
-                        if (
672
-                            strpos($table->get_table_name(), 'esp_')
673
-                            && (is_main_site()// for main tables, verify global tables
674
-                                || ! $table->is_global()// if not the main site, then only verify non-global tables (avoid doubling up)
675
-                            )
676
-                            && function_exists('maybe_convert_table_to_utf8mb4')
677
-                        ) {
678
-                            $tables_to_check[] = $table->get_table_name();
679
-                        }
680
-                    }
681
-                }
682
-            }
683
-        }
684
-        // and let's just be sure these addons' tables get migrated too. They already get handled if their addons are active
685
-        // when this code is run, but not otherwise. Once we record what tables EE added, we'll be able to use that instead
686
-        // of hard-coding this
687
-        $addon_tables = array(
688
-            // mailchimp
689
-            'esp_event_mailchimp_list_group',
690
-            'esp_event_question_mailchimp_field',
691
-            // multisite
692
-            'esp_blog_meta',
693
-            // people
694
-            'esp_people_to_post',
695
-            // promotions
696
-            'esp_promotion',
697
-            'esp_promotion_object',
698
-        );
699
-        foreach ($addon_tables as $table_name) {
700
-                $tables_to_check[] = $table_name;
701
-        }
702
-        $this->_verify_db_collations_for_tables(array_unique($tables_to_check));
703
-        // ok and now let's remember this was done (without needing to check the db schemas all over again)
704
-        add_option('ee_verified_db_collations', true, null, 'no');
705
-        // seeing how this ran with the fix from 10435, no need to check again
706
-        add_option('ee_verified_db_collations_again', true, null, 'no');
707
-    }
649
+	/**
650
+	 * Verify all EE4 models' tables use utf8mb4 collation
651
+	 *
652
+	 * @return void
653
+	 */
654
+	public function verify_db_collations()
655
+	{
656
+		global $wpdb;
657
+		// double-check we haven't already done it or that that the DB doesn't support utf8mb4
658
+		if (
659
+			'utf8mb4' !== $wpdb->charset
660
+			|| get_option('ee_verified_db_collations', false)
661
+		) {
662
+			return;
663
+		}
664
+		// grab tables from each model
665
+		$tables_to_check = array();
666
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
667
+			if (method_exists($model_name, 'instance')) {
668
+				$model_obj = call_user_func(array($model_name, 'instance'));
669
+				if ($model_obj instanceof EEM_Base) {
670
+					foreach ($model_obj->get_tables() as $table) {
671
+						if (
672
+							strpos($table->get_table_name(), 'esp_')
673
+							&& (is_main_site()// for main tables, verify global tables
674
+								|| ! $table->is_global()// if not the main site, then only verify non-global tables (avoid doubling up)
675
+							)
676
+							&& function_exists('maybe_convert_table_to_utf8mb4')
677
+						) {
678
+							$tables_to_check[] = $table->get_table_name();
679
+						}
680
+					}
681
+				}
682
+			}
683
+		}
684
+		// and let's just be sure these addons' tables get migrated too. They already get handled if their addons are active
685
+		// when this code is run, but not otherwise. Once we record what tables EE added, we'll be able to use that instead
686
+		// of hard-coding this
687
+		$addon_tables = array(
688
+			// mailchimp
689
+			'esp_event_mailchimp_list_group',
690
+			'esp_event_question_mailchimp_field',
691
+			// multisite
692
+			'esp_blog_meta',
693
+			// people
694
+			'esp_people_to_post',
695
+			// promotions
696
+			'esp_promotion',
697
+			'esp_promotion_object',
698
+		);
699
+		foreach ($addon_tables as $table_name) {
700
+				$tables_to_check[] = $table_name;
701
+		}
702
+		$this->_verify_db_collations_for_tables(array_unique($tables_to_check));
703
+		// ok and now let's remember this was done (without needing to check the db schemas all over again)
704
+		add_option('ee_verified_db_collations', true, null, 'no');
705
+		// seeing how this ran with the fix from 10435, no need to check again
706
+		add_option('ee_verified_db_collations_again', true, null, 'no');
707
+	}
708 708
 
709 709
 
710 710
 
711
-    /**
712
-     * Verifies DB collations because a bug was discovered on https://events.codebasehq.com/projects/event-espresso/tickets/10435
713
-     * which meant some DB collations might not have been updated
714
-     * @return void
715
-     */
716
-    public function verify_db_collations_again()
717
-    {
718
-        global $wpdb;
719
-        // double-check we haven't already done this or that the DB doesn't support it
720
-        // compare to how WordPress' upgrade_430() function does this check
721
-        if (
722
-            'utf8mb4' !== $wpdb->charset
723
-            || get_option('ee_verified_db_collations_again', false)
724
-        ) {
725
-            return;
726
-        }
727
-        $tables_to_check = array(
728
-            'esp_attendee_meta',
729
-            'esp_message'
730
-        );
731
-        $this->_verify_db_collations_for_tables(array_unique($tables_to_check));
732
-        add_option('ee_verified_db_collations_again', true, null, 'no');
733
-    }
711
+	/**
712
+	 * Verifies DB collations because a bug was discovered on https://events.codebasehq.com/projects/event-espresso/tickets/10435
713
+	 * which meant some DB collations might not have been updated
714
+	 * @return void
715
+	 */
716
+	public function verify_db_collations_again()
717
+	{
718
+		global $wpdb;
719
+		// double-check we haven't already done this or that the DB doesn't support it
720
+		// compare to how WordPress' upgrade_430() function does this check
721
+		if (
722
+			'utf8mb4' !== $wpdb->charset
723
+			|| get_option('ee_verified_db_collations_again', false)
724
+		) {
725
+			return;
726
+		}
727
+		$tables_to_check = array(
728
+			'esp_attendee_meta',
729
+			'esp_message'
730
+		);
731
+		$this->_verify_db_collations_for_tables(array_unique($tables_to_check));
732
+		add_option('ee_verified_db_collations_again', true, null, 'no');
733
+	}
734 734
 
735 735
 
736 736
 
737
-    /**
738
-     * Runs maybe_convert_table_to_utf8mb4 on the specified tables
739
-     * @param $tables_to_check
740
-     * @return boolean true if logic ran, false if it didn't
741
-     */
742
-    protected function _verify_db_collations_for_tables($tables_to_check)
743
-    {
744
-        foreach ($tables_to_check as $table_name) {
745
-            $table_name = $this->_table_analysis->ensureTableNameHasPrefix($table_name);
746
-            if (
747
-                ! apply_filters('FHEE__EE_DMS_Core_4_9_0__verify_db_collations__check_overridden', false, $table_name)
748
-                && $this->_get_table_analysis()->tableExists($table_name)
749
-            ) {
750
-                maybe_convert_table_to_utf8mb4($table_name);
751
-            }
752
-        }
753
-    }
737
+	/**
738
+	 * Runs maybe_convert_table_to_utf8mb4 on the specified tables
739
+	 * @param $tables_to_check
740
+	 * @return boolean true if logic ran, false if it didn't
741
+	 */
742
+	protected function _verify_db_collations_for_tables($tables_to_check)
743
+	{
744
+		foreach ($tables_to_check as $table_name) {
745
+			$table_name = $this->_table_analysis->ensureTableNameHasPrefix($table_name);
746
+			if (
747
+				! apply_filters('FHEE__EE_DMS_Core_4_9_0__verify_db_collations__check_overridden', false, $table_name)
748
+				&& $this->_get_table_analysis()->tableExists($table_name)
749
+			) {
750
+				maybe_convert_table_to_utf8mb4($table_name);
751
+			}
752
+		}
753
+	}
754 754
 }
Please login to merge, or discard this patch.
4_6_0_stages/EE_DMS_4_6_0_invoice_settings.dmsstage.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -66,8 +66,8 @@
 block discarded – undo
66 66
     {
67 67
 
68 68
         $templates_relative_path = 'modules/gateways/Invoice/lib/templates/';
69
-        $overridden_invoice_body = EEH_Template::locate_template($templates_relative_path . 'invoice_body.template.php', null, false, false, true);
70
-        $overridden_receipt_body = EEH_Template::locate_template($templates_relative_path . 'receipt_body.template.php', null, false, false, true);
69
+        $overridden_invoice_body = EEH_Template::locate_template($templates_relative_path.'invoice_body.template.php', null, false, false, true);
70
+        $overridden_receipt_body = EEH_Template::locate_template($templates_relative_path.'receipt_body.template.php', null, false, false, true);
71 71
         if ($overridden_invoice_body || $overridden_receipt_body) {
72 72
             new PersistentAdminNotice(
73 73
                 'invoice_overriding_templates',
Please login to merge, or discard this patch.
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -27,59 +27,59 @@
 block discarded – undo
27 27
  */
28 28
 class EE_DMS_4_6_0_invoice_settings extends EE_Data_Migration_Script_Stage
29 29
 {
30
-    /**
31
-     * Just initializes the status of the migration
32
-     */
33
-    public function __construct()
34
-    {
35
-        $this->_pretty_name = esc_html__('Update Invoice Settings', 'event_espresso');
36
-        parent::__construct();
37
-    }
30
+	/**
31
+	 * Just initializes the status of the migration
32
+	 */
33
+	public function __construct()
34
+	{
35
+		$this->_pretty_name = esc_html__('Update Invoice Settings', 'event_espresso');
36
+		parent::__construct();
37
+	}
38 38
 
39 39
 
40 40
 
41
-    /**
42
-     * _count_records_to_migrate
43
-     * Counts the records to migrate; the public version may cache it
44
-     *
45
-     * @access protected
46
-     * @return int
47
-     */
48
-    protected function _count_records_to_migrate()
49
-    {
50
-        return 1;
51
-    }
41
+	/**
42
+	 * _count_records_to_migrate
43
+	 * Counts the records to migrate; the public version may cache it
44
+	 *
45
+	 * @access protected
46
+	 * @return int
47
+	 */
48
+	protected function _count_records_to_migrate()
49
+	{
50
+		return 1;
51
+	}
52 52
 
53 53
 
54 54
 
55
-    /**
56
-     *    _migration_step
57
-     *
58
-     * @access protected
59
-     * @param int $num_items
60
-     * @throws EE_Error
61
-     * @return int number of items ACTUALLY migrated
62
-     * @throws InvalidDataTypeException
63
-     */
64
-    protected function _migration_step($num_items = 1)
65
-    {
55
+	/**
56
+	 *    _migration_step
57
+	 *
58
+	 * @access protected
59
+	 * @param int $num_items
60
+	 * @throws EE_Error
61
+	 * @return int number of items ACTUALLY migrated
62
+	 * @throws InvalidDataTypeException
63
+	 */
64
+	protected function _migration_step($num_items = 1)
65
+	{
66 66
 
67
-        $templates_relative_path = 'modules/gateways/Invoice/lib/templates/';
68
-        $overridden_invoice_body = EEH_Template::locate_template($templates_relative_path . 'invoice_body.template.php', null, false, false, true);
69
-        $overridden_receipt_body = EEH_Template::locate_template($templates_relative_path . 'receipt_body.template.php', null, false, false, true);
70
-        if ($overridden_invoice_body || $overridden_receipt_body) {
71
-            new PersistentAdminNotice(
72
-                'invoice_overriding_templates',
73
-                esc_html__(
74
-                    'Note: in this version of Event Espresso, PDF and HTML Invoices and Receipts are now Messages and can be changed just like any other messages; however we noticed you had previously overridden the old default Invoice/Receipt templates. Because of this, your old Invoice/Receipt templates will continue to be used INSTEAD of the new Invoice/Receipt message equivalents (but this will be removed in an upcoming version). We recommend deleting your old Invoice/Receipt templates and using the new messages system. Then modify the new Invoice and Receipt messages\'s content in Messages -> Invoice and Messages -> Receipt.',
75
-                    'event_espresso'
76
-                ),
77
-                true
78
-            );
79
-        }
67
+		$templates_relative_path = 'modules/gateways/Invoice/lib/templates/';
68
+		$overridden_invoice_body = EEH_Template::locate_template($templates_relative_path . 'invoice_body.template.php', null, false, false, true);
69
+		$overridden_receipt_body = EEH_Template::locate_template($templates_relative_path . 'receipt_body.template.php', null, false, false, true);
70
+		if ($overridden_invoice_body || $overridden_receipt_body) {
71
+			new PersistentAdminNotice(
72
+				'invoice_overriding_templates',
73
+				esc_html__(
74
+					'Note: in this version of Event Espresso, PDF and HTML Invoices and Receipts are now Messages and can be changed just like any other messages; however we noticed you had previously overridden the old default Invoice/Receipt templates. Because of this, your old Invoice/Receipt templates will continue to be used INSTEAD of the new Invoice/Receipt message equivalents (but this will be removed in an upcoming version). We recommend deleting your old Invoice/Receipt templates and using the new messages system. Then modify the new Invoice and Receipt messages\'s content in Messages -> Invoice and Messages -> Receipt.',
75
+					'event_espresso'
76
+				),
77
+				true
78
+			);
79
+		}
80 80
 
81
-        // regardless of whether it worked or not, we ought to continue the migration
82
-        $this->set_completed();
83
-        return 1;
84
-    }
81
+		// regardless of whether it worked or not, we ought to continue the migration
82
+		$this->set_completed();
83
+		return 1;
84
+	}
85 85
 }
Please login to merge, or discard this patch.
core/EE_Load_Textdomain.core.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -36,19 +36,19 @@  discard block
 block discarded – undo
36 36
     {
37 37
         EE_Load_Textdomain::loadTranslationsForLocale();
38 38
         // now load the textdomain
39
-        if (!empty(EE_Load_Textdomain::$locale)) {
40
-            $github_mo_path = EE_LANGUAGES_SAFE_DIR . 'event_espresso-' . EE_Load_Textdomain::$locale . '.mo';
39
+        if ( ! empty(EE_Load_Textdomain::$locale)) {
40
+            $github_mo_path = EE_LANGUAGES_SAFE_DIR.'event_espresso-'.EE_Load_Textdomain::$locale.'.mo';
41 41
             if (is_readable($github_mo_path)) {
42 42
                 load_plugin_textdomain('event_espresso', false, EE_LANGUAGES_SAFE_LOC);
43 43
                 return;
44 44
             }
45
-            $glotpress_mo_path = EE_LANGUAGES_SAFE_DIR . 'event-espresso-4-' . EE_Load_Textdomain::$locale . '.mo';
45
+            $glotpress_mo_path = EE_LANGUAGES_SAFE_DIR.'event-espresso-4-'.EE_Load_Textdomain::$locale.'.mo';
46 46
             if (is_readable($glotpress_mo_path)) {
47 47
                 load_textdomain('event_espresso', $glotpress_mo_path);
48 48
                 return;
49 49
             }
50 50
         }
51
-        load_plugin_textdomain('event_espresso', false, dirname(EE_PLUGIN_BASENAME) . '/languages/');
51
+        load_plugin_textdomain('event_espresso', false, dirname(EE_PLUGIN_BASENAME).'/languages/');
52 52
     }
53 53
 
54 54
 
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
         if (empty(EE_Load_Textdomain::$locale)) {
72 72
             return;
73 73
         }
74
-        $language_check_option_name = 'ee_lang_check_' . EE_Load_Textdomain::$locale . '_' . EVENT_ESPRESSO_VERSION;
74
+        $language_check_option_name = 'ee_lang_check_'.EE_Load_Textdomain::$locale.'_'.EVENT_ESPRESSO_VERSION;
75 75
         // check if language files has already been sideloaded
76 76
         if (get_option($language_check_option_name)) {
77 77
             return;
@@ -81,8 +81,8 @@  discard block
 block discarded – undo
81 81
 
82 82
         // load sideloader and sideload the .POT file as this should always be included.
83 83
         $sideloader_args = array(
84
-            '_upload_to'     => EE_PLUGIN_DIR_PATH . 'languages/',
85
-            '_download_from'   => $repo_base_URL . '.pot?raw=true',
84
+            '_upload_to'     => EE_PLUGIN_DIR_PATH.'languages/',
85
+            '_download_from'   => $repo_base_URL.'.pot?raw=true',
86 86
             '_new_file_name' => 'event_espresso.pot',
87 87
         );
88 88
         /** @var EEH_Sideloader $sideloader */
@@ -98,8 +98,8 @@  discard block
 block discarded – undo
98 98
             update_option($language_check_option_name, 1);
99 99
             return;
100 100
         }
101
-        $repo_locale_URL = $repo_base_URL . '-' . EE_Load_Textdomain::$locale;
102
-        $file_name_base = 'event_espresso-' . EE_Load_Textdomain::$locale;
101
+        $repo_locale_URL = $repo_base_URL.'-'.EE_Load_Textdomain::$locale;
102
+        $file_name_base = 'event_espresso-'.EE_Load_Textdomain::$locale;
103 103
 
104 104
         // made it here so let's get the language files from the github repo, first the .mo file
105 105
         $sideloader->set_download_from("{$repo_locale_URL}.mo?raw=true");
Please login to merge, or discard this patch.
Indentation   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -12,105 +12,105 @@
 block discarded – undo
12 12
  */
13 13
 class EE_Load_Textdomain extends EE_Base
14 14
 {
15
-    /**
16
-     * holds the current lang in WP
17
-     *
18
-     * @var string
19
-     */
20
-    private static $locale;
15
+	/**
16
+	 * holds the current lang in WP
17
+	 *
18
+	 * @var string
19
+	 */
20
+	private static $locale;
21 21
 
22 22
 
23
-    /**
24
-     * this takes care of retrieving a matching textdomain for event espresso for the current WPLANG from EE GitHub
25
-     * repo (if necessary) and then loading it for translations. should only be called in wp plugins_loaded callback
26
-     *
27
-     * @return void
28
-     * @throws EE_Error
29
-     * @throws InvalidArgumentException
30
-     * @throws ReflectionException
31
-     * @throws InvalidDataTypeException
32
-     * @throws InvalidInterfaceException
33
-     */
34
-    public static function load_textdomain()
35
-    {
36
-        EE_Load_Textdomain::loadTranslationsForLocale();
37
-        // now load the textdomain
38
-        if (!empty(EE_Load_Textdomain::$locale)) {
39
-            $github_mo_path = EE_LANGUAGES_SAFE_DIR . 'event_espresso-' . EE_Load_Textdomain::$locale . '.mo';
40
-            if (is_readable($github_mo_path)) {
41
-                load_plugin_textdomain('event_espresso', false, EE_LANGUAGES_SAFE_LOC);
42
-                return;
43
-            }
44
-            $glotpress_mo_path = EE_LANGUAGES_SAFE_DIR . 'event-espresso-4-' . EE_Load_Textdomain::$locale . '.mo';
45
-            if (is_readable($glotpress_mo_path)) {
46
-                load_textdomain('event_espresso', $glotpress_mo_path);
47
-                return;
48
-            }
49
-        }
50
-        load_plugin_textdomain('event_espresso', false, dirname(EE_PLUGIN_BASENAME) . '/languages/');
51
-    }
23
+	/**
24
+	 * this takes care of retrieving a matching textdomain for event espresso for the current WPLANG from EE GitHub
25
+	 * repo (if necessary) and then loading it for translations. should only be called in wp plugins_loaded callback
26
+	 *
27
+	 * @return void
28
+	 * @throws EE_Error
29
+	 * @throws InvalidArgumentException
30
+	 * @throws ReflectionException
31
+	 * @throws InvalidDataTypeException
32
+	 * @throws InvalidInterfaceException
33
+	 */
34
+	public static function load_textdomain()
35
+	{
36
+		EE_Load_Textdomain::loadTranslationsForLocale();
37
+		// now load the textdomain
38
+		if (!empty(EE_Load_Textdomain::$locale)) {
39
+			$github_mo_path = EE_LANGUAGES_SAFE_DIR . 'event_espresso-' . EE_Load_Textdomain::$locale . '.mo';
40
+			if (is_readable($github_mo_path)) {
41
+				load_plugin_textdomain('event_espresso', false, EE_LANGUAGES_SAFE_LOC);
42
+				return;
43
+			}
44
+			$glotpress_mo_path = EE_LANGUAGES_SAFE_DIR . 'event-espresso-4-' . EE_Load_Textdomain::$locale . '.mo';
45
+			if (is_readable($glotpress_mo_path)) {
46
+				load_textdomain('event_espresso', $glotpress_mo_path);
47
+				return;
48
+			}
49
+		}
50
+		load_plugin_textdomain('event_espresso', false, dirname(EE_PLUGIN_BASENAME) . '/languages/');
51
+	}
52 52
 
53 53
 
54
-    /**
55
-     * The purpose of this method is to sideload all of the lang files for EE, this includes the POT file and also the PO/MO files for the given WPLANG locale (if necessary).
56
-     *
57
-     * @access private
58
-     * @static
59
-     * @return void
60
-     * @throws EE_Error
61
-     * @throws InvalidArgumentException
62
-     * @throws ReflectionException
63
-     * @throws InvalidDataTypeException
64
-     * @throws InvalidInterfaceException
65
-     */
66
-    private static function loadTranslationsForLocale()
67
-    {
68
-        EE_Load_Textdomain::$locale = get_locale();
69
-        // can't download a language file if a language isn't set <taps temple>
70
-        if (empty(EE_Load_Textdomain::$locale)) {
71
-            return;
72
-        }
73
-        $language_check_option_name = 'ee_lang_check_' . EE_Load_Textdomain::$locale . '_' . EVENT_ESPRESSO_VERSION;
74
-        // check if language files has already been sideloaded
75
-        if (get_option($language_check_option_name)) {
76
-            return;
77
-        }
54
+	/**
55
+	 * The purpose of this method is to sideload all of the lang files for EE, this includes the POT file and also the PO/MO files for the given WPLANG locale (if necessary).
56
+	 *
57
+	 * @access private
58
+	 * @static
59
+	 * @return void
60
+	 * @throws EE_Error
61
+	 * @throws InvalidArgumentException
62
+	 * @throws ReflectionException
63
+	 * @throws InvalidDataTypeException
64
+	 * @throws InvalidInterfaceException
65
+	 */
66
+	private static function loadTranslationsForLocale()
67
+	{
68
+		EE_Load_Textdomain::$locale = get_locale();
69
+		// can't download a language file if a language isn't set <taps temple>
70
+		if (empty(EE_Load_Textdomain::$locale)) {
71
+			return;
72
+		}
73
+		$language_check_option_name = 'ee_lang_check_' . EE_Load_Textdomain::$locale . '_' . EVENT_ESPRESSO_VERSION;
74
+		// check if language files has already been sideloaded
75
+		if (get_option($language_check_option_name)) {
76
+			return;
77
+		}
78 78
 
79
-        $repo_base_URL = 'https://github.com/eventespresso/languages-ee4/blob/master/event_espresso';
79
+		$repo_base_URL = 'https://github.com/eventespresso/languages-ee4/blob/master/event_espresso';
80 80
 
81
-        // load sideloader and sideload the .POT file as this should always be included.
82
-        $sideloader_args = array(
83
-            '_upload_to'     => EE_PLUGIN_DIR_PATH . 'languages/',
84
-            '_download_from'   => $repo_base_URL . '.pot?raw=true',
85
-            '_new_file_name' => 'event_espresso.pot',
86
-        );
87
-        /** @var EEH_Sideloader $sideloader */
88
-        $sideloader = EE_Registry::instance()->load_helper('Sideloader', $sideloader_args, false);
89
-        // sideload the .POT file only for main site of the network, or if not running Multisite.
90
-        if (is_main_site()) {
91
-            $sideloader->sideload();
92
-        }
81
+		// load sideloader and sideload the .POT file as this should always be included.
82
+		$sideloader_args = array(
83
+			'_upload_to'     => EE_PLUGIN_DIR_PATH . 'languages/',
84
+			'_download_from'   => $repo_base_URL . '.pot?raw=true',
85
+			'_new_file_name' => 'event_espresso.pot',
86
+		);
87
+		/** @var EEH_Sideloader $sideloader */
88
+		$sideloader = EE_Registry::instance()->load_helper('Sideloader', $sideloader_args, false);
89
+		// sideload the .POT file only for main site of the network, or if not running Multisite.
90
+		if (is_main_site()) {
91
+			$sideloader->sideload();
92
+		}
93 93
 
94
-        // if locale is "en_US" then lets just get out, since Event Espresso core is already "en_US"
95
-        if (EE_Load_Textdomain::$locale === 'en_US') {
96
-            // but set option first else we'll forever be downloading the pot file
97
-            update_option($language_check_option_name, 1);
98
-            return;
99
-        }
100
-        $repo_locale_URL = $repo_base_URL . '-' . EE_Load_Textdomain::$locale;
101
-        $file_name_base = 'event_espresso-' . EE_Load_Textdomain::$locale;
94
+		// if locale is "en_US" then lets just get out, since Event Espresso core is already "en_US"
95
+		if (EE_Load_Textdomain::$locale === 'en_US') {
96
+			// but set option first else we'll forever be downloading the pot file
97
+			update_option($language_check_option_name, 1);
98
+			return;
99
+		}
100
+		$repo_locale_URL = $repo_base_URL . '-' . EE_Load_Textdomain::$locale;
101
+		$file_name_base = 'event_espresso-' . EE_Load_Textdomain::$locale;
102 102
 
103
-        // made it here so let's get the language files from the github repo, first the .mo file
104
-        $sideloader->set_download_from("{$repo_locale_URL}.mo?raw=true");
105
-        $sideloader->set_new_file_name("{$file_name_base}.mo");
106
-        $sideloader->sideload();
103
+		// made it here so let's get the language files from the github repo, first the .mo file
104
+		$sideloader->set_download_from("{$repo_locale_URL}.mo?raw=true");
105
+		$sideloader->set_new_file_name("{$file_name_base}.mo");
106
+		$sideloader->sideload();
107 107
 
108
-        // now the .po file:
109
-        $sideloader->set_download_from("{$repo_locale_URL}.po?raw=true");
110
-        $sideloader->set_new_file_name("{$file_name_base}.po");
111
-        $sideloader->sideload();
108
+		// now the .po file:
109
+		$sideloader->set_download_from("{$repo_locale_URL}.po?raw=true");
110
+		$sideloader->set_new_file_name("{$file_name_base}.po");
111
+		$sideloader->sideload();
112 112
 
113
-        // set option so the above only runs when EE updates.
114
-        update_option($language_check_option_name, 1);
115
-    }
113
+		// set option so the above only runs when EE updates.
114
+		update_option($language_check_option_name, 1);
115
+	}
116 116
 }
Please login to merge, or discard this patch.