Completed
Branch fix/escaping-2 (5dcb9a)
by
unknown
13:02 queued 10:26
created
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
@@ -17,2117 +17,2117 @@
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * Used to reference when a registration has never been checked in.
22
-     *
23
-     * @deprecated use \EE_Checkin::status_checked_never instead
24
-     * @type int
25
-     */
26
-    const checkin_status_never = 2;
27
-
28
-    /**
29
-     * Used to reference when a registration has been checked in.
30
-     *
31
-     * @deprecated use \EE_Checkin::status_checked_in instead
32
-     * @type int
33
-     */
34
-    const checkin_status_in = 1;
35
-
36
-
37
-    /**
38
-     * Used to reference when a registration has been checked out.
39
-     *
40
-     * @deprecated use \EE_Checkin::status_checked_out instead
41
-     * @type int
42
-     */
43
-    const checkin_status_out = 0;
44
-
45
-
46
-    /**
47
-     * extra meta key for tracking reg status os trashed registrations
48
-     *
49
-     * @type string
50
-     */
51
-    const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
-
53
-
54
-    /**
55
-     * extra meta key for tracking if registration has reserved ticket
56
-     *
57
-     * @type string
58
-     */
59
-    const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
60
-
61
-
62
-    /**
63
-     * @param array  $props_n_values          incoming values
64
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
65
-     *                                        used.)
66
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
67
-     *                                        date_format and the second value is the time format
68
-     * @return EE_Registration
69
-     * @throws EE_Error
70
-     */
71
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
72
-    {
73
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
74
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
75
-    }
76
-
77
-
78
-    /**
79
-     * @param array  $props_n_values  incoming values from the database
80
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
-     *                                the website will be used.
82
-     * @return EE_Registration
83
-     */
84
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
85
-    {
86
-        return new self($props_n_values, true, $timezone);
87
-    }
88
-
89
-
90
-    /**
91
-     *        Set Event ID
92
-     *
93
-     * @param        int $EVT_ID Event ID
94
-     * @throws EE_Error
95
-     * @throws RuntimeException
96
-     */
97
-    public function set_event($EVT_ID = 0)
98
-    {
99
-        $this->set('EVT_ID', $EVT_ID);
100
-    }
101
-
102
-
103
-    /**
104
-     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
105
-     * be routed to internal methods
106
-     *
107
-     * @param string $field_name
108
-     * @param mixed  $field_value
109
-     * @param bool   $use_default
110
-     * @throws EE_Error
111
-     * @throws EntityNotFoundException
112
-     * @throws InvalidArgumentException
113
-     * @throws InvalidDataTypeException
114
-     * @throws InvalidInterfaceException
115
-     * @throws ReflectionException
116
-     * @throws RuntimeException
117
-     */
118
-    public function set($field_name, $field_value, $use_default = false)
119
-    {
120
-        switch ($field_name) {
121
-            case 'REG_code':
122
-                if (! empty($field_value) && $this->reg_code() === null) {
123
-                    $this->set_reg_code($field_value, $use_default);
124
-                }
125
-                break;
126
-            case 'STS_ID':
127
-                $this->set_status($field_value, $use_default);
128
-                break;
129
-            default:
130
-                parent::set($field_name, $field_value, $use_default);
131
-        }
132
-    }
133
-
134
-
135
-    /**
136
-     * Set Status ID
137
-     * updates the registration status and ALSO...
138
-     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
139
-     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
140
-     *
141
-     * @param string                $new_STS_ID
142
-     * @param boolean               $use_default
143
-     * @param ContextInterface|null $context
144
-     * @return bool
145
-     * @throws DomainException
146
-     * @throws EE_Error
147
-     * @throws EntityNotFoundException
148
-     * @throws InvalidArgumentException
149
-     * @throws InvalidDataTypeException
150
-     * @throws InvalidInterfaceException
151
-     * @throws ReflectionException
152
-     * @throws RuntimeException
153
-     * @throws UnexpectedEntityException
154
-     */
155
-    public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
156
-    {
157
-        // get current REG_Status
158
-        $old_STS_ID = $this->status_ID();
159
-        // if status has changed
160
-        if (
161
-            $old_STS_ID !== $new_STS_ID // and that status has actually changed
162
-            && ! empty($old_STS_ID) // and that old status is actually set
163
-            && ! empty($new_STS_ID) // as well as the new status
164
-            && $this->ID() // ensure registration is in the db
165
-        ) {
166
-            // update internal status first
167
-            parent::set('STS_ID', $new_STS_ID, $use_default);
168
-            // THEN handle other changes that occur when reg status changes
169
-            // TO approved
170
-            if ($new_STS_ID === EEM_Registration::status_id_approved) {
171
-                // reserve a space by incrementing ticket and datetime sold values
172
-                $this->reserveRegistrationSpace();
173
-                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
174
-                // OR FROM  approved
175
-            } elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
176
-                // release a space by decrementing ticket and datetime sold values
177
-                $this->releaseRegistrationSpace();
178
-                do_action(
179
-                    'AHEE__EE_Registration__set_status__from_approved',
180
-                    $this,
181
-                    $old_STS_ID,
182
-                    $new_STS_ID,
183
-                    $context
184
-                );
185
-            }
186
-            // update status
187
-            parent::set('STS_ID', $new_STS_ID, $use_default);
188
-            $this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
189
-            if ($this->statusChangeUpdatesTransaction($context)) {
190
-                $this->updateTransactionAfterStatusChange();
191
-            }
192
-            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
193
-            return true;
194
-        }
195
-        // even though the old value matches the new value, it's still good to
196
-        // allow the parent set method to have a say
197
-        parent::set('STS_ID', $new_STS_ID, $use_default);
198
-        return true;
199
-    }
200
-
201
-
202
-    /**
203
-     * update REGs and TXN when cancelled or declined registrations involved
204
-     *
205
-     * @param string                $new_STS_ID
206
-     * @param string                $old_STS_ID
207
-     * @param ContextInterface|null $context
208
-     * @throws EE_Error
209
-     * @throws InvalidArgumentException
210
-     * @throws InvalidDataTypeException
211
-     * @throws InvalidInterfaceException
212
-     * @throws ReflectionException
213
-     * @throws RuntimeException
214
-     */
215
-    private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
216
-    {
217
-        // these reg statuses should not be considered in any calculations involving monies owing
218
-        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
219
-        // true if registration has been cancelled or declined
220
-        $this->updateIfCanceled(
221
-            $closed_reg_statuses,
222
-            $new_STS_ID,
223
-            $old_STS_ID,
224
-            $context
225
-        );
226
-        $this->updateIfReinstated(
227
-            $closed_reg_statuses,
228
-            $new_STS_ID,
229
-            $old_STS_ID,
230
-            $context
231
-        );
232
-    }
233
-
234
-
235
-    /**
236
-     * update REGs and TXN when cancelled or declined registrations involved
237
-     *
238
-     * @param array                 $closed_reg_statuses
239
-     * @param string                $new_STS_ID
240
-     * @param string                $old_STS_ID
241
-     * @param ContextInterface|null $context
242
-     * @throws EE_Error
243
-     * @throws InvalidArgumentException
244
-     * @throws InvalidDataTypeException
245
-     * @throws InvalidInterfaceException
246
-     * @throws ReflectionException
247
-     * @throws RuntimeException
248
-     */
249
-    private function updateIfCanceled(
250
-        array $closed_reg_statuses,
251
-        $new_STS_ID,
252
-        $old_STS_ID,
253
-        ContextInterface $context = null
254
-    ) {
255
-        // true if registration has been cancelled or declined
256
-        if (
257
-            in_array($new_STS_ID, $closed_reg_statuses, true)
258
-            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
259
-        ) {
260
-            /** @type EE_Registration_Processor $registration_processor */
261
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
262
-            /** @type EE_Transaction_Processor $transaction_processor */
263
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
264
-            // cancelled or declined registration
265
-            $registration_processor->update_registration_after_being_canceled_or_declined(
266
-                $this,
267
-                $closed_reg_statuses
268
-            );
269
-            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
270
-                $this,
271
-                $closed_reg_statuses,
272
-                false
273
-            );
274
-            do_action(
275
-                'AHEE__EE_Registration__set_status__canceled_or_declined',
276
-                $this,
277
-                $old_STS_ID,
278
-                $new_STS_ID,
279
-                $context
280
-            );
281
-            return;
282
-        }
283
-    }
284
-
285
-
286
-    /**
287
-     * update REGs and TXN when cancelled or declined registrations involved
288
-     *
289
-     * @param array                 $closed_reg_statuses
290
-     * @param string                $new_STS_ID
291
-     * @param string                $old_STS_ID
292
-     * @param ContextInterface|null $context
293
-     * @throws EE_Error
294
-     * @throws InvalidArgumentException
295
-     * @throws InvalidDataTypeException
296
-     * @throws InvalidInterfaceException
297
-     * @throws ReflectionException
298
-     */
299
-    private function updateIfReinstated(
300
-        array $closed_reg_statuses,
301
-        $new_STS_ID,
302
-        $old_STS_ID,
303
-        ContextInterface $context = null
304
-    ) {
305
-        // true if reinstating cancelled or declined registration
306
-        if (
307
-            in_array($old_STS_ID, $closed_reg_statuses, true)
308
-            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
309
-        ) {
310
-            /** @type EE_Registration_Processor $registration_processor */
311
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
312
-            /** @type EE_Transaction_Processor $transaction_processor */
313
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
314
-            // reinstating cancelled or declined registration
315
-            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
316
-                $this,
317
-                $closed_reg_statuses
318
-            );
319
-            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
320
-                $this,
321
-                $closed_reg_statuses,
322
-                false
323
-            );
324
-            do_action(
325
-                'AHEE__EE_Registration__set_status__after_reinstated',
326
-                $this,
327
-                $old_STS_ID,
328
-                $new_STS_ID,
329
-                $context
330
-            );
331
-        }
332
-    }
333
-
334
-
335
-    /**
336
-     * @param ContextInterface|null $context
337
-     * @return bool
338
-     */
339
-    private function statusChangeUpdatesTransaction(ContextInterface $context = null)
340
-    {
341
-        $contexts_that_do_not_update_transaction = (array) apply_filters(
342
-            'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
343
-            array('spco_reg_step_attendee_information_process_registrations'),
344
-            $context,
345
-            $this
346
-        );
347
-        return ! (
348
-            $context instanceof ContextInterface
349
-            && in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
350
-        );
351
-    }
352
-
353
-
354
-    /**
355
-     * @throws EE_Error
356
-     * @throws EntityNotFoundException
357
-     * @throws InvalidArgumentException
358
-     * @throws InvalidDataTypeException
359
-     * @throws InvalidInterfaceException
360
-     * @throws ReflectionException
361
-     * @throws RuntimeException
362
-     */
363
-    private function updateTransactionAfterStatusChange()
364
-    {
365
-        /** @type EE_Transaction_Payments $transaction_payments */
366
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
367
-        $transaction_payments->recalculate_transaction_total($this->transaction(), false);
368
-        $this->transaction()->update_status_based_on_total_paid(true);
369
-    }
370
-
371
-
372
-    /**
373
-     *        get Status ID
374
-     */
375
-    public function status_ID()
376
-    {
377
-        return $this->get('STS_ID');
378
-    }
379
-
380
-
381
-    /**
382
-     * Gets the ticket this registration is for
383
-     *
384
-     * @param boolean $include_archived whether to include archived tickets or not.
385
-     *
386
-     * @return EE_Ticket|EE_Base_Class
387
-     * @throws EE_Error
388
-     */
389
-    public function ticket($include_archived = true)
390
-    {
391
-        $query_params = array();
392
-        if ($include_archived) {
393
-            $query_params['default_where_conditions'] = 'none';
394
-        }
395
-        return $this->get_first_related('Ticket', $query_params);
396
-    }
397
-
398
-
399
-    /**
400
-     * Gets the event this registration is for
401
-     *
402
-     * @return EE_Event
403
-     * @throws EE_Error
404
-     * @throws EntityNotFoundException
405
-     */
406
-    public function event()
407
-    {
408
-        $event = $this->get_first_related('Event');
409
-        if (! $event instanceof \EE_Event) {
410
-            throw new EntityNotFoundException('Event ID', $this->event_ID());
411
-        }
412
-        return $event;
413
-    }
414
-
415
-
416
-    /**
417
-     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
418
-     * with the author of the event this registration is for.
419
-     *
420
-     * @since 4.5.0
421
-     * @return int
422
-     * @throws EE_Error
423
-     * @throws EntityNotFoundException
424
-     */
425
-    public function wp_user()
426
-    {
427
-        $event = $this->event();
428
-        if ($event instanceof EE_Event) {
429
-            return $event->wp_user();
430
-        }
431
-        return 0;
432
-    }
433
-
434
-
435
-    /**
436
-     * increments this registration's related ticket sold and corresponding datetime sold values
437
-     *
438
-     * @return void
439
-     * @throws DomainException
440
-     * @throws EE_Error
441
-     * @throws EntityNotFoundException
442
-     * @throws InvalidArgumentException
443
-     * @throws InvalidDataTypeException
444
-     * @throws InvalidInterfaceException
445
-     * @throws ReflectionException
446
-     * @throws UnexpectedEntityException
447
-     */
448
-    private function reserveRegistrationSpace()
449
-    {
450
-        // reserved ticket and datetime counts will be decremented as sold counts are incremented
451
-        // so stop tracking that this reg has a ticket reserved
452
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
453
-        $ticket = $this->ticket();
454
-        $ticket->increaseSold();
455
-        // possibly set event status to sold out
456
-        $this->event()->perform_sold_out_status_check();
457
-    }
458
-
459
-
460
-    /**
461
-     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
462
-     *
463
-     * @return void
464
-     * @throws DomainException
465
-     * @throws EE_Error
466
-     * @throws EntityNotFoundException
467
-     * @throws InvalidArgumentException
468
-     * @throws InvalidDataTypeException
469
-     * @throws InvalidInterfaceException
470
-     * @throws ReflectionException
471
-     * @throws UnexpectedEntityException
472
-     */
473
-    private function releaseRegistrationSpace()
474
-    {
475
-        $ticket = $this->ticket();
476
-        $ticket->decreaseSold();
477
-        // possibly change event status from sold out back to previous status
478
-        $this->event()->perform_sold_out_status_check();
479
-    }
480
-
481
-
482
-    /**
483
-     * tracks this registration's ticket reservation in extra meta
484
-     * and can increment related ticket reserved and corresponding datetime reserved values
485
-     *
486
-     * @param bool $update_ticket if true, will increment ticket and datetime reserved count
487
-     * @return void
488
-     * @throws EE_Error
489
-     * @throws InvalidArgumentException
490
-     * @throws InvalidDataTypeException
491
-     * @throws InvalidInterfaceException
492
-     * @throws ReflectionException
493
-     */
494
-    public function reserve_ticket($update_ticket = false, $source = 'unknown')
495
-    {
496
-        // only reserve ticket if space is not currently reserved
497
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
498
-            $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
499
-            // IMPORTANT !!!
500
-            // although checking $update_ticket first would be more efficient,
501
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
502
-            if (
503
-                $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
504
-                && $update_ticket
505
-            ) {
506
-                $ticket = $this->ticket();
507
-                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
508
-                $ticket->save();
509
-            }
510
-        }
511
-    }
512
-
513
-
514
-    /**
515
-     * stops tracking this registration's ticket reservation in extra meta
516
-     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
517
-     *
518
-     * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
519
-     * @return void
520
-     * @throws EE_Error
521
-     * @throws InvalidArgumentException
522
-     * @throws InvalidDataTypeException
523
-     * @throws InvalidInterfaceException
524
-     * @throws ReflectionException
525
-     */
526
-    public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
527
-    {
528
-        // only release ticket if space is currently reserved
529
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
530
-            $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
531
-            // IMPORTANT !!!
532
-            // although checking $update_ticket first would be more efficient,
533
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
534
-            if (
535
-                $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
536
-                && $update_ticket
537
-            ) {
538
-                $ticket = $this->ticket();
539
-                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
540
-            }
541
-        }
542
-    }
543
-
544
-
545
-    /**
546
-     * Set Attendee ID
547
-     *
548
-     * @param        int $ATT_ID Attendee ID
549
-     * @throws EE_Error
550
-     * @throws RuntimeException
551
-     */
552
-    public function set_attendee_id($ATT_ID = 0)
553
-    {
554
-        $this->set('ATT_ID', $ATT_ID);
555
-    }
556
-
557
-
558
-    /**
559
-     *        Set Transaction ID
560
-     *
561
-     * @param        int $TXN_ID Transaction ID
562
-     * @throws EE_Error
563
-     * @throws RuntimeException
564
-     */
565
-    public function set_transaction_id($TXN_ID = 0)
566
-    {
567
-        $this->set('TXN_ID', $TXN_ID);
568
-    }
569
-
570
-
571
-    /**
572
-     *        Set Session
573
-     *
574
-     * @param    string $REG_session PHP Session ID
575
-     * @throws EE_Error
576
-     * @throws RuntimeException
577
-     */
578
-    public function set_session($REG_session = '')
579
-    {
580
-        $this->set('REG_session', $REG_session);
581
-    }
582
-
583
-
584
-    /**
585
-     *        Set Registration URL Link
586
-     *
587
-     * @param    string $REG_url_link Registration URL Link
588
-     * @throws EE_Error
589
-     * @throws RuntimeException
590
-     */
591
-    public function set_reg_url_link($REG_url_link = '')
592
-    {
593
-        $this->set('REG_url_link', $REG_url_link);
594
-    }
595
-
596
-
597
-    /**
598
-     *        Set Attendee Counter
599
-     *
600
-     * @param        int $REG_count Primary Attendee
601
-     * @throws EE_Error
602
-     * @throws RuntimeException
603
-     */
604
-    public function set_count($REG_count = 1)
605
-    {
606
-        $this->set('REG_count', $REG_count);
607
-    }
608
-
609
-
610
-    /**
611
-     *        Set Group Size
612
-     *
613
-     * @param        boolean $REG_group_size Group Registration
614
-     * @throws EE_Error
615
-     * @throws RuntimeException
616
-     */
617
-    public function set_group_size($REG_group_size = false)
618
-    {
619
-        $this->set('REG_group_size', $REG_group_size);
620
-    }
621
-
622
-
623
-    /**
624
-     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
625
-     *    EEM_Registration::status_id_not_approved
626
-     *
627
-     * @return        boolean
628
-     */
629
-    public function is_not_approved()
630
-    {
631
-        return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
632
-    }
633
-
634
-
635
-    /**
636
-     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
637
-     *    EEM_Registration::status_id_pending_payment
638
-     *
639
-     * @return        boolean
640
-     */
641
-    public function is_pending_payment()
642
-    {
643
-        return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
644
-    }
645
-
646
-
647
-    /**
648
-     *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
649
-     *
650
-     * @return        boolean
651
-     */
652
-    public function is_approved()
653
-    {
654
-        return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
655
-    }
656
-
657
-
658
-    /**
659
-     *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
660
-     *
661
-     * @return        boolean
662
-     */
663
-    public function is_cancelled()
664
-    {
665
-        return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
666
-    }
667
-
668
-
669
-    /**
670
-     *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
671
-     *
672
-     * @return        boolean
673
-     */
674
-    public function is_declined()
675
-    {
676
-        return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
677
-    }
678
-
679
-
680
-    /**
681
-     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
682
-     *    EEM_Registration::status_id_incomplete
683
-     *
684
-     * @return        boolean
685
-     */
686
-    public function is_incomplete()
687
-    {
688
-        return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
689
-    }
690
-
691
-
692
-    /**
693
-     *        Set Registration Date
694
-     *
695
-     * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
696
-     *                                                 Date
697
-     * @throws EE_Error
698
-     * @throws RuntimeException
699
-     */
700
-    public function set_reg_date($REG_date = false)
701
-    {
702
-        $this->set('REG_date', $REG_date);
703
-    }
704
-
705
-
706
-    /**
707
-     *    Set final price owing for this registration after all ticket/price modifications
708
-     *
709
-     * @access    public
710
-     * @param    float $REG_final_price
711
-     * @throws EE_Error
712
-     * @throws RuntimeException
713
-     */
714
-    public function set_final_price($REG_final_price = 0.00)
715
-    {
716
-        $this->set('REG_final_price', $REG_final_price);
717
-    }
718
-
719
-
720
-    /**
721
-     *    Set amount paid towards this registration's final price
722
-     *
723
-     * @access    public
724
-     * @param    float $REG_paid
725
-     * @throws EE_Error
726
-     * @throws RuntimeException
727
-     */
728
-    public function set_paid($REG_paid = 0.00)
729
-    {
730
-        $this->set('REG_paid', $REG_paid);
731
-    }
732
-
733
-
734
-    /**
735
-     *        Attendee Is Going
736
-     *
737
-     * @param        boolean $REG_att_is_going Attendee Is Going
738
-     * @throws EE_Error
739
-     * @throws RuntimeException
740
-     */
741
-    public function set_att_is_going($REG_att_is_going = false)
742
-    {
743
-        $this->set('REG_att_is_going', $REG_att_is_going);
744
-    }
745
-
746
-
747
-    /**
748
-     * Gets the related attendee
749
-     *
750
-     * @return EE_Attendee
751
-     * @throws EE_Error
752
-     */
753
-    public function attendee()
754
-    {
755
-        return $this->get_first_related('Attendee');
756
-    }
757
-
758
-    /**
759
-     * Gets the name of the attendee.
760
-     * @since 4.10.12.p
761
-     * @param bool $apply_html_entities set to true if you want to use HTML entities.
762
-     * @return string
763
-     * @throws EE_Error
764
-     * @throws InvalidArgumentException
765
-     * @throws InvalidDataTypeException
766
-     * @throws InvalidInterfaceException
767
-     * @throws ReflectionException
768
-     */
769
-    public function attendeeName($apply_html_entities = false)
770
-    {
771
-        $attendee = $this->get_first_related('Attendee');
772
-        if ($attendee instanceof EE_Attendee) {
773
-            $attendee_name = $attendee->full_name($apply_html_entities);
774
-        } else {
775
-            $attendee_name = esc_html__('Unknown', 'event_espresso');
776
-        }
777
-        return $attendee_name;
778
-    }
779
-
780
-
781
-    /**
782
-     *        get Event ID
783
-     */
784
-    public function event_ID()
785
-    {
786
-        return $this->get('EVT_ID');
787
-    }
788
-
789
-
790
-    /**
791
-     *        get Event ID
792
-     */
793
-    public function event_name()
794
-    {
795
-        $event = $this->event_obj();
796
-        if ($event) {
797
-            return $event->name();
798
-        } else {
799
-            return null;
800
-        }
801
-    }
802
-
803
-
804
-    /**
805
-     * Fetches the event this registration is for
806
-     *
807
-     * @return EE_Event
808
-     * @throws EE_Error
809
-     */
810
-    public function event_obj()
811
-    {
812
-        return $this->get_first_related('Event');
813
-    }
814
-
815
-
816
-    /**
817
-     *        get Attendee ID
818
-     */
819
-    public function attendee_ID()
820
-    {
821
-        return $this->get('ATT_ID');
822
-    }
823
-
824
-
825
-    /**
826
-     *        get PHP Session ID
827
-     */
828
-    public function session_ID()
829
-    {
830
-        return $this->get('REG_session');
831
-    }
832
-
833
-
834
-    /**
835
-     * Gets the string which represents the URL trigger for the receipt template in the message template system.
836
-     *
837
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
838
-     * @return string
839
-     */
840
-    public function receipt_url($messenger = 'html')
841
-    {
842
-
843
-        /**
844
-         * The below will be deprecated one version after this.  We check first if there is a custom receipt template
845
-         * already in use on old system.  If there is then we just return the standard url for it.
846
-         *
847
-         * @since 4.5.0
848
-         */
849
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
850
-        $has_custom = EEH_Template::locate_template(
851
-            $template_relative_path,
852
-            array(),
853
-            true,
854
-            true,
855
-            true
856
-        );
857
-
858
-        if ($has_custom) {
859
-            return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
860
-        }
861
-        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
862
-    }
863
-
864
-
865
-    /**
866
-     * Gets the string which represents the URL trigger for the invoice template in the message template system.
867
-     *
868
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
869
-     * @return string
870
-     * @throws EE_Error
871
-     */
872
-    public function invoice_url($messenger = 'html')
873
-    {
874
-        /**
875
-         * The below will be deprecated one version after this.  We check first if there is a custom invoice template
876
-         * already in use on old system.  If there is then we just return the standard url for it.
877
-         *
878
-         * @since 4.5.0
879
-         */
880
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
881
-        $has_custom = EEH_Template::locate_template(
882
-            $template_relative_path,
883
-            array(),
884
-            true,
885
-            true,
886
-            true
887
-        );
888
-
889
-        if ($has_custom) {
890
-            if ($messenger == 'html') {
891
-                return $this->invoice_url('launch');
892
-            }
893
-            $route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
894
-
895
-            $query_args = array('ee' => $route, 'id' => $this->reg_url_link());
896
-            if ($messenger == 'html') {
897
-                $query_args['html'] = true;
898
-            }
899
-            return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
900
-        }
901
-        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
902
-    }
903
-
904
-
905
-    /**
906
-     * get Registration URL Link
907
-     *
908
-     * @access public
909
-     * @return string
910
-     * @throws EE_Error
911
-     */
912
-    public function reg_url_link()
913
-    {
914
-        return (string) $this->get('REG_url_link');
915
-    }
916
-
917
-
918
-    /**
919
-     * Echoes out invoice_url()
920
-     *
921
-     * @param string $type 'download','launch', or 'html' (default is 'launch')
922
-     * @return void
923
-     * @throws EE_Error
924
-     */
925
-    public function e_invoice_url($type = 'launch')
926
-    {
927
-        echo esc_url_raw($this->invoice_url($type));
928
-    }
929
-
930
-
931
-    /**
932
-     * Echoes out payment_overview_url
933
-     */
934
-    public function e_payment_overview_url()
935
-    {
936
-        echo esc_url_raw($this->payment_overview_url());
937
-    }
938
-
939
-
940
-    /**
941
-     * Gets the URL for the checkout payment options reg step
942
-     * with this registration's REG_url_link added as a query parameter
943
-     *
944
-     * @param bool $clear_session Set to true when you want to clear the session on revisiting the
945
-     *                            payment overview url.
946
-     * @return string
947
-     * @throws InvalidInterfaceException
948
-     * @throws InvalidDataTypeException
949
-     * @throws EE_Error
950
-     * @throws InvalidArgumentException
951
-     */
952
-    public function payment_overview_url($clear_session = false)
953
-    {
954
-        return add_query_arg(
955
-            (array) apply_filters(
956
-                'FHEE__EE_Registration__payment_overview_url__query_args',
957
-                array(
958
-                    'e_reg_url_link' => $this->reg_url_link(),
959
-                    'step'           => 'payment_options',
960
-                    'revisit'        => true,
961
-                    'clear_session'  => (bool) $clear_session,
962
-                ),
963
-                $this
964
-            ),
965
-            EE_Registry::instance()->CFG->core->reg_page_url()
966
-        );
967
-    }
968
-
969
-
970
-    /**
971
-     * Gets the URL for the checkout attendee information reg step
972
-     * with this registration's REG_url_link added as a query parameter
973
-     *
974
-     * @return string
975
-     * @throws InvalidInterfaceException
976
-     * @throws InvalidDataTypeException
977
-     * @throws EE_Error
978
-     * @throws InvalidArgumentException
979
-     */
980
-    public function edit_attendee_information_url()
981
-    {
982
-        return add_query_arg(
983
-            (array) apply_filters(
984
-                'FHEE__EE_Registration__edit_attendee_information_url__query_args',
985
-                array(
986
-                    'e_reg_url_link' => $this->reg_url_link(),
987
-                    'step'           => 'attendee_information',
988
-                    'revisit'        => true,
989
-                ),
990
-                $this
991
-            ),
992
-            EE_Registry::instance()->CFG->core->reg_page_url()
993
-        );
994
-    }
995
-
996
-
997
-    /**
998
-     * Simply generates and returns the appropriate admin_url link to edit this registration
999
-     *
1000
-     * @return string
1001
-     * @throws EE_Error
1002
-     */
1003
-    public function get_admin_edit_url()
1004
-    {
1005
-        return EEH_URL::add_query_args_and_nonce(
1006
-            array(
1007
-                'page'    => 'espresso_registrations',
1008
-                'action'  => 'view_registration',
1009
-                '_REG_ID' => $this->ID(),
1010
-            ),
1011
-            admin_url('admin.php')
1012
-        );
1013
-    }
1014
-
1015
-
1016
-    /**
1017
-     *    is_primary_registrant?
1018
-     */
1019
-    public function is_primary_registrant()
1020
-    {
1021
-        return $this->get('REG_count') === 1 ? true : false;
1022
-    }
1023
-
1024
-
1025
-    /**
1026
-     * This returns the primary registration object for this registration group (which may be this object).
1027
-     *
1028
-     * @return EE_Registration
1029
-     * @throws EE_Error
1030
-     */
1031
-    public function get_primary_registration()
1032
-    {
1033
-        if ($this->is_primary_registrant()) {
1034
-            return $this;
1035
-        }
1036
-
1037
-        // k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1038
-        /** @var EE_Registration $primary_registrant */
1039
-        $primary_registrant = EEM_Registration::instance()->get_one(
1040
-            array(
1041
-                array(
1042
-                    'TXN_ID'    => $this->transaction_ID(),
1043
-                    'REG_count' => 1,
1044
-                ),
1045
-            )
1046
-        );
1047
-        return $primary_registrant;
1048
-    }
1049
-
1050
-
1051
-    /**
1052
-     *        get  Attendee Number
1053
-     *
1054
-     * @access        public
1055
-     */
1056
-    public function count()
1057
-    {
1058
-        return $this->get('REG_count');
1059
-    }
1060
-
1061
-
1062
-    /**
1063
-     *        get Group Size
1064
-     */
1065
-    public function group_size()
1066
-    {
1067
-        return $this->get('REG_group_size');
1068
-    }
1069
-
1070
-
1071
-    /**
1072
-     *        get Registration Date
1073
-     */
1074
-    public function date()
1075
-    {
1076
-        return $this->get('REG_date');
1077
-    }
1078
-
1079
-
1080
-    /**
1081
-     * gets a pretty date
1082
-     *
1083
-     * @param string $date_format
1084
-     * @param string $time_format
1085
-     * @return string
1086
-     * @throws EE_Error
1087
-     */
1088
-    public function pretty_date($date_format = null, $time_format = null)
1089
-    {
1090
-        return $this->get_datetime('REG_date', $date_format, $time_format);
1091
-    }
1092
-
1093
-
1094
-    /**
1095
-     * final_price
1096
-     * the registration's share of the transaction total, so that the
1097
-     * sum of all the transaction's REG_final_prices equal the transaction's total
1098
-     *
1099
-     * @return float
1100
-     * @throws EE_Error
1101
-     */
1102
-    public function final_price()
1103
-    {
1104
-        return $this->get('REG_final_price');
1105
-    }
1106
-
1107
-
1108
-    /**
1109
-     * pretty_final_price
1110
-     *  final price as formatted string, with correct decimal places and currency symbol
1111
-     *
1112
-     * @return string
1113
-     * @throws EE_Error
1114
-     */
1115
-    public function pretty_final_price()
1116
-    {
1117
-        return $this->get_pretty('REG_final_price');
1118
-    }
1119
-
1120
-
1121
-    /**
1122
-     * get paid (yeah)
1123
-     *
1124
-     * @return float
1125
-     * @throws EE_Error
1126
-     */
1127
-    public function paid()
1128
-    {
1129
-        return $this->get('REG_paid');
1130
-    }
1131
-
1132
-
1133
-    /**
1134
-     * pretty_paid
1135
-     *
1136
-     * @return float
1137
-     * @throws EE_Error
1138
-     */
1139
-    public function pretty_paid()
1140
-    {
1141
-        return $this->get_pretty('REG_paid');
1142
-    }
1143
-
1144
-
1145
-    /**
1146
-     * owes_monies_and_can_pay
1147
-     * whether or not this registration has monies owing and it's' status allows payment
1148
-     *
1149
-     * @param array $requires_payment
1150
-     * @return bool
1151
-     * @throws EE_Error
1152
-     */
1153
-    public function owes_monies_and_can_pay($requires_payment = array())
1154
-    {
1155
-        // these reg statuses require payment (if event is not free)
1156
-        $requires_payment = ! empty($requires_payment)
1157
-            ? $requires_payment
1158
-            : EEM_Registration::reg_statuses_that_allow_payment();
1159
-        if (
1160
-            in_array($this->status_ID(), $requires_payment) &&
1161
-            $this->final_price() != 0 &&
1162
-            $this->final_price() != $this->paid()
1163
-        ) {
1164
-            return true;
1165
-        } else {
1166
-            return false;
1167
-        }
1168
-    }
1169
-
1170
-
1171
-    /**
1172
-     * Prints out the return value of $this->pretty_status()
1173
-     *
1174
-     * @param bool $show_icons
1175
-     * @return void
1176
-     * @throws EE_Error
1177
-     */
1178
-    public function e_pretty_status($show_icons = false)
1179
-    {
1180
-        echo $this->pretty_status($show_icons); // already escaped
1181
-    }
1182
-
1183
-
1184
-    /**
1185
-     * Returns a nice version of the status for displaying to customers
1186
-     *
1187
-     * @param bool $show_icons
1188
-     * @return string
1189
-     * @throws EE_Error
1190
-     */
1191
-    public function pretty_status($show_icons = false)
1192
-    {
1193
-        $status = EEM_Status::instance()->localized_status(
1194
-            array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1195
-            false,
1196
-            'sentence'
1197
-        );
1198
-        $icon = '';
1199
-        switch ($this->status_ID()) {
1200
-            case EEM_Registration::status_id_approved:
1201
-                $icon = $show_icons
1202
-                    ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1203
-                    : '';
1204
-                break;
1205
-            case EEM_Registration::status_id_pending_payment:
1206
-                $icon = $show_icons
1207
-                    ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1208
-                    : '';
1209
-                break;
1210
-            case EEM_Registration::status_id_not_approved:
1211
-                $icon = $show_icons
1212
-                    ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1213
-                    : '';
1214
-                break;
1215
-            case EEM_Registration::status_id_cancelled:
1216
-                $icon = $show_icons
1217
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1218
-                    : '';
1219
-                break;
1220
-            case EEM_Registration::status_id_incomplete:
1221
-                $icon = $show_icons
1222
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1223
-                    : '';
1224
-                break;
1225
-            case EEM_Registration::status_id_declined:
1226
-                $icon = $show_icons
1227
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1228
-                    : '';
1229
-                break;
1230
-            case EEM_Registration::status_id_wait_list:
1231
-                $icon = $show_icons
1232
-                    ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1233
-                    : '';
1234
-                break;
1235
-        }
1236
-        return $icon . $status[ $this->status_ID() ];
1237
-    }
1238
-
1239
-
1240
-    /**
1241
-     *        get Attendee Is Going
1242
-     */
1243
-    public function att_is_going()
1244
-    {
1245
-        return $this->get('REG_att_is_going');
1246
-    }
1247
-
1248
-
1249
-    /**
1250
-     * Gets related answers
1251
-     *
1252
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1253
-     * @return EE_Answer[]
1254
-     * @throws EE_Error
1255
-     */
1256
-    public function answers($query_params = null)
1257
-    {
1258
-        return $this->get_many_related('Answer', $query_params);
1259
-    }
1260
-
1261
-
1262
-    /**
1263
-     * Gets the registration's answer value to the specified question
1264
-     * (either the question's ID or a question object)
1265
-     *
1266
-     * @param EE_Question|int $question
1267
-     * @param bool            $pretty_value
1268
-     * @return array|string if pretty_value= true, the result will always be a string
1269
-     * (because the answer might be an array of answer values, so passing pretty_value=true
1270
-     * will convert it into some kind of string)
1271
-     * @throws EE_Error
1272
-     */
1273
-    public function answer_value_to_question($question, $pretty_value = true)
1274
-    {
1275
-        $question_id = EEM_Question::instance()->ensure_is_ID($question);
1276
-        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1277
-    }
1278
-
1279
-
1280
-    /**
1281
-     * question_groups
1282
-     * returns an array of EE_Question_Group objects for this registration
1283
-     *
1284
-     * @return EE_Question_Group[]
1285
-     * @throws EE_Error
1286
-     * @throws InvalidArgumentException
1287
-     * @throws InvalidDataTypeException
1288
-     * @throws InvalidInterfaceException
1289
-     * @throws ReflectionException
1290
-     */
1291
-    public function question_groups()
1292
-    {
1293
-        return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1294
-    }
1295
-
1296
-
1297
-    /**
1298
-     * count_question_groups
1299
-     * returns a count of the number of EE_Question_Group objects for this registration
1300
-     *
1301
-     * @return int
1302
-     * @throws EE_Error
1303
-     * @throws EntityNotFoundException
1304
-     * @throws InvalidArgumentException
1305
-     * @throws InvalidDataTypeException
1306
-     * @throws InvalidInterfaceException
1307
-     * @throws ReflectionException
1308
-     */
1309
-    public function count_question_groups()
1310
-    {
1311
-        return EEM_Event::instance()->count_related(
1312
-            $this->event_ID(),
1313
-            'Question_Group',
1314
-            [
1315
-                [
1316
-                    'Event_Question_Group.'
1317
-                    . EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1318
-                ]
1319
-            ]
1320
-        );
1321
-    }
1322
-
1323
-
1324
-    /**
1325
-     * Returns the registration date in the 'standard' string format
1326
-     * (function may be improved in the future to allow for different formats and timezones)
1327
-     *
1328
-     * @return string
1329
-     * @throws EE_Error
1330
-     */
1331
-    public function reg_date()
1332
-    {
1333
-        return $this->get_datetime('REG_date');
1334
-    }
1335
-
1336
-
1337
-    /**
1338
-     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1339
-     * the ticket this registration purchased, or the datetime they have registered
1340
-     * to attend)
1341
-     *
1342
-     * @return EE_Datetime_Ticket
1343
-     * @throws EE_Error
1344
-     */
1345
-    public function datetime_ticket()
1346
-    {
1347
-        return $this->get_first_related('Datetime_Ticket');
1348
-    }
1349
-
1350
-
1351
-    /**
1352
-     * Sets the registration's datetime_ticket.
1353
-     *
1354
-     * @param EE_Datetime_Ticket $datetime_ticket
1355
-     * @return EE_Datetime_Ticket
1356
-     * @throws EE_Error
1357
-     */
1358
-    public function set_datetime_ticket($datetime_ticket)
1359
-    {
1360
-        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1361
-    }
1362
-
1363
-    /**
1364
-     * Gets deleted
1365
-     *
1366
-     * @return bool
1367
-     * @throws EE_Error
1368
-     */
1369
-    public function deleted()
1370
-    {
1371
-        return $this->get('REG_deleted');
1372
-    }
1373
-
1374
-    /**
1375
-     * Sets deleted
1376
-     *
1377
-     * @param boolean $deleted
1378
-     * @return bool
1379
-     * @throws EE_Error
1380
-     * @throws RuntimeException
1381
-     */
1382
-    public function set_deleted($deleted)
1383
-    {
1384
-        if ($deleted) {
1385
-            $this->delete();
1386
-        } else {
1387
-            $this->restore();
1388
-        }
1389
-    }
1390
-
1391
-
1392
-    /**
1393
-     * Get the status object of this object
1394
-     *
1395
-     * @return EE_Status
1396
-     * @throws EE_Error
1397
-     */
1398
-    public function status_obj()
1399
-    {
1400
-        return $this->get_first_related('Status');
1401
-    }
1402
-
1403
-
1404
-    /**
1405
-     * Returns the number of times this registration has checked into any of the datetimes
1406
-     * its available for
1407
-     *
1408
-     * @return int
1409
-     * @throws EE_Error
1410
-     */
1411
-    public function count_checkins()
1412
-    {
1413
-        return $this->get_model()->count_related($this, 'Checkin');
1414
-    }
1415
-
1416
-
1417
-    /**
1418
-     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1419
-     * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1420
-     *
1421
-     * @return int
1422
-     * @throws EE_Error
1423
-     */
1424
-    public function count_checkins_not_checkedout()
1425
-    {
1426
-        return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1427
-    }
1428
-
1429
-
1430
-    /**
1431
-     * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1432
-     *
1433
-     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1434
-     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1435
-     *                                          consider registration status as well as datetime access.
1436
-     * @return bool
1437
-     * @throws EE_Error
1438
-     */
1439
-    public function can_checkin($DTT_OR_ID, $check_approved = true)
1440
-    {
1441
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1442
-
1443
-        // first check registration status
1444
-        if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1445
-            return false;
1446
-        }
1447
-        // is there a datetime ticket that matches this dtt_ID?
1448
-        if (
1449
-            ! (EEM_Datetime_Ticket::instance()->exists(
1450
-                array(
1451
-                array(
1452
-                    'TKT_ID' => $this->get('TKT_ID'),
1453
-                    'DTT_ID' => $DTT_ID,
1454
-                ),
1455
-                )
1456
-            ))
1457
-        ) {
1458
-            return false;
1459
-        }
1460
-
1461
-        // final check is against TKT_uses
1462
-        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1463
-    }
1464
-
1465
-
1466
-    /**
1467
-     * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1468
-     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1469
-     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1470
-     * then return false.  Otherwise return true.
1471
-     *
1472
-     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1473
-     * @return bool true means can checkin.  false means cannot checkin.
1474
-     * @throws EE_Error
1475
-     */
1476
-    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1477
-    {
1478
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1479
-
1480
-        if (! $DTT_ID) {
1481
-            return false;
1482
-        }
1483
-
1484
-        $max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1485
-
1486
-        // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1487
-        // check-in or not.
1488
-        if (! $max_uses || $max_uses === EE_INF) {
1489
-            return true;
1490
-        }
1491
-
1492
-        // does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1493
-        // go ahead and toggle.
1494
-        if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1495
-            return true;
1496
-        }
1497
-
1498
-        // made it here so the last check is whether the number of checkins per unique datetime on this registration
1499
-        // disallows further check-ins.
1500
-        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1501
-            array(
1502
-                array(
1503
-                    'REG_ID' => $this->ID(),
1504
-                    'CHK_in' => true,
1505
-                ),
1506
-            ),
1507
-            'DTT_ID',
1508
-            true
1509
-        );
1510
-        // checkins have already reached their max number of uses
1511
-        // so registrant can NOT checkin
1512
-        if ($count_unique_dtt_checkins >= $max_uses) {
1513
-            EE_Error::add_error(
1514
-                esc_html__(
1515
-                    'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1516
-                    'event_espresso'
1517
-                ),
1518
-                __FILE__,
1519
-                __FUNCTION__,
1520
-                __LINE__
1521
-            );
1522
-            return false;
1523
-        }
1524
-        return true;
1525
-    }
1526
-
1527
-
1528
-    /**
1529
-     * toggle Check-in status for this registration
1530
-     * Check-ins are toggled in the following order:
1531
-     * never checked in -> checked in
1532
-     * checked in -> checked out
1533
-     * checked out -> checked in
1534
-     *
1535
-     * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1536
-     *                      If not included or null, then it is assumed latest datetime is being toggled.
1537
-     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1538
-     *                      can be checked in or not.  Otherwise this forces change in checkin status.
1539
-     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1540
-     * @throws EE_Error
1541
-     */
1542
-    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1543
-    {
1544
-        if (empty($DTT_ID)) {
1545
-            $datetime = $this->get_latest_related_datetime();
1546
-            $DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1547
-            // verify the registration can checkin for the given DTT_ID
1548
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1549
-            EE_Error::add_error(
1550
-                sprintf(
1551
-                    esc_html__(
1552
-                        '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',
1553
-                        'event_espresso'
1554
-                    ),
1555
-                    $this->ID(),
1556
-                    $DTT_ID
1557
-                ),
1558
-                __FILE__,
1559
-                __FUNCTION__,
1560
-                __LINE__
1561
-            );
1562
-            return false;
1563
-        }
1564
-        $status_paths = array(
1565
-            EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1566
-            EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1567
-            EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1568
-        );
1569
-        // start by getting the current status so we know what status we'll be changing to.
1570
-        $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1571
-        $status_to = $status_paths[ $cur_status ];
1572
-        // database only records true for checked IN or false for checked OUT
1573
-        // no record ( null ) means checked in NEVER, but we obviously don't save that
1574
-        $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1575
-        // add relation - note Check-ins are always creating new rows
1576
-        // because we are keeping track of Check-ins over time.
1577
-        // Eventually we'll probably want to show a list table
1578
-        // for the individual Check-ins so that they can be managed.
1579
-        $checkin = EE_Checkin::new_instance(
1580
-            array(
1581
-                'REG_ID' => $this->ID(),
1582
-                'DTT_ID' => $DTT_ID,
1583
-                'CHK_in' => $new_status,
1584
-            )
1585
-        );
1586
-        // if the record could not be saved then return false
1587
-        if ($checkin->save() === 0) {
1588
-            if (WP_DEBUG) {
1589
-                global $wpdb;
1590
-                $error = sprintf(
1591
-                    esc_html__(
1592
-                        'Registration check in update failed because of the following database error: %1$s%2$s',
1593
-                        'event_espresso'
1594
-                    ),
1595
-                    '<br />',
1596
-                    $wpdb->last_error
1597
-                );
1598
-            } else {
1599
-                $error = esc_html__(
1600
-                    'Registration check in update failed because of an unknown database error',
1601
-                    'event_espresso'
1602
-                );
1603
-            }
1604
-            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1605
-            return false;
1606
-        }
1607
-        // Fire a checked_in and checkout_out action.
1608
-        $checked_status = $status_to === EE_Checkin::status_checked_in ? 'checked_in' : 'checked_out';
1609
-        do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1610
-        return $status_to;
1611
-    }
1612
-
1613
-
1614
-    /**
1615
-     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1616
-     * "Latest" is defined by the `DTT_EVT_start` column.
1617
-     *
1618
-     * @return EE_Datetime|null
1619
-     * @throws EE_Error
1620
-     */
1621
-    public function get_latest_related_datetime()
1622
-    {
1623
-        return EEM_Datetime::instance()->get_one(
1624
-            array(
1625
-                array(
1626
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1627
-                ),
1628
-                'order_by' => array('DTT_EVT_start' => 'DESC'),
1629
-            )
1630
-        );
1631
-    }
1632
-
1633
-
1634
-    /**
1635
-     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1636
-     * "Earliest" is defined by the `DTT_EVT_start` column.
1637
-     *
1638
-     * @throws EE_Error
1639
-     */
1640
-    public function get_earliest_related_datetime()
1641
-    {
1642
-        return EEM_Datetime::instance()->get_one(
1643
-            array(
1644
-                array(
1645
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1646
-                ),
1647
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
1648
-            )
1649
-        );
1650
-    }
1651
-
1652
-
1653
-    /**
1654
-     * This method simply returns the check-in status for this registration and the given datetime.
1655
-     * If neither the datetime nor the checkin values are provided as arguments,
1656
-     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1657
-     *
1658
-     * @param  int       $DTT_ID  The ID of the datetime we're checking against
1659
-     *                            (if empty we'll get the primary datetime for
1660
-     *                            this registration (via event) and use it's ID);
1661
-     * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1662
-     *
1663
-     * @return int                Integer representing Check-in status.
1664
-     * @throws EE_Error
1665
-     */
1666
-    public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1667
-    {
1668
-        $checkin_query_params = array(
1669
-            'order_by' => array('CHK_timestamp' => 'DESC'),
1670
-        );
1671
-
1672
-        if ($DTT_ID > 0) {
1673
-            $checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1674
-        }
1675
-
1676
-        // get checkin object (if exists)
1677
-        $checkin = $checkin instanceof EE_Checkin
1678
-            ? $checkin
1679
-            : $this->get_first_related('Checkin', $checkin_query_params);
1680
-        if ($checkin instanceof EE_Checkin) {
1681
-            if ($checkin->get('CHK_in')) {
1682
-                return EE_Checkin::status_checked_in; // checked in
1683
-            }
1684
-            return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1685
-        }
1686
-        return EE_Checkin::status_checked_never; // never been checked in
1687
-    }
1688
-
1689
-
1690
-    /**
1691
-     * This method returns a localized message for the toggled Check-in message.
1692
-     *
1693
-     * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1694
-     *                     then it is assumed Check-in for primary datetime was toggled.
1695
-     * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1696
-     *                     message can be customized with the attendee name.
1697
-     * @return string internationalized message
1698
-     * @throws EE_Error
1699
-     */
1700
-    public function get_checkin_msg($DTT_ID, $error = false)
1701
-    {
1702
-        // let's get the attendee first so we can include the name of the attendee
1703
-        $attendee = $this->get_first_related('Attendee');
1704
-        if ($attendee instanceof EE_Attendee) {
1705
-            if ($error) {
1706
-                return sprintf(esc_html__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1707
-            }
1708
-            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1709
-            // what is the status message going to be?
1710
-            switch ($cur_status) {
1711
-                case EE_Checkin::status_checked_never:
1712
-                    return sprintf(
1713
-                        esc_html__("%s has been removed from Check-in records", "event_espresso"),
1714
-                        $attendee->full_name()
1715
-                    );
1716
-                    break;
1717
-                case EE_Checkin::status_checked_in:
1718
-                    return sprintf(esc_html__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1719
-                    break;
1720
-                case EE_Checkin::status_checked_out:
1721
-                    return sprintf(esc_html__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1722
-                    break;
1723
-            }
1724
-        }
1725
-        return esc_html__("The check-in status could not be determined.", "event_espresso");
1726
-    }
1727
-
1728
-
1729
-    /**
1730
-     * Returns the related EE_Transaction to this registration
1731
-     *
1732
-     * @return EE_Transaction
1733
-     * @throws EE_Error
1734
-     * @throws EntityNotFoundException
1735
-     */
1736
-    public function transaction()
1737
-    {
1738
-        $transaction = $this->get_first_related('Transaction');
1739
-        if (! $transaction instanceof \EE_Transaction) {
1740
-            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1741
-        }
1742
-        return $transaction;
1743
-    }
1744
-
1745
-
1746
-    /**
1747
-     *        get Registration Code
1748
-     */
1749
-    public function reg_code()
1750
-    {
1751
-        return $this->get('REG_code');
1752
-    }
1753
-
1754
-
1755
-    /**
1756
-     *        get Transaction ID
1757
-     */
1758
-    public function transaction_ID()
1759
-    {
1760
-        return $this->get('TXN_ID');
1761
-    }
1762
-
1763
-
1764
-    /**
1765
-     * @return int
1766
-     * @throws EE_Error
1767
-     */
1768
-    public function ticket_ID()
1769
-    {
1770
-        return $this->get('TKT_ID');
1771
-    }
1772
-
1773
-
1774
-    /**
1775
-     *        Set Registration Code
1776
-     *
1777
-     * @access    public
1778
-     * @param    string  $REG_code Registration Code
1779
-     * @param    boolean $use_default
1780
-     * @throws EE_Error
1781
-     */
1782
-    public function set_reg_code($REG_code, $use_default = false)
1783
-    {
1784
-        if (empty($REG_code)) {
1785
-            EE_Error::add_error(
1786
-                esc_html__('REG_code can not be empty.', 'event_espresso'),
1787
-                __FILE__,
1788
-                __FUNCTION__,
1789
-                __LINE__
1790
-            );
1791
-            return;
1792
-        }
1793
-        if (! $this->reg_code()) {
1794
-            parent::set('REG_code', $REG_code, $use_default);
1795
-        } else {
1796
-            EE_Error::doing_it_wrong(
1797
-                __CLASS__ . '::' . __FUNCTION__,
1798
-                esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1799
-                '4.6.0'
1800
-            );
1801
-        }
1802
-    }
1803
-
1804
-
1805
-    /**
1806
-     * Returns all other registrations in the same group as this registrant who have the same ticket option.
1807
-     * Note, if you want to just get all registrations in the same transaction (group), use:
1808
-     *    $registration->transaction()->registrations();
1809
-     *
1810
-     * @since 4.5.0
1811
-     * @return EE_Registration[] or empty array if this isn't a group registration.
1812
-     * @throws EE_Error
1813
-     */
1814
-    public function get_all_other_registrations_in_group()
1815
-    {
1816
-        if ($this->group_size() < 2) {
1817
-            return array();
1818
-        }
1819
-
1820
-        $query[0] = array(
1821
-            'TXN_ID' => $this->transaction_ID(),
1822
-            'REG_ID' => array('!=', $this->ID()),
1823
-            'TKT_ID' => $this->ticket_ID(),
1824
-        );
1825
-        /** @var EE_Registration[] $registrations */
1826
-        $registrations = $this->get_model()->get_all($query);
1827
-        return $registrations;
1828
-    }
1829
-
1830
-    /**
1831
-     * Return the link to the admin details for the object.
1832
-     *
1833
-     * @return string
1834
-     * @throws EE_Error
1835
-     */
1836
-    public function get_admin_details_link()
1837
-    {
1838
-        EE_Registry::instance()->load_helper('URL');
1839
-        return EEH_URL::add_query_args_and_nonce(
1840
-            array(
1841
-                'page'    => 'espresso_registrations',
1842
-                'action'  => 'view_registration',
1843
-                '_REG_ID' => $this->ID(),
1844
-            ),
1845
-            admin_url('admin.php')
1846
-        );
1847
-    }
1848
-
1849
-    /**
1850
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1851
-     *
1852
-     * @return string
1853
-     * @throws EE_Error
1854
-     */
1855
-    public function get_admin_edit_link()
1856
-    {
1857
-        return $this->get_admin_details_link();
1858
-    }
1859
-
1860
-    /**
1861
-     * Returns the link to a settings page for the object.
1862
-     *
1863
-     * @return string
1864
-     * @throws EE_Error
1865
-     */
1866
-    public function get_admin_settings_link()
1867
-    {
1868
-        return $this->get_admin_details_link();
1869
-    }
1870
-
1871
-    /**
1872
-     * Returns the link to the "overview" for the object (typically the "list table" view).
1873
-     *
1874
-     * @return string
1875
-     */
1876
-    public function get_admin_overview_link()
1877
-    {
1878
-        EE_Registry::instance()->load_helper('URL');
1879
-        return EEH_URL::add_query_args_and_nonce(
1880
-            array(
1881
-                'page' => 'espresso_registrations',
1882
-            ),
1883
-            admin_url('admin.php')
1884
-        );
1885
-    }
1886
-
1887
-
1888
-    /**
1889
-     * @param array $query_params
1890
-     *
1891
-     * @return \EE_Registration[]
1892
-     * @throws EE_Error
1893
-     */
1894
-    public function payments($query_params = array())
1895
-    {
1896
-        return $this->get_many_related('Payment', $query_params);
1897
-    }
1898
-
1899
-
1900
-    /**
1901
-     * @param array $query_params
1902
-     *
1903
-     * @return \EE_Registration_Payment[]
1904
-     * @throws EE_Error
1905
-     */
1906
-    public function registration_payments($query_params = array())
1907
-    {
1908
-        return $this->get_many_related('Registration_Payment', $query_params);
1909
-    }
1910
-
1911
-
1912
-    /**
1913
-     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1914
-     * Note: if there are no payments on the registration there will be no payment method returned.
1915
-     *
1916
-     * @return EE_Payment_Method|null
1917
-     */
1918
-    public function payment_method()
1919
-    {
1920
-        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1921
-    }
1922
-
1923
-
1924
-    /**
1925
-     * @return \EE_Line_Item
1926
-     * @throws EntityNotFoundException
1927
-     * @throws EE_Error
1928
-     */
1929
-    public function ticket_line_item()
1930
-    {
1931
-        $ticket = $this->ticket();
1932
-        $transaction = $this->transaction();
1933
-        $line_item = null;
1934
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1935
-            $transaction->total_line_item(),
1936
-            'Ticket',
1937
-            array($ticket->ID())
1938
-        );
1939
-        foreach ($ticket_line_items as $ticket_line_item) {
1940
-            if (
1941
-                $ticket_line_item instanceof \EE_Line_Item
1942
-                && $ticket_line_item->OBJ_type() === 'Ticket'
1943
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
1944
-            ) {
1945
-                $line_item = $ticket_line_item;
1946
-                break;
1947
-            }
1948
-        }
1949
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1950
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1951
-        }
1952
-        return $line_item;
1953
-    }
1954
-
1955
-
1956
-    /**
1957
-     * Soft Deletes this model object.
1958
-     *
1959
-     * @return boolean | int
1960
-     * @throws RuntimeException
1961
-     * @throws EE_Error
1962
-     */
1963
-    public function delete()
1964
-    {
1965
-        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1966
-            $this->set_status(EEM_Registration::status_id_cancelled);
1967
-        }
1968
-        return parent::delete();
1969
-    }
1970
-
1971
-
1972
-    /**
1973
-     * Restores whatever the previous status was on a registration before it was trashed (if possible)
1974
-     *
1975
-     * @throws EE_Error
1976
-     * @throws RuntimeException
1977
-     */
1978
-    public function restore()
1979
-    {
1980
-        $previous_status = $this->get_extra_meta(
1981
-            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1982
-            true,
1983
-            EEM_Registration::status_id_cancelled
1984
-        );
1985
-        if ($previous_status) {
1986
-            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1987
-            $this->set_status($previous_status);
1988
-        }
1989
-        return parent::restore();
1990
-    }
1991
-
1992
-
1993
-    /**
1994
-     * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1995
-     *
1996
-     * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1997
-     *                                           depending on whether the reg status changes to or from "Approved"
1998
-     * @return boolean whether the Registration status was updated
1999
-     * @throws EE_Error
2000
-     * @throws RuntimeException
2001
-     */
2002
-    public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
2003
-    {
2004
-        $paid = $this->paid();
2005
-        $price = $this->final_price();
2006
-        switch (true) {
2007
-            // overpaid or paid
2008
-            case EEH_Money::compare_floats($paid, $price, '>'):
2009
-            case EEH_Money::compare_floats($paid, $price):
2010
-                $new_status = EEM_Registration::status_id_approved;
2011
-                break;
2012
-            //  underpaid
2013
-            case EEH_Money::compare_floats($paid, $price, '<'):
2014
-                $new_status = EEM_Registration::status_id_pending_payment;
2015
-                break;
2016
-            // uhhh Houston...
2017
-            default:
2018
-                throw new RuntimeException(
2019
-                    esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2020
-                );
2021
-        }
2022
-        if ($new_status !== $this->status_ID()) {
2023
-            if ($trigger_set_status_logic) {
2024
-                return $this->set_status($new_status);
2025
-            }
2026
-            parent::set('STS_ID', $new_status);
2027
-            return true;
2028
-        }
2029
-        return false;
2030
-    }
2031
-
2032
-
2033
-    /*************************** DEPRECATED ***************************/
2034
-
2035
-
2036
-    /**
2037
-     * @deprecated
2038
-     * @since     4.7.0
2039
-     * @access    public
2040
-     */
2041
-    public function price_paid()
2042
-    {
2043
-        EE_Error::doing_it_wrong(
2044
-            'EE_Registration::price_paid()',
2045
-            esc_html__(
2046
-                'This method is deprecated, please use EE_Registration::final_price() instead.',
2047
-                'event_espresso'
2048
-            ),
2049
-            '4.7.0'
2050
-        );
2051
-        return $this->final_price();
2052
-    }
2053
-
2054
-
2055
-    /**
2056
-     * @deprecated
2057
-     * @since     4.7.0
2058
-     * @access    public
2059
-     * @param    float $REG_final_price
2060
-     * @throws EE_Error
2061
-     * @throws RuntimeException
2062
-     */
2063
-    public function set_price_paid($REG_final_price = 0.00)
2064
-    {
2065
-        EE_Error::doing_it_wrong(
2066
-            'EE_Registration::set_price_paid()',
2067
-            esc_html__(
2068
-                'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2069
-                'event_espresso'
2070
-            ),
2071
-            '4.7.0'
2072
-        );
2073
-        $this->set_final_price($REG_final_price);
2074
-    }
2075
-
2076
-
2077
-    /**
2078
-     * @deprecated
2079
-     * @since 4.7.0
2080
-     * @return string
2081
-     * @throws EE_Error
2082
-     */
2083
-    public function pretty_price_paid()
2084
-    {
2085
-        EE_Error::doing_it_wrong(
2086
-            'EE_Registration::pretty_price_paid()',
2087
-            esc_html__(
2088
-                'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2089
-                'event_espresso'
2090
-            ),
2091
-            '4.7.0'
2092
-        );
2093
-        return $this->pretty_final_price();
2094
-    }
2095
-
2096
-
2097
-    /**
2098
-     * Gets the primary datetime related to this registration via the related Event to this registration
2099
-     *
2100
-     * @deprecated 4.9.17
2101
-     * @return EE_Datetime
2102
-     * @throws EE_Error
2103
-     * @throws EntityNotFoundException
2104
-     */
2105
-    public function get_related_primary_datetime()
2106
-    {
2107
-        EE_Error::doing_it_wrong(
2108
-            __METHOD__,
2109
-            esc_html__(
2110
-                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2111
-                'event_espresso'
2112
-            ),
2113
-            '4.9.17',
2114
-            '5.0.0'
2115
-        );
2116
-        return $this->event()->primary_datetime();
2117
-    }
2118
-
2119
-    /**
2120
-     * Returns the contact's name (or "Unknown" if there is no contact.)
2121
-     * @since 4.10.12.p
2122
-     * @return string
2123
-     * @throws EE_Error
2124
-     * @throws InvalidArgumentException
2125
-     * @throws InvalidDataTypeException
2126
-     * @throws InvalidInterfaceException
2127
-     * @throws ReflectionException
2128
-     */
2129
-    public function name()
2130
-    {
2131
-        return $this->attendeeName();
2132
-    }
20
+	/**
21
+	 * Used to reference when a registration has never been checked in.
22
+	 *
23
+	 * @deprecated use \EE_Checkin::status_checked_never instead
24
+	 * @type int
25
+	 */
26
+	const checkin_status_never = 2;
27
+
28
+	/**
29
+	 * Used to reference when a registration has been checked in.
30
+	 *
31
+	 * @deprecated use \EE_Checkin::status_checked_in instead
32
+	 * @type int
33
+	 */
34
+	const checkin_status_in = 1;
35
+
36
+
37
+	/**
38
+	 * Used to reference when a registration has been checked out.
39
+	 *
40
+	 * @deprecated use \EE_Checkin::status_checked_out instead
41
+	 * @type int
42
+	 */
43
+	const checkin_status_out = 0;
44
+
45
+
46
+	/**
47
+	 * extra meta key for tracking reg status os trashed registrations
48
+	 *
49
+	 * @type string
50
+	 */
51
+	const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
+
53
+
54
+	/**
55
+	 * extra meta key for tracking if registration has reserved ticket
56
+	 *
57
+	 * @type string
58
+	 */
59
+	const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
60
+
61
+
62
+	/**
63
+	 * @param array  $props_n_values          incoming values
64
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
65
+	 *                                        used.)
66
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
67
+	 *                                        date_format and the second value is the time format
68
+	 * @return EE_Registration
69
+	 * @throws EE_Error
70
+	 */
71
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
72
+	{
73
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
74
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param array  $props_n_values  incoming values from the database
80
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
+	 *                                the website will be used.
82
+	 * @return EE_Registration
83
+	 */
84
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
85
+	{
86
+		return new self($props_n_values, true, $timezone);
87
+	}
88
+
89
+
90
+	/**
91
+	 *        Set Event ID
92
+	 *
93
+	 * @param        int $EVT_ID Event ID
94
+	 * @throws EE_Error
95
+	 * @throws RuntimeException
96
+	 */
97
+	public function set_event($EVT_ID = 0)
98
+	{
99
+		$this->set('EVT_ID', $EVT_ID);
100
+	}
101
+
102
+
103
+	/**
104
+	 * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
105
+	 * be routed to internal methods
106
+	 *
107
+	 * @param string $field_name
108
+	 * @param mixed  $field_value
109
+	 * @param bool   $use_default
110
+	 * @throws EE_Error
111
+	 * @throws EntityNotFoundException
112
+	 * @throws InvalidArgumentException
113
+	 * @throws InvalidDataTypeException
114
+	 * @throws InvalidInterfaceException
115
+	 * @throws ReflectionException
116
+	 * @throws RuntimeException
117
+	 */
118
+	public function set($field_name, $field_value, $use_default = false)
119
+	{
120
+		switch ($field_name) {
121
+			case 'REG_code':
122
+				if (! empty($field_value) && $this->reg_code() === null) {
123
+					$this->set_reg_code($field_value, $use_default);
124
+				}
125
+				break;
126
+			case 'STS_ID':
127
+				$this->set_status($field_value, $use_default);
128
+				break;
129
+			default:
130
+				parent::set($field_name, $field_value, $use_default);
131
+		}
132
+	}
133
+
134
+
135
+	/**
136
+	 * Set Status ID
137
+	 * updates the registration status and ALSO...
138
+	 * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
139
+	 * calls release_registration_space() if the reg status changes FROM approved to any other reg status
140
+	 *
141
+	 * @param string                $new_STS_ID
142
+	 * @param boolean               $use_default
143
+	 * @param ContextInterface|null $context
144
+	 * @return bool
145
+	 * @throws DomainException
146
+	 * @throws EE_Error
147
+	 * @throws EntityNotFoundException
148
+	 * @throws InvalidArgumentException
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws InvalidInterfaceException
151
+	 * @throws ReflectionException
152
+	 * @throws RuntimeException
153
+	 * @throws UnexpectedEntityException
154
+	 */
155
+	public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
156
+	{
157
+		// get current REG_Status
158
+		$old_STS_ID = $this->status_ID();
159
+		// if status has changed
160
+		if (
161
+			$old_STS_ID !== $new_STS_ID // and that status has actually changed
162
+			&& ! empty($old_STS_ID) // and that old status is actually set
163
+			&& ! empty($new_STS_ID) // as well as the new status
164
+			&& $this->ID() // ensure registration is in the db
165
+		) {
166
+			// update internal status first
167
+			parent::set('STS_ID', $new_STS_ID, $use_default);
168
+			// THEN handle other changes that occur when reg status changes
169
+			// TO approved
170
+			if ($new_STS_ID === EEM_Registration::status_id_approved) {
171
+				// reserve a space by incrementing ticket and datetime sold values
172
+				$this->reserveRegistrationSpace();
173
+				do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
174
+				// OR FROM  approved
175
+			} elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
176
+				// release a space by decrementing ticket and datetime sold values
177
+				$this->releaseRegistrationSpace();
178
+				do_action(
179
+					'AHEE__EE_Registration__set_status__from_approved',
180
+					$this,
181
+					$old_STS_ID,
182
+					$new_STS_ID,
183
+					$context
184
+				);
185
+			}
186
+			// update status
187
+			parent::set('STS_ID', $new_STS_ID, $use_default);
188
+			$this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
189
+			if ($this->statusChangeUpdatesTransaction($context)) {
190
+				$this->updateTransactionAfterStatusChange();
191
+			}
192
+			do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
193
+			return true;
194
+		}
195
+		// even though the old value matches the new value, it's still good to
196
+		// allow the parent set method to have a say
197
+		parent::set('STS_ID', $new_STS_ID, $use_default);
198
+		return true;
199
+	}
200
+
201
+
202
+	/**
203
+	 * update REGs and TXN when cancelled or declined registrations involved
204
+	 *
205
+	 * @param string                $new_STS_ID
206
+	 * @param string                $old_STS_ID
207
+	 * @param ContextInterface|null $context
208
+	 * @throws EE_Error
209
+	 * @throws InvalidArgumentException
210
+	 * @throws InvalidDataTypeException
211
+	 * @throws InvalidInterfaceException
212
+	 * @throws ReflectionException
213
+	 * @throws RuntimeException
214
+	 */
215
+	private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
216
+	{
217
+		// these reg statuses should not be considered in any calculations involving monies owing
218
+		$closed_reg_statuses = EEM_Registration::closed_reg_statuses();
219
+		// true if registration has been cancelled or declined
220
+		$this->updateIfCanceled(
221
+			$closed_reg_statuses,
222
+			$new_STS_ID,
223
+			$old_STS_ID,
224
+			$context
225
+		);
226
+		$this->updateIfReinstated(
227
+			$closed_reg_statuses,
228
+			$new_STS_ID,
229
+			$old_STS_ID,
230
+			$context
231
+		);
232
+	}
233
+
234
+
235
+	/**
236
+	 * update REGs and TXN when cancelled or declined registrations involved
237
+	 *
238
+	 * @param array                 $closed_reg_statuses
239
+	 * @param string                $new_STS_ID
240
+	 * @param string                $old_STS_ID
241
+	 * @param ContextInterface|null $context
242
+	 * @throws EE_Error
243
+	 * @throws InvalidArgumentException
244
+	 * @throws InvalidDataTypeException
245
+	 * @throws InvalidInterfaceException
246
+	 * @throws ReflectionException
247
+	 * @throws RuntimeException
248
+	 */
249
+	private function updateIfCanceled(
250
+		array $closed_reg_statuses,
251
+		$new_STS_ID,
252
+		$old_STS_ID,
253
+		ContextInterface $context = null
254
+	) {
255
+		// true if registration has been cancelled or declined
256
+		if (
257
+			in_array($new_STS_ID, $closed_reg_statuses, true)
258
+			&& ! in_array($old_STS_ID, $closed_reg_statuses, true)
259
+		) {
260
+			/** @type EE_Registration_Processor $registration_processor */
261
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
262
+			/** @type EE_Transaction_Processor $transaction_processor */
263
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
264
+			// cancelled or declined registration
265
+			$registration_processor->update_registration_after_being_canceled_or_declined(
266
+				$this,
267
+				$closed_reg_statuses
268
+			);
269
+			$transaction_processor->update_transaction_after_canceled_or_declined_registration(
270
+				$this,
271
+				$closed_reg_statuses,
272
+				false
273
+			);
274
+			do_action(
275
+				'AHEE__EE_Registration__set_status__canceled_or_declined',
276
+				$this,
277
+				$old_STS_ID,
278
+				$new_STS_ID,
279
+				$context
280
+			);
281
+			return;
282
+		}
283
+	}
284
+
285
+
286
+	/**
287
+	 * update REGs and TXN when cancelled or declined registrations involved
288
+	 *
289
+	 * @param array                 $closed_reg_statuses
290
+	 * @param string                $new_STS_ID
291
+	 * @param string                $old_STS_ID
292
+	 * @param ContextInterface|null $context
293
+	 * @throws EE_Error
294
+	 * @throws InvalidArgumentException
295
+	 * @throws InvalidDataTypeException
296
+	 * @throws InvalidInterfaceException
297
+	 * @throws ReflectionException
298
+	 */
299
+	private function updateIfReinstated(
300
+		array $closed_reg_statuses,
301
+		$new_STS_ID,
302
+		$old_STS_ID,
303
+		ContextInterface $context = null
304
+	) {
305
+		// true if reinstating cancelled or declined registration
306
+		if (
307
+			in_array($old_STS_ID, $closed_reg_statuses, true)
308
+			&& ! in_array($new_STS_ID, $closed_reg_statuses, true)
309
+		) {
310
+			/** @type EE_Registration_Processor $registration_processor */
311
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
312
+			/** @type EE_Transaction_Processor $transaction_processor */
313
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
314
+			// reinstating cancelled or declined registration
315
+			$registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
316
+				$this,
317
+				$closed_reg_statuses
318
+			);
319
+			$transaction_processor->update_transaction_after_reinstating_canceled_registration(
320
+				$this,
321
+				$closed_reg_statuses,
322
+				false
323
+			);
324
+			do_action(
325
+				'AHEE__EE_Registration__set_status__after_reinstated',
326
+				$this,
327
+				$old_STS_ID,
328
+				$new_STS_ID,
329
+				$context
330
+			);
331
+		}
332
+	}
333
+
334
+
335
+	/**
336
+	 * @param ContextInterface|null $context
337
+	 * @return bool
338
+	 */
339
+	private function statusChangeUpdatesTransaction(ContextInterface $context = null)
340
+	{
341
+		$contexts_that_do_not_update_transaction = (array) apply_filters(
342
+			'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
343
+			array('spco_reg_step_attendee_information_process_registrations'),
344
+			$context,
345
+			$this
346
+		);
347
+		return ! (
348
+			$context instanceof ContextInterface
349
+			&& in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
350
+		);
351
+	}
352
+
353
+
354
+	/**
355
+	 * @throws EE_Error
356
+	 * @throws EntityNotFoundException
357
+	 * @throws InvalidArgumentException
358
+	 * @throws InvalidDataTypeException
359
+	 * @throws InvalidInterfaceException
360
+	 * @throws ReflectionException
361
+	 * @throws RuntimeException
362
+	 */
363
+	private function updateTransactionAfterStatusChange()
364
+	{
365
+		/** @type EE_Transaction_Payments $transaction_payments */
366
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
367
+		$transaction_payments->recalculate_transaction_total($this->transaction(), false);
368
+		$this->transaction()->update_status_based_on_total_paid(true);
369
+	}
370
+
371
+
372
+	/**
373
+	 *        get Status ID
374
+	 */
375
+	public function status_ID()
376
+	{
377
+		return $this->get('STS_ID');
378
+	}
379
+
380
+
381
+	/**
382
+	 * Gets the ticket this registration is for
383
+	 *
384
+	 * @param boolean $include_archived whether to include archived tickets or not.
385
+	 *
386
+	 * @return EE_Ticket|EE_Base_Class
387
+	 * @throws EE_Error
388
+	 */
389
+	public function ticket($include_archived = true)
390
+	{
391
+		$query_params = array();
392
+		if ($include_archived) {
393
+			$query_params['default_where_conditions'] = 'none';
394
+		}
395
+		return $this->get_first_related('Ticket', $query_params);
396
+	}
397
+
398
+
399
+	/**
400
+	 * Gets the event this registration is for
401
+	 *
402
+	 * @return EE_Event
403
+	 * @throws EE_Error
404
+	 * @throws EntityNotFoundException
405
+	 */
406
+	public function event()
407
+	{
408
+		$event = $this->get_first_related('Event');
409
+		if (! $event instanceof \EE_Event) {
410
+			throw new EntityNotFoundException('Event ID', $this->event_ID());
411
+		}
412
+		return $event;
413
+	}
414
+
415
+
416
+	/**
417
+	 * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
418
+	 * with the author of the event this registration is for.
419
+	 *
420
+	 * @since 4.5.0
421
+	 * @return int
422
+	 * @throws EE_Error
423
+	 * @throws EntityNotFoundException
424
+	 */
425
+	public function wp_user()
426
+	{
427
+		$event = $this->event();
428
+		if ($event instanceof EE_Event) {
429
+			return $event->wp_user();
430
+		}
431
+		return 0;
432
+	}
433
+
434
+
435
+	/**
436
+	 * increments this registration's related ticket sold and corresponding datetime sold values
437
+	 *
438
+	 * @return void
439
+	 * @throws DomainException
440
+	 * @throws EE_Error
441
+	 * @throws EntityNotFoundException
442
+	 * @throws InvalidArgumentException
443
+	 * @throws InvalidDataTypeException
444
+	 * @throws InvalidInterfaceException
445
+	 * @throws ReflectionException
446
+	 * @throws UnexpectedEntityException
447
+	 */
448
+	private function reserveRegistrationSpace()
449
+	{
450
+		// reserved ticket and datetime counts will be decremented as sold counts are incremented
451
+		// so stop tracking that this reg has a ticket reserved
452
+		$this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
453
+		$ticket = $this->ticket();
454
+		$ticket->increaseSold();
455
+		// possibly set event status to sold out
456
+		$this->event()->perform_sold_out_status_check();
457
+	}
458
+
459
+
460
+	/**
461
+	 * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
462
+	 *
463
+	 * @return void
464
+	 * @throws DomainException
465
+	 * @throws EE_Error
466
+	 * @throws EntityNotFoundException
467
+	 * @throws InvalidArgumentException
468
+	 * @throws InvalidDataTypeException
469
+	 * @throws InvalidInterfaceException
470
+	 * @throws ReflectionException
471
+	 * @throws UnexpectedEntityException
472
+	 */
473
+	private function releaseRegistrationSpace()
474
+	{
475
+		$ticket = $this->ticket();
476
+		$ticket->decreaseSold();
477
+		// possibly change event status from sold out back to previous status
478
+		$this->event()->perform_sold_out_status_check();
479
+	}
480
+
481
+
482
+	/**
483
+	 * tracks this registration's ticket reservation in extra meta
484
+	 * and can increment related ticket reserved and corresponding datetime reserved values
485
+	 *
486
+	 * @param bool $update_ticket if true, will increment ticket and datetime reserved count
487
+	 * @return void
488
+	 * @throws EE_Error
489
+	 * @throws InvalidArgumentException
490
+	 * @throws InvalidDataTypeException
491
+	 * @throws InvalidInterfaceException
492
+	 * @throws ReflectionException
493
+	 */
494
+	public function reserve_ticket($update_ticket = false, $source = 'unknown')
495
+	{
496
+		// only reserve ticket if space is not currently reserved
497
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
498
+			$this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
499
+			// IMPORTANT !!!
500
+			// although checking $update_ticket first would be more efficient,
501
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
502
+			if (
503
+				$this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
504
+				&& $update_ticket
505
+			) {
506
+				$ticket = $this->ticket();
507
+				$ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
508
+				$ticket->save();
509
+			}
510
+		}
511
+	}
512
+
513
+
514
+	/**
515
+	 * stops tracking this registration's ticket reservation in extra meta
516
+	 * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
517
+	 *
518
+	 * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
519
+	 * @return void
520
+	 * @throws EE_Error
521
+	 * @throws InvalidArgumentException
522
+	 * @throws InvalidDataTypeException
523
+	 * @throws InvalidInterfaceException
524
+	 * @throws ReflectionException
525
+	 */
526
+	public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
527
+	{
528
+		// only release ticket if space is currently reserved
529
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
530
+			$this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
531
+			// IMPORTANT !!!
532
+			// although checking $update_ticket first would be more efficient,
533
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
534
+			if (
535
+				$this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
536
+				&& $update_ticket
537
+			) {
538
+				$ticket = $this->ticket();
539
+				$ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
540
+			}
541
+		}
542
+	}
543
+
544
+
545
+	/**
546
+	 * Set Attendee ID
547
+	 *
548
+	 * @param        int $ATT_ID Attendee ID
549
+	 * @throws EE_Error
550
+	 * @throws RuntimeException
551
+	 */
552
+	public function set_attendee_id($ATT_ID = 0)
553
+	{
554
+		$this->set('ATT_ID', $ATT_ID);
555
+	}
556
+
557
+
558
+	/**
559
+	 *        Set Transaction ID
560
+	 *
561
+	 * @param        int $TXN_ID Transaction ID
562
+	 * @throws EE_Error
563
+	 * @throws RuntimeException
564
+	 */
565
+	public function set_transaction_id($TXN_ID = 0)
566
+	{
567
+		$this->set('TXN_ID', $TXN_ID);
568
+	}
569
+
570
+
571
+	/**
572
+	 *        Set Session
573
+	 *
574
+	 * @param    string $REG_session PHP Session ID
575
+	 * @throws EE_Error
576
+	 * @throws RuntimeException
577
+	 */
578
+	public function set_session($REG_session = '')
579
+	{
580
+		$this->set('REG_session', $REG_session);
581
+	}
582
+
583
+
584
+	/**
585
+	 *        Set Registration URL Link
586
+	 *
587
+	 * @param    string $REG_url_link Registration URL Link
588
+	 * @throws EE_Error
589
+	 * @throws RuntimeException
590
+	 */
591
+	public function set_reg_url_link($REG_url_link = '')
592
+	{
593
+		$this->set('REG_url_link', $REG_url_link);
594
+	}
595
+
596
+
597
+	/**
598
+	 *        Set Attendee Counter
599
+	 *
600
+	 * @param        int $REG_count Primary Attendee
601
+	 * @throws EE_Error
602
+	 * @throws RuntimeException
603
+	 */
604
+	public function set_count($REG_count = 1)
605
+	{
606
+		$this->set('REG_count', $REG_count);
607
+	}
608
+
609
+
610
+	/**
611
+	 *        Set Group Size
612
+	 *
613
+	 * @param        boolean $REG_group_size Group Registration
614
+	 * @throws EE_Error
615
+	 * @throws RuntimeException
616
+	 */
617
+	public function set_group_size($REG_group_size = false)
618
+	{
619
+		$this->set('REG_group_size', $REG_group_size);
620
+	}
621
+
622
+
623
+	/**
624
+	 *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
625
+	 *    EEM_Registration::status_id_not_approved
626
+	 *
627
+	 * @return        boolean
628
+	 */
629
+	public function is_not_approved()
630
+	{
631
+		return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
632
+	}
633
+
634
+
635
+	/**
636
+	 *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
637
+	 *    EEM_Registration::status_id_pending_payment
638
+	 *
639
+	 * @return        boolean
640
+	 */
641
+	public function is_pending_payment()
642
+	{
643
+		return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
644
+	}
645
+
646
+
647
+	/**
648
+	 *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
649
+	 *
650
+	 * @return        boolean
651
+	 */
652
+	public function is_approved()
653
+	{
654
+		return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
655
+	}
656
+
657
+
658
+	/**
659
+	 *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
660
+	 *
661
+	 * @return        boolean
662
+	 */
663
+	public function is_cancelled()
664
+	{
665
+		return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
666
+	}
667
+
668
+
669
+	/**
670
+	 *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
671
+	 *
672
+	 * @return        boolean
673
+	 */
674
+	public function is_declined()
675
+	{
676
+		return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
677
+	}
678
+
679
+
680
+	/**
681
+	 *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
682
+	 *    EEM_Registration::status_id_incomplete
683
+	 *
684
+	 * @return        boolean
685
+	 */
686
+	public function is_incomplete()
687
+	{
688
+		return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
689
+	}
690
+
691
+
692
+	/**
693
+	 *        Set Registration Date
694
+	 *
695
+	 * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
696
+	 *                                                 Date
697
+	 * @throws EE_Error
698
+	 * @throws RuntimeException
699
+	 */
700
+	public function set_reg_date($REG_date = false)
701
+	{
702
+		$this->set('REG_date', $REG_date);
703
+	}
704
+
705
+
706
+	/**
707
+	 *    Set final price owing for this registration after all ticket/price modifications
708
+	 *
709
+	 * @access    public
710
+	 * @param    float $REG_final_price
711
+	 * @throws EE_Error
712
+	 * @throws RuntimeException
713
+	 */
714
+	public function set_final_price($REG_final_price = 0.00)
715
+	{
716
+		$this->set('REG_final_price', $REG_final_price);
717
+	}
718
+
719
+
720
+	/**
721
+	 *    Set amount paid towards this registration's final price
722
+	 *
723
+	 * @access    public
724
+	 * @param    float $REG_paid
725
+	 * @throws EE_Error
726
+	 * @throws RuntimeException
727
+	 */
728
+	public function set_paid($REG_paid = 0.00)
729
+	{
730
+		$this->set('REG_paid', $REG_paid);
731
+	}
732
+
733
+
734
+	/**
735
+	 *        Attendee Is Going
736
+	 *
737
+	 * @param        boolean $REG_att_is_going Attendee Is Going
738
+	 * @throws EE_Error
739
+	 * @throws RuntimeException
740
+	 */
741
+	public function set_att_is_going($REG_att_is_going = false)
742
+	{
743
+		$this->set('REG_att_is_going', $REG_att_is_going);
744
+	}
745
+
746
+
747
+	/**
748
+	 * Gets the related attendee
749
+	 *
750
+	 * @return EE_Attendee
751
+	 * @throws EE_Error
752
+	 */
753
+	public function attendee()
754
+	{
755
+		return $this->get_first_related('Attendee');
756
+	}
757
+
758
+	/**
759
+	 * Gets the name of the attendee.
760
+	 * @since 4.10.12.p
761
+	 * @param bool $apply_html_entities set to true if you want to use HTML entities.
762
+	 * @return string
763
+	 * @throws EE_Error
764
+	 * @throws InvalidArgumentException
765
+	 * @throws InvalidDataTypeException
766
+	 * @throws InvalidInterfaceException
767
+	 * @throws ReflectionException
768
+	 */
769
+	public function attendeeName($apply_html_entities = false)
770
+	{
771
+		$attendee = $this->get_first_related('Attendee');
772
+		if ($attendee instanceof EE_Attendee) {
773
+			$attendee_name = $attendee->full_name($apply_html_entities);
774
+		} else {
775
+			$attendee_name = esc_html__('Unknown', 'event_espresso');
776
+		}
777
+		return $attendee_name;
778
+	}
779
+
780
+
781
+	/**
782
+	 *        get Event ID
783
+	 */
784
+	public function event_ID()
785
+	{
786
+		return $this->get('EVT_ID');
787
+	}
788
+
789
+
790
+	/**
791
+	 *        get Event ID
792
+	 */
793
+	public function event_name()
794
+	{
795
+		$event = $this->event_obj();
796
+		if ($event) {
797
+			return $event->name();
798
+		} else {
799
+			return null;
800
+		}
801
+	}
802
+
803
+
804
+	/**
805
+	 * Fetches the event this registration is for
806
+	 *
807
+	 * @return EE_Event
808
+	 * @throws EE_Error
809
+	 */
810
+	public function event_obj()
811
+	{
812
+		return $this->get_first_related('Event');
813
+	}
814
+
815
+
816
+	/**
817
+	 *        get Attendee ID
818
+	 */
819
+	public function attendee_ID()
820
+	{
821
+		return $this->get('ATT_ID');
822
+	}
823
+
824
+
825
+	/**
826
+	 *        get PHP Session ID
827
+	 */
828
+	public function session_ID()
829
+	{
830
+		return $this->get('REG_session');
831
+	}
832
+
833
+
834
+	/**
835
+	 * Gets the string which represents the URL trigger for the receipt template in the message template system.
836
+	 *
837
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
838
+	 * @return string
839
+	 */
840
+	public function receipt_url($messenger = 'html')
841
+	{
842
+
843
+		/**
844
+		 * The below will be deprecated one version after this.  We check first if there is a custom receipt template
845
+		 * already in use on old system.  If there is then we just return the standard url for it.
846
+		 *
847
+		 * @since 4.5.0
848
+		 */
849
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
850
+		$has_custom = EEH_Template::locate_template(
851
+			$template_relative_path,
852
+			array(),
853
+			true,
854
+			true,
855
+			true
856
+		);
857
+
858
+		if ($has_custom) {
859
+			return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
860
+		}
861
+		return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
862
+	}
863
+
864
+
865
+	/**
866
+	 * Gets the string which represents the URL trigger for the invoice template in the message template system.
867
+	 *
868
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
869
+	 * @return string
870
+	 * @throws EE_Error
871
+	 */
872
+	public function invoice_url($messenger = 'html')
873
+	{
874
+		/**
875
+		 * The below will be deprecated one version after this.  We check first if there is a custom invoice template
876
+		 * already in use on old system.  If there is then we just return the standard url for it.
877
+		 *
878
+		 * @since 4.5.0
879
+		 */
880
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
881
+		$has_custom = EEH_Template::locate_template(
882
+			$template_relative_path,
883
+			array(),
884
+			true,
885
+			true,
886
+			true
887
+		);
888
+
889
+		if ($has_custom) {
890
+			if ($messenger == 'html') {
891
+				return $this->invoice_url('launch');
892
+			}
893
+			$route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
894
+
895
+			$query_args = array('ee' => $route, 'id' => $this->reg_url_link());
896
+			if ($messenger == 'html') {
897
+				$query_args['html'] = true;
898
+			}
899
+			return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
900
+		}
901
+		return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
902
+	}
903
+
904
+
905
+	/**
906
+	 * get Registration URL Link
907
+	 *
908
+	 * @access public
909
+	 * @return string
910
+	 * @throws EE_Error
911
+	 */
912
+	public function reg_url_link()
913
+	{
914
+		return (string) $this->get('REG_url_link');
915
+	}
916
+
917
+
918
+	/**
919
+	 * Echoes out invoice_url()
920
+	 *
921
+	 * @param string $type 'download','launch', or 'html' (default is 'launch')
922
+	 * @return void
923
+	 * @throws EE_Error
924
+	 */
925
+	public function e_invoice_url($type = 'launch')
926
+	{
927
+		echo esc_url_raw($this->invoice_url($type));
928
+	}
929
+
930
+
931
+	/**
932
+	 * Echoes out payment_overview_url
933
+	 */
934
+	public function e_payment_overview_url()
935
+	{
936
+		echo esc_url_raw($this->payment_overview_url());
937
+	}
938
+
939
+
940
+	/**
941
+	 * Gets the URL for the checkout payment options reg step
942
+	 * with this registration's REG_url_link added as a query parameter
943
+	 *
944
+	 * @param bool $clear_session Set to true when you want to clear the session on revisiting the
945
+	 *                            payment overview url.
946
+	 * @return string
947
+	 * @throws InvalidInterfaceException
948
+	 * @throws InvalidDataTypeException
949
+	 * @throws EE_Error
950
+	 * @throws InvalidArgumentException
951
+	 */
952
+	public function payment_overview_url($clear_session = false)
953
+	{
954
+		return add_query_arg(
955
+			(array) apply_filters(
956
+				'FHEE__EE_Registration__payment_overview_url__query_args',
957
+				array(
958
+					'e_reg_url_link' => $this->reg_url_link(),
959
+					'step'           => 'payment_options',
960
+					'revisit'        => true,
961
+					'clear_session'  => (bool) $clear_session,
962
+				),
963
+				$this
964
+			),
965
+			EE_Registry::instance()->CFG->core->reg_page_url()
966
+		);
967
+	}
968
+
969
+
970
+	/**
971
+	 * Gets the URL for the checkout attendee information reg step
972
+	 * with this registration's REG_url_link added as a query parameter
973
+	 *
974
+	 * @return string
975
+	 * @throws InvalidInterfaceException
976
+	 * @throws InvalidDataTypeException
977
+	 * @throws EE_Error
978
+	 * @throws InvalidArgumentException
979
+	 */
980
+	public function edit_attendee_information_url()
981
+	{
982
+		return add_query_arg(
983
+			(array) apply_filters(
984
+				'FHEE__EE_Registration__edit_attendee_information_url__query_args',
985
+				array(
986
+					'e_reg_url_link' => $this->reg_url_link(),
987
+					'step'           => 'attendee_information',
988
+					'revisit'        => true,
989
+				),
990
+				$this
991
+			),
992
+			EE_Registry::instance()->CFG->core->reg_page_url()
993
+		);
994
+	}
995
+
996
+
997
+	/**
998
+	 * Simply generates and returns the appropriate admin_url link to edit this registration
999
+	 *
1000
+	 * @return string
1001
+	 * @throws EE_Error
1002
+	 */
1003
+	public function get_admin_edit_url()
1004
+	{
1005
+		return EEH_URL::add_query_args_and_nonce(
1006
+			array(
1007
+				'page'    => 'espresso_registrations',
1008
+				'action'  => 'view_registration',
1009
+				'_REG_ID' => $this->ID(),
1010
+			),
1011
+			admin_url('admin.php')
1012
+		);
1013
+	}
1014
+
1015
+
1016
+	/**
1017
+	 *    is_primary_registrant?
1018
+	 */
1019
+	public function is_primary_registrant()
1020
+	{
1021
+		return $this->get('REG_count') === 1 ? true : false;
1022
+	}
1023
+
1024
+
1025
+	/**
1026
+	 * This returns the primary registration object for this registration group (which may be this object).
1027
+	 *
1028
+	 * @return EE_Registration
1029
+	 * @throws EE_Error
1030
+	 */
1031
+	public function get_primary_registration()
1032
+	{
1033
+		if ($this->is_primary_registrant()) {
1034
+			return $this;
1035
+		}
1036
+
1037
+		// k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1038
+		/** @var EE_Registration $primary_registrant */
1039
+		$primary_registrant = EEM_Registration::instance()->get_one(
1040
+			array(
1041
+				array(
1042
+					'TXN_ID'    => $this->transaction_ID(),
1043
+					'REG_count' => 1,
1044
+				),
1045
+			)
1046
+		);
1047
+		return $primary_registrant;
1048
+	}
1049
+
1050
+
1051
+	/**
1052
+	 *        get  Attendee Number
1053
+	 *
1054
+	 * @access        public
1055
+	 */
1056
+	public function count()
1057
+	{
1058
+		return $this->get('REG_count');
1059
+	}
1060
+
1061
+
1062
+	/**
1063
+	 *        get Group Size
1064
+	 */
1065
+	public function group_size()
1066
+	{
1067
+		return $this->get('REG_group_size');
1068
+	}
1069
+
1070
+
1071
+	/**
1072
+	 *        get Registration Date
1073
+	 */
1074
+	public function date()
1075
+	{
1076
+		return $this->get('REG_date');
1077
+	}
1078
+
1079
+
1080
+	/**
1081
+	 * gets a pretty date
1082
+	 *
1083
+	 * @param string $date_format
1084
+	 * @param string $time_format
1085
+	 * @return string
1086
+	 * @throws EE_Error
1087
+	 */
1088
+	public function pretty_date($date_format = null, $time_format = null)
1089
+	{
1090
+		return $this->get_datetime('REG_date', $date_format, $time_format);
1091
+	}
1092
+
1093
+
1094
+	/**
1095
+	 * final_price
1096
+	 * the registration's share of the transaction total, so that the
1097
+	 * sum of all the transaction's REG_final_prices equal the transaction's total
1098
+	 *
1099
+	 * @return float
1100
+	 * @throws EE_Error
1101
+	 */
1102
+	public function final_price()
1103
+	{
1104
+		return $this->get('REG_final_price');
1105
+	}
1106
+
1107
+
1108
+	/**
1109
+	 * pretty_final_price
1110
+	 *  final price as formatted string, with correct decimal places and currency symbol
1111
+	 *
1112
+	 * @return string
1113
+	 * @throws EE_Error
1114
+	 */
1115
+	public function pretty_final_price()
1116
+	{
1117
+		return $this->get_pretty('REG_final_price');
1118
+	}
1119
+
1120
+
1121
+	/**
1122
+	 * get paid (yeah)
1123
+	 *
1124
+	 * @return float
1125
+	 * @throws EE_Error
1126
+	 */
1127
+	public function paid()
1128
+	{
1129
+		return $this->get('REG_paid');
1130
+	}
1131
+
1132
+
1133
+	/**
1134
+	 * pretty_paid
1135
+	 *
1136
+	 * @return float
1137
+	 * @throws EE_Error
1138
+	 */
1139
+	public function pretty_paid()
1140
+	{
1141
+		return $this->get_pretty('REG_paid');
1142
+	}
1143
+
1144
+
1145
+	/**
1146
+	 * owes_monies_and_can_pay
1147
+	 * whether or not this registration has monies owing and it's' status allows payment
1148
+	 *
1149
+	 * @param array $requires_payment
1150
+	 * @return bool
1151
+	 * @throws EE_Error
1152
+	 */
1153
+	public function owes_monies_and_can_pay($requires_payment = array())
1154
+	{
1155
+		// these reg statuses require payment (if event is not free)
1156
+		$requires_payment = ! empty($requires_payment)
1157
+			? $requires_payment
1158
+			: EEM_Registration::reg_statuses_that_allow_payment();
1159
+		if (
1160
+			in_array($this->status_ID(), $requires_payment) &&
1161
+			$this->final_price() != 0 &&
1162
+			$this->final_price() != $this->paid()
1163
+		) {
1164
+			return true;
1165
+		} else {
1166
+			return false;
1167
+		}
1168
+	}
1169
+
1170
+
1171
+	/**
1172
+	 * Prints out the return value of $this->pretty_status()
1173
+	 *
1174
+	 * @param bool $show_icons
1175
+	 * @return void
1176
+	 * @throws EE_Error
1177
+	 */
1178
+	public function e_pretty_status($show_icons = false)
1179
+	{
1180
+		echo $this->pretty_status($show_icons); // already escaped
1181
+	}
1182
+
1183
+
1184
+	/**
1185
+	 * Returns a nice version of the status for displaying to customers
1186
+	 *
1187
+	 * @param bool $show_icons
1188
+	 * @return string
1189
+	 * @throws EE_Error
1190
+	 */
1191
+	public function pretty_status($show_icons = false)
1192
+	{
1193
+		$status = EEM_Status::instance()->localized_status(
1194
+			array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1195
+			false,
1196
+			'sentence'
1197
+		);
1198
+		$icon = '';
1199
+		switch ($this->status_ID()) {
1200
+			case EEM_Registration::status_id_approved:
1201
+				$icon = $show_icons
1202
+					? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1203
+					: '';
1204
+				break;
1205
+			case EEM_Registration::status_id_pending_payment:
1206
+				$icon = $show_icons
1207
+					? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1208
+					: '';
1209
+				break;
1210
+			case EEM_Registration::status_id_not_approved:
1211
+				$icon = $show_icons
1212
+					? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1213
+					: '';
1214
+				break;
1215
+			case EEM_Registration::status_id_cancelled:
1216
+				$icon = $show_icons
1217
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1218
+					: '';
1219
+				break;
1220
+			case EEM_Registration::status_id_incomplete:
1221
+				$icon = $show_icons
1222
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1223
+					: '';
1224
+				break;
1225
+			case EEM_Registration::status_id_declined:
1226
+				$icon = $show_icons
1227
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1228
+					: '';
1229
+				break;
1230
+			case EEM_Registration::status_id_wait_list:
1231
+				$icon = $show_icons
1232
+					? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1233
+					: '';
1234
+				break;
1235
+		}
1236
+		return $icon . $status[ $this->status_ID() ];
1237
+	}
1238
+
1239
+
1240
+	/**
1241
+	 *        get Attendee Is Going
1242
+	 */
1243
+	public function att_is_going()
1244
+	{
1245
+		return $this->get('REG_att_is_going');
1246
+	}
1247
+
1248
+
1249
+	/**
1250
+	 * Gets related answers
1251
+	 *
1252
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1253
+	 * @return EE_Answer[]
1254
+	 * @throws EE_Error
1255
+	 */
1256
+	public function answers($query_params = null)
1257
+	{
1258
+		return $this->get_many_related('Answer', $query_params);
1259
+	}
1260
+
1261
+
1262
+	/**
1263
+	 * Gets the registration's answer value to the specified question
1264
+	 * (either the question's ID or a question object)
1265
+	 *
1266
+	 * @param EE_Question|int $question
1267
+	 * @param bool            $pretty_value
1268
+	 * @return array|string if pretty_value= true, the result will always be a string
1269
+	 * (because the answer might be an array of answer values, so passing pretty_value=true
1270
+	 * will convert it into some kind of string)
1271
+	 * @throws EE_Error
1272
+	 */
1273
+	public function answer_value_to_question($question, $pretty_value = true)
1274
+	{
1275
+		$question_id = EEM_Question::instance()->ensure_is_ID($question);
1276
+		return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1277
+	}
1278
+
1279
+
1280
+	/**
1281
+	 * question_groups
1282
+	 * returns an array of EE_Question_Group objects for this registration
1283
+	 *
1284
+	 * @return EE_Question_Group[]
1285
+	 * @throws EE_Error
1286
+	 * @throws InvalidArgumentException
1287
+	 * @throws InvalidDataTypeException
1288
+	 * @throws InvalidInterfaceException
1289
+	 * @throws ReflectionException
1290
+	 */
1291
+	public function question_groups()
1292
+	{
1293
+		return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1294
+	}
1295
+
1296
+
1297
+	/**
1298
+	 * count_question_groups
1299
+	 * returns a count of the number of EE_Question_Group objects for this registration
1300
+	 *
1301
+	 * @return int
1302
+	 * @throws EE_Error
1303
+	 * @throws EntityNotFoundException
1304
+	 * @throws InvalidArgumentException
1305
+	 * @throws InvalidDataTypeException
1306
+	 * @throws InvalidInterfaceException
1307
+	 * @throws ReflectionException
1308
+	 */
1309
+	public function count_question_groups()
1310
+	{
1311
+		return EEM_Event::instance()->count_related(
1312
+			$this->event_ID(),
1313
+			'Question_Group',
1314
+			[
1315
+				[
1316
+					'Event_Question_Group.'
1317
+					. EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1318
+				]
1319
+			]
1320
+		);
1321
+	}
1322
+
1323
+
1324
+	/**
1325
+	 * Returns the registration date in the 'standard' string format
1326
+	 * (function may be improved in the future to allow for different formats and timezones)
1327
+	 *
1328
+	 * @return string
1329
+	 * @throws EE_Error
1330
+	 */
1331
+	public function reg_date()
1332
+	{
1333
+		return $this->get_datetime('REG_date');
1334
+	}
1335
+
1336
+
1337
+	/**
1338
+	 * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1339
+	 * the ticket this registration purchased, or the datetime they have registered
1340
+	 * to attend)
1341
+	 *
1342
+	 * @return EE_Datetime_Ticket
1343
+	 * @throws EE_Error
1344
+	 */
1345
+	public function datetime_ticket()
1346
+	{
1347
+		return $this->get_first_related('Datetime_Ticket');
1348
+	}
1349
+
1350
+
1351
+	/**
1352
+	 * Sets the registration's datetime_ticket.
1353
+	 *
1354
+	 * @param EE_Datetime_Ticket $datetime_ticket
1355
+	 * @return EE_Datetime_Ticket
1356
+	 * @throws EE_Error
1357
+	 */
1358
+	public function set_datetime_ticket($datetime_ticket)
1359
+	{
1360
+		return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1361
+	}
1362
+
1363
+	/**
1364
+	 * Gets deleted
1365
+	 *
1366
+	 * @return bool
1367
+	 * @throws EE_Error
1368
+	 */
1369
+	public function deleted()
1370
+	{
1371
+		return $this->get('REG_deleted');
1372
+	}
1373
+
1374
+	/**
1375
+	 * Sets deleted
1376
+	 *
1377
+	 * @param boolean $deleted
1378
+	 * @return bool
1379
+	 * @throws EE_Error
1380
+	 * @throws RuntimeException
1381
+	 */
1382
+	public function set_deleted($deleted)
1383
+	{
1384
+		if ($deleted) {
1385
+			$this->delete();
1386
+		} else {
1387
+			$this->restore();
1388
+		}
1389
+	}
1390
+
1391
+
1392
+	/**
1393
+	 * Get the status object of this object
1394
+	 *
1395
+	 * @return EE_Status
1396
+	 * @throws EE_Error
1397
+	 */
1398
+	public function status_obj()
1399
+	{
1400
+		return $this->get_first_related('Status');
1401
+	}
1402
+
1403
+
1404
+	/**
1405
+	 * Returns the number of times this registration has checked into any of the datetimes
1406
+	 * its available for
1407
+	 *
1408
+	 * @return int
1409
+	 * @throws EE_Error
1410
+	 */
1411
+	public function count_checkins()
1412
+	{
1413
+		return $this->get_model()->count_related($this, 'Checkin');
1414
+	}
1415
+
1416
+
1417
+	/**
1418
+	 * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1419
+	 * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1420
+	 *
1421
+	 * @return int
1422
+	 * @throws EE_Error
1423
+	 */
1424
+	public function count_checkins_not_checkedout()
1425
+	{
1426
+		return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1427
+	}
1428
+
1429
+
1430
+	/**
1431
+	 * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1432
+	 *
1433
+	 * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1434
+	 * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1435
+	 *                                          consider registration status as well as datetime access.
1436
+	 * @return bool
1437
+	 * @throws EE_Error
1438
+	 */
1439
+	public function can_checkin($DTT_OR_ID, $check_approved = true)
1440
+	{
1441
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1442
+
1443
+		// first check registration status
1444
+		if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1445
+			return false;
1446
+		}
1447
+		// is there a datetime ticket that matches this dtt_ID?
1448
+		if (
1449
+			! (EEM_Datetime_Ticket::instance()->exists(
1450
+				array(
1451
+				array(
1452
+					'TKT_ID' => $this->get('TKT_ID'),
1453
+					'DTT_ID' => $DTT_ID,
1454
+				),
1455
+				)
1456
+			))
1457
+		) {
1458
+			return false;
1459
+		}
1460
+
1461
+		// final check is against TKT_uses
1462
+		return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1463
+	}
1464
+
1465
+
1466
+	/**
1467
+	 * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1468
+	 * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1469
+	 * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1470
+	 * then return false.  Otherwise return true.
1471
+	 *
1472
+	 * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1473
+	 * @return bool true means can checkin.  false means cannot checkin.
1474
+	 * @throws EE_Error
1475
+	 */
1476
+	public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1477
+	{
1478
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1479
+
1480
+		if (! $DTT_ID) {
1481
+			return false;
1482
+		}
1483
+
1484
+		$max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1485
+
1486
+		// if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1487
+		// check-in or not.
1488
+		if (! $max_uses || $max_uses === EE_INF) {
1489
+			return true;
1490
+		}
1491
+
1492
+		// does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1493
+		// go ahead and toggle.
1494
+		if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1495
+			return true;
1496
+		}
1497
+
1498
+		// made it here so the last check is whether the number of checkins per unique datetime on this registration
1499
+		// disallows further check-ins.
1500
+		$count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1501
+			array(
1502
+				array(
1503
+					'REG_ID' => $this->ID(),
1504
+					'CHK_in' => true,
1505
+				),
1506
+			),
1507
+			'DTT_ID',
1508
+			true
1509
+		);
1510
+		// checkins have already reached their max number of uses
1511
+		// so registrant can NOT checkin
1512
+		if ($count_unique_dtt_checkins >= $max_uses) {
1513
+			EE_Error::add_error(
1514
+				esc_html__(
1515
+					'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1516
+					'event_espresso'
1517
+				),
1518
+				__FILE__,
1519
+				__FUNCTION__,
1520
+				__LINE__
1521
+			);
1522
+			return false;
1523
+		}
1524
+		return true;
1525
+	}
1526
+
1527
+
1528
+	/**
1529
+	 * toggle Check-in status for this registration
1530
+	 * Check-ins are toggled in the following order:
1531
+	 * never checked in -> checked in
1532
+	 * checked in -> checked out
1533
+	 * checked out -> checked in
1534
+	 *
1535
+	 * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1536
+	 *                      If not included or null, then it is assumed latest datetime is being toggled.
1537
+	 * @param bool $verify  If true then can_checkin() is used to verify whether the person
1538
+	 *                      can be checked in or not.  Otherwise this forces change in checkin status.
1539
+	 * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1540
+	 * @throws EE_Error
1541
+	 */
1542
+	public function toggle_checkin_status($DTT_ID = null, $verify = false)
1543
+	{
1544
+		if (empty($DTT_ID)) {
1545
+			$datetime = $this->get_latest_related_datetime();
1546
+			$DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1547
+			// verify the registration can checkin for the given DTT_ID
1548
+		} elseif (! $this->can_checkin($DTT_ID, $verify)) {
1549
+			EE_Error::add_error(
1550
+				sprintf(
1551
+					esc_html__(
1552
+						'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',
1553
+						'event_espresso'
1554
+					),
1555
+					$this->ID(),
1556
+					$DTT_ID
1557
+				),
1558
+				__FILE__,
1559
+				__FUNCTION__,
1560
+				__LINE__
1561
+			);
1562
+			return false;
1563
+		}
1564
+		$status_paths = array(
1565
+			EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1566
+			EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1567
+			EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1568
+		);
1569
+		// start by getting the current status so we know what status we'll be changing to.
1570
+		$cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1571
+		$status_to = $status_paths[ $cur_status ];
1572
+		// database only records true for checked IN or false for checked OUT
1573
+		// no record ( null ) means checked in NEVER, but we obviously don't save that
1574
+		$new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1575
+		// add relation - note Check-ins are always creating new rows
1576
+		// because we are keeping track of Check-ins over time.
1577
+		// Eventually we'll probably want to show a list table
1578
+		// for the individual Check-ins so that they can be managed.
1579
+		$checkin = EE_Checkin::new_instance(
1580
+			array(
1581
+				'REG_ID' => $this->ID(),
1582
+				'DTT_ID' => $DTT_ID,
1583
+				'CHK_in' => $new_status,
1584
+			)
1585
+		);
1586
+		// if the record could not be saved then return false
1587
+		if ($checkin->save() === 0) {
1588
+			if (WP_DEBUG) {
1589
+				global $wpdb;
1590
+				$error = sprintf(
1591
+					esc_html__(
1592
+						'Registration check in update failed because of the following database error: %1$s%2$s',
1593
+						'event_espresso'
1594
+					),
1595
+					'<br />',
1596
+					$wpdb->last_error
1597
+				);
1598
+			} else {
1599
+				$error = esc_html__(
1600
+					'Registration check in update failed because of an unknown database error',
1601
+					'event_espresso'
1602
+				);
1603
+			}
1604
+			EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1605
+			return false;
1606
+		}
1607
+		// Fire a checked_in and checkout_out action.
1608
+		$checked_status = $status_to === EE_Checkin::status_checked_in ? 'checked_in' : 'checked_out';
1609
+		do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1610
+		return $status_to;
1611
+	}
1612
+
1613
+
1614
+	/**
1615
+	 * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1616
+	 * "Latest" is defined by the `DTT_EVT_start` column.
1617
+	 *
1618
+	 * @return EE_Datetime|null
1619
+	 * @throws EE_Error
1620
+	 */
1621
+	public function get_latest_related_datetime()
1622
+	{
1623
+		return EEM_Datetime::instance()->get_one(
1624
+			array(
1625
+				array(
1626
+					'Ticket.Registration.REG_ID' => $this->ID(),
1627
+				),
1628
+				'order_by' => array('DTT_EVT_start' => 'DESC'),
1629
+			)
1630
+		);
1631
+	}
1632
+
1633
+
1634
+	/**
1635
+	 * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1636
+	 * "Earliest" is defined by the `DTT_EVT_start` column.
1637
+	 *
1638
+	 * @throws EE_Error
1639
+	 */
1640
+	public function get_earliest_related_datetime()
1641
+	{
1642
+		return EEM_Datetime::instance()->get_one(
1643
+			array(
1644
+				array(
1645
+					'Ticket.Registration.REG_ID' => $this->ID(),
1646
+				),
1647
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
1648
+			)
1649
+		);
1650
+	}
1651
+
1652
+
1653
+	/**
1654
+	 * This method simply returns the check-in status for this registration and the given datetime.
1655
+	 * If neither the datetime nor the checkin values are provided as arguments,
1656
+	 * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1657
+	 *
1658
+	 * @param  int       $DTT_ID  The ID of the datetime we're checking against
1659
+	 *                            (if empty we'll get the primary datetime for
1660
+	 *                            this registration (via event) and use it's ID);
1661
+	 * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1662
+	 *
1663
+	 * @return int                Integer representing Check-in status.
1664
+	 * @throws EE_Error
1665
+	 */
1666
+	public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1667
+	{
1668
+		$checkin_query_params = array(
1669
+			'order_by' => array('CHK_timestamp' => 'DESC'),
1670
+		);
1671
+
1672
+		if ($DTT_ID > 0) {
1673
+			$checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1674
+		}
1675
+
1676
+		// get checkin object (if exists)
1677
+		$checkin = $checkin instanceof EE_Checkin
1678
+			? $checkin
1679
+			: $this->get_first_related('Checkin', $checkin_query_params);
1680
+		if ($checkin instanceof EE_Checkin) {
1681
+			if ($checkin->get('CHK_in')) {
1682
+				return EE_Checkin::status_checked_in; // checked in
1683
+			}
1684
+			return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1685
+		}
1686
+		return EE_Checkin::status_checked_never; // never been checked in
1687
+	}
1688
+
1689
+
1690
+	/**
1691
+	 * This method returns a localized message for the toggled Check-in message.
1692
+	 *
1693
+	 * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1694
+	 *                     then it is assumed Check-in for primary datetime was toggled.
1695
+	 * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1696
+	 *                     message can be customized with the attendee name.
1697
+	 * @return string internationalized message
1698
+	 * @throws EE_Error
1699
+	 */
1700
+	public function get_checkin_msg($DTT_ID, $error = false)
1701
+	{
1702
+		// let's get the attendee first so we can include the name of the attendee
1703
+		$attendee = $this->get_first_related('Attendee');
1704
+		if ($attendee instanceof EE_Attendee) {
1705
+			if ($error) {
1706
+				return sprintf(esc_html__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1707
+			}
1708
+			$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1709
+			// what is the status message going to be?
1710
+			switch ($cur_status) {
1711
+				case EE_Checkin::status_checked_never:
1712
+					return sprintf(
1713
+						esc_html__("%s has been removed from Check-in records", "event_espresso"),
1714
+						$attendee->full_name()
1715
+					);
1716
+					break;
1717
+				case EE_Checkin::status_checked_in:
1718
+					return sprintf(esc_html__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1719
+					break;
1720
+				case EE_Checkin::status_checked_out:
1721
+					return sprintf(esc_html__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1722
+					break;
1723
+			}
1724
+		}
1725
+		return esc_html__("The check-in status could not be determined.", "event_espresso");
1726
+	}
1727
+
1728
+
1729
+	/**
1730
+	 * Returns the related EE_Transaction to this registration
1731
+	 *
1732
+	 * @return EE_Transaction
1733
+	 * @throws EE_Error
1734
+	 * @throws EntityNotFoundException
1735
+	 */
1736
+	public function transaction()
1737
+	{
1738
+		$transaction = $this->get_first_related('Transaction');
1739
+		if (! $transaction instanceof \EE_Transaction) {
1740
+			throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1741
+		}
1742
+		return $transaction;
1743
+	}
1744
+
1745
+
1746
+	/**
1747
+	 *        get Registration Code
1748
+	 */
1749
+	public function reg_code()
1750
+	{
1751
+		return $this->get('REG_code');
1752
+	}
1753
+
1754
+
1755
+	/**
1756
+	 *        get Transaction ID
1757
+	 */
1758
+	public function transaction_ID()
1759
+	{
1760
+		return $this->get('TXN_ID');
1761
+	}
1762
+
1763
+
1764
+	/**
1765
+	 * @return int
1766
+	 * @throws EE_Error
1767
+	 */
1768
+	public function ticket_ID()
1769
+	{
1770
+		return $this->get('TKT_ID');
1771
+	}
1772
+
1773
+
1774
+	/**
1775
+	 *        Set Registration Code
1776
+	 *
1777
+	 * @access    public
1778
+	 * @param    string  $REG_code Registration Code
1779
+	 * @param    boolean $use_default
1780
+	 * @throws EE_Error
1781
+	 */
1782
+	public function set_reg_code($REG_code, $use_default = false)
1783
+	{
1784
+		if (empty($REG_code)) {
1785
+			EE_Error::add_error(
1786
+				esc_html__('REG_code can not be empty.', 'event_espresso'),
1787
+				__FILE__,
1788
+				__FUNCTION__,
1789
+				__LINE__
1790
+			);
1791
+			return;
1792
+		}
1793
+		if (! $this->reg_code()) {
1794
+			parent::set('REG_code', $REG_code, $use_default);
1795
+		} else {
1796
+			EE_Error::doing_it_wrong(
1797
+				__CLASS__ . '::' . __FUNCTION__,
1798
+				esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1799
+				'4.6.0'
1800
+			);
1801
+		}
1802
+	}
1803
+
1804
+
1805
+	/**
1806
+	 * Returns all other registrations in the same group as this registrant who have the same ticket option.
1807
+	 * Note, if you want to just get all registrations in the same transaction (group), use:
1808
+	 *    $registration->transaction()->registrations();
1809
+	 *
1810
+	 * @since 4.5.0
1811
+	 * @return EE_Registration[] or empty array if this isn't a group registration.
1812
+	 * @throws EE_Error
1813
+	 */
1814
+	public function get_all_other_registrations_in_group()
1815
+	{
1816
+		if ($this->group_size() < 2) {
1817
+			return array();
1818
+		}
1819
+
1820
+		$query[0] = array(
1821
+			'TXN_ID' => $this->transaction_ID(),
1822
+			'REG_ID' => array('!=', $this->ID()),
1823
+			'TKT_ID' => $this->ticket_ID(),
1824
+		);
1825
+		/** @var EE_Registration[] $registrations */
1826
+		$registrations = $this->get_model()->get_all($query);
1827
+		return $registrations;
1828
+	}
1829
+
1830
+	/**
1831
+	 * Return the link to the admin details for the object.
1832
+	 *
1833
+	 * @return string
1834
+	 * @throws EE_Error
1835
+	 */
1836
+	public function get_admin_details_link()
1837
+	{
1838
+		EE_Registry::instance()->load_helper('URL');
1839
+		return EEH_URL::add_query_args_and_nonce(
1840
+			array(
1841
+				'page'    => 'espresso_registrations',
1842
+				'action'  => 'view_registration',
1843
+				'_REG_ID' => $this->ID(),
1844
+			),
1845
+			admin_url('admin.php')
1846
+		);
1847
+	}
1848
+
1849
+	/**
1850
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1851
+	 *
1852
+	 * @return string
1853
+	 * @throws EE_Error
1854
+	 */
1855
+	public function get_admin_edit_link()
1856
+	{
1857
+		return $this->get_admin_details_link();
1858
+	}
1859
+
1860
+	/**
1861
+	 * Returns the link to a settings page for the object.
1862
+	 *
1863
+	 * @return string
1864
+	 * @throws EE_Error
1865
+	 */
1866
+	public function get_admin_settings_link()
1867
+	{
1868
+		return $this->get_admin_details_link();
1869
+	}
1870
+
1871
+	/**
1872
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
1873
+	 *
1874
+	 * @return string
1875
+	 */
1876
+	public function get_admin_overview_link()
1877
+	{
1878
+		EE_Registry::instance()->load_helper('URL');
1879
+		return EEH_URL::add_query_args_and_nonce(
1880
+			array(
1881
+				'page' => 'espresso_registrations',
1882
+			),
1883
+			admin_url('admin.php')
1884
+		);
1885
+	}
1886
+
1887
+
1888
+	/**
1889
+	 * @param array $query_params
1890
+	 *
1891
+	 * @return \EE_Registration[]
1892
+	 * @throws EE_Error
1893
+	 */
1894
+	public function payments($query_params = array())
1895
+	{
1896
+		return $this->get_many_related('Payment', $query_params);
1897
+	}
1898
+
1899
+
1900
+	/**
1901
+	 * @param array $query_params
1902
+	 *
1903
+	 * @return \EE_Registration_Payment[]
1904
+	 * @throws EE_Error
1905
+	 */
1906
+	public function registration_payments($query_params = array())
1907
+	{
1908
+		return $this->get_many_related('Registration_Payment', $query_params);
1909
+	}
1910
+
1911
+
1912
+	/**
1913
+	 * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1914
+	 * Note: if there are no payments on the registration there will be no payment method returned.
1915
+	 *
1916
+	 * @return EE_Payment_Method|null
1917
+	 */
1918
+	public function payment_method()
1919
+	{
1920
+		return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1921
+	}
1922
+
1923
+
1924
+	/**
1925
+	 * @return \EE_Line_Item
1926
+	 * @throws EntityNotFoundException
1927
+	 * @throws EE_Error
1928
+	 */
1929
+	public function ticket_line_item()
1930
+	{
1931
+		$ticket = $this->ticket();
1932
+		$transaction = $this->transaction();
1933
+		$line_item = null;
1934
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1935
+			$transaction->total_line_item(),
1936
+			'Ticket',
1937
+			array($ticket->ID())
1938
+		);
1939
+		foreach ($ticket_line_items as $ticket_line_item) {
1940
+			if (
1941
+				$ticket_line_item instanceof \EE_Line_Item
1942
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
1943
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
1944
+			) {
1945
+				$line_item = $ticket_line_item;
1946
+				break;
1947
+			}
1948
+		}
1949
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1950
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1951
+		}
1952
+		return $line_item;
1953
+	}
1954
+
1955
+
1956
+	/**
1957
+	 * Soft Deletes this model object.
1958
+	 *
1959
+	 * @return boolean | int
1960
+	 * @throws RuntimeException
1961
+	 * @throws EE_Error
1962
+	 */
1963
+	public function delete()
1964
+	{
1965
+		if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1966
+			$this->set_status(EEM_Registration::status_id_cancelled);
1967
+		}
1968
+		return parent::delete();
1969
+	}
1970
+
1971
+
1972
+	/**
1973
+	 * Restores whatever the previous status was on a registration before it was trashed (if possible)
1974
+	 *
1975
+	 * @throws EE_Error
1976
+	 * @throws RuntimeException
1977
+	 */
1978
+	public function restore()
1979
+	{
1980
+		$previous_status = $this->get_extra_meta(
1981
+			EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1982
+			true,
1983
+			EEM_Registration::status_id_cancelled
1984
+		);
1985
+		if ($previous_status) {
1986
+			$this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1987
+			$this->set_status($previous_status);
1988
+		}
1989
+		return parent::restore();
1990
+	}
1991
+
1992
+
1993
+	/**
1994
+	 * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1995
+	 *
1996
+	 * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1997
+	 *                                           depending on whether the reg status changes to or from "Approved"
1998
+	 * @return boolean whether the Registration status was updated
1999
+	 * @throws EE_Error
2000
+	 * @throws RuntimeException
2001
+	 */
2002
+	public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
2003
+	{
2004
+		$paid = $this->paid();
2005
+		$price = $this->final_price();
2006
+		switch (true) {
2007
+			// overpaid or paid
2008
+			case EEH_Money::compare_floats($paid, $price, '>'):
2009
+			case EEH_Money::compare_floats($paid, $price):
2010
+				$new_status = EEM_Registration::status_id_approved;
2011
+				break;
2012
+			//  underpaid
2013
+			case EEH_Money::compare_floats($paid, $price, '<'):
2014
+				$new_status = EEM_Registration::status_id_pending_payment;
2015
+				break;
2016
+			// uhhh Houston...
2017
+			default:
2018
+				throw new RuntimeException(
2019
+					esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2020
+				);
2021
+		}
2022
+		if ($new_status !== $this->status_ID()) {
2023
+			if ($trigger_set_status_logic) {
2024
+				return $this->set_status($new_status);
2025
+			}
2026
+			parent::set('STS_ID', $new_status);
2027
+			return true;
2028
+		}
2029
+		return false;
2030
+	}
2031
+
2032
+
2033
+	/*************************** DEPRECATED ***************************/
2034
+
2035
+
2036
+	/**
2037
+	 * @deprecated
2038
+	 * @since     4.7.0
2039
+	 * @access    public
2040
+	 */
2041
+	public function price_paid()
2042
+	{
2043
+		EE_Error::doing_it_wrong(
2044
+			'EE_Registration::price_paid()',
2045
+			esc_html__(
2046
+				'This method is deprecated, please use EE_Registration::final_price() instead.',
2047
+				'event_espresso'
2048
+			),
2049
+			'4.7.0'
2050
+		);
2051
+		return $this->final_price();
2052
+	}
2053
+
2054
+
2055
+	/**
2056
+	 * @deprecated
2057
+	 * @since     4.7.0
2058
+	 * @access    public
2059
+	 * @param    float $REG_final_price
2060
+	 * @throws EE_Error
2061
+	 * @throws RuntimeException
2062
+	 */
2063
+	public function set_price_paid($REG_final_price = 0.00)
2064
+	{
2065
+		EE_Error::doing_it_wrong(
2066
+			'EE_Registration::set_price_paid()',
2067
+			esc_html__(
2068
+				'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2069
+				'event_espresso'
2070
+			),
2071
+			'4.7.0'
2072
+		);
2073
+		$this->set_final_price($REG_final_price);
2074
+	}
2075
+
2076
+
2077
+	/**
2078
+	 * @deprecated
2079
+	 * @since 4.7.0
2080
+	 * @return string
2081
+	 * @throws EE_Error
2082
+	 */
2083
+	public function pretty_price_paid()
2084
+	{
2085
+		EE_Error::doing_it_wrong(
2086
+			'EE_Registration::pretty_price_paid()',
2087
+			esc_html__(
2088
+				'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2089
+				'event_espresso'
2090
+			),
2091
+			'4.7.0'
2092
+		);
2093
+		return $this->pretty_final_price();
2094
+	}
2095
+
2096
+
2097
+	/**
2098
+	 * Gets the primary datetime related to this registration via the related Event to this registration
2099
+	 *
2100
+	 * @deprecated 4.9.17
2101
+	 * @return EE_Datetime
2102
+	 * @throws EE_Error
2103
+	 * @throws EntityNotFoundException
2104
+	 */
2105
+	public function get_related_primary_datetime()
2106
+	{
2107
+		EE_Error::doing_it_wrong(
2108
+			__METHOD__,
2109
+			esc_html__(
2110
+				'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2111
+				'event_espresso'
2112
+			),
2113
+			'4.9.17',
2114
+			'5.0.0'
2115
+		);
2116
+		return $this->event()->primary_datetime();
2117
+	}
2118
+
2119
+	/**
2120
+	 * Returns the contact's name (or "Unknown" if there is no contact.)
2121
+	 * @since 4.10.12.p
2122
+	 * @return string
2123
+	 * @throws EE_Error
2124
+	 * @throws InvalidArgumentException
2125
+	 * @throws InvalidDataTypeException
2126
+	 * @throws InvalidInterfaceException
2127
+	 * @throws ReflectionException
2128
+	 */
2129
+	public function name()
2130
+	{
2131
+		return $this->attendeeName();
2132
+	}
2133 2133
 }
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   +3347 added lines, -3347 removed lines patch added patch discarded remove patch
@@ -13,3363 +13,3363 @@
 block discarded – undo
13 13
 abstract class EE_Base_Class
14 14
 {
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 $this->get_pretty($field_name, $extra_cache_ref); // sanitized
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 = 'T', $datetime_value, $fieldname)
1582
-    {
1583
-        $field = $this->_get_dtt_field_settings($fieldname);
1584
-        $field->set_timezone($this->_timezone);
1585
-        $field->set_date_format($this->_dt_frmt);
1586
-        $field->set_time_format($this->_tm_frmt);
1587
-        switch ($what) {
1588
-            case 'T':
1589
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1590
-                    $datetime_value,
1591
-                    $this->_fields[ $fieldname ]
1592
-                );
1593
-                $this->_has_changes = true;
1594
-                break;
1595
-            case 'D':
1596
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1597
-                    $datetime_value,
1598
-                    $this->_fields[ $fieldname ]
1599
-                );
1600
-                $this->_has_changes = true;
1601
-                break;
1602
-            case 'B':
1603
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1604
-                $this->_has_changes = true;
1605
-                break;
1606
-        }
1607
-        $this->_clear_cached_property($fieldname);
1608
-    }
1609
-
1610
-
1611
-    /**
1612
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1613
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1614
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1615
-     * that could lead to some unexpected results!
1616
-     *
1617
-     * @access public
1618
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1619
-     *                                         value being returned.
1620
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1621
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1622
-     * @param string $prepend                  You can include something to prepend on the timestamp
1623
-     * @param string $append                   You can include something to append on the timestamp
1624
-     * @throws ReflectionException
1625
-     * @throws InvalidArgumentException
1626
-     * @throws InvalidInterfaceException
1627
-     * @throws InvalidDataTypeException
1628
-     * @throws EE_Error
1629
-     * @return string timestamp
1630
-     */
1631
-    public function display_in_my_timezone(
1632
-        $field_name,
1633
-        $callback = 'get_datetime',
1634
-        $args = null,
1635
-        $prepend = '',
1636
-        $append = ''
1637
-    ) {
1638
-        $timezone = EEH_DTT_Helper::get_timezone();
1639
-        if ($timezone === $this->_timezone) {
1640
-            return '';
1641
-        }
1642
-        $original_timezone = $this->_timezone;
1643
-        $this->set_timezone($timezone);
1644
-        $fn = (array) $field_name;
1645
-        $args = array_merge($fn, (array) $args);
1646
-        if (! method_exists($this, $callback)) {
1647
-            throw new EE_Error(
1648
-                sprintf(
1649
-                    esc_html__(
1650
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1651
-                        'event_espresso'
1652
-                    ),
1653
-                    $callback
1654
-                )
1655
-            );
1656
-        }
1657
-        $args = (array) $args;
1658
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1659
-        $this->set_timezone($original_timezone);
1660
-        return $return;
1661
-    }
1662
-
1663
-
1664
-    /**
1665
-     * Deletes this model object.
1666
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1667
-     * override
1668
-     * `EE_Base_Class::_delete` NOT this class.
1669
-     *
1670
-     * @return boolean | int
1671
-     * @throws ReflectionException
1672
-     * @throws InvalidArgumentException
1673
-     * @throws InvalidInterfaceException
1674
-     * @throws InvalidDataTypeException
1675
-     * @throws EE_Error
1676
-     */
1677
-    public function delete()
1678
-    {
1679
-        /**
1680
-         * Called just before the `EE_Base_Class::_delete` method call.
1681
-         * Note:
1682
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
-         * should be aware that `_delete` may not always result in a permanent delete.
1684
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1685
-         * soft deletes (trash) the object and does not permanently delete it.
1686
-         *
1687
-         * @param EE_Base_Class $model_object about to be 'deleted'
1688
-         */
1689
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1690
-        $result = $this->_delete();
1691
-        /**
1692
-         * Called just after the `EE_Base_Class::_delete` method call.
1693
-         * Note:
1694
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1695
-         * should be aware that `_delete` may not always result in a permanent delete.
1696
-         * For example `EE_Soft_Base_Class::_delete`
1697
-         * soft deletes (trash) the object and does not permanently delete it.
1698
-         *
1699
-         * @param EE_Base_Class $model_object that was just 'deleted'
1700
-         * @param boolean       $result
1701
-         */
1702
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1703
-        return $result;
1704
-    }
1705
-
1706
-
1707
-    /**
1708
-     * Calls the specific delete method for the instantiated class.
1709
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1710
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1711
-     * `EE_Base_Class::delete`
1712
-     *
1713
-     * @return bool|int
1714
-     * @throws ReflectionException
1715
-     * @throws InvalidArgumentException
1716
-     * @throws InvalidInterfaceException
1717
-     * @throws InvalidDataTypeException
1718
-     * @throws EE_Error
1719
-     */
1720
-    protected function _delete()
1721
-    {
1722
-        return $this->delete_permanently();
1723
-    }
1724
-
1725
-
1726
-    /**
1727
-     * Deletes this model object permanently from db
1728
-     * (but keep in mind related models may block the delete and return an error)
1729
-     *
1730
-     * @return bool | int
1731
-     * @throws ReflectionException
1732
-     * @throws InvalidArgumentException
1733
-     * @throws InvalidInterfaceException
1734
-     * @throws InvalidDataTypeException
1735
-     * @throws EE_Error
1736
-     */
1737
-    public function delete_permanently()
1738
-    {
1739
-        /**
1740
-         * Called just before HARD deleting a model object
1741
-         *
1742
-         * @param EE_Base_Class $model_object about to be 'deleted'
1743
-         */
1744
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1745
-        $model = $this->get_model();
1746
-        $result = $model->delete_permanently_by_ID($this->ID());
1747
-        $this->refresh_cache_of_related_objects();
1748
-        /**
1749
-         * Called just after HARD deleting a model object
1750
-         *
1751
-         * @param EE_Base_Class $model_object that was just 'deleted'
1752
-         * @param boolean       $result
1753
-         */
1754
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1755
-        return $result;
1756
-    }
1757
-
1758
-
1759
-    /**
1760
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1761
-     * related model objects
1762
-     *
1763
-     * @throws ReflectionException
1764
-     * @throws InvalidArgumentException
1765
-     * @throws InvalidInterfaceException
1766
-     * @throws InvalidDataTypeException
1767
-     * @throws EE_Error
1768
-     */
1769
-    public function refresh_cache_of_related_objects()
1770
-    {
1771
-        $model = $this->get_model();
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 ];
1775
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776
-                    // this relation only stores a single model object, not an array
1777
-                    // but let's make it consistent
1778
-                    $related_objects = array($related_objects);
1779
-                }
1780
-                foreach ($related_objects as $related_object) {
1781
-                    // only refresh their cache if they're in memory
1782
-                    if ($related_object instanceof EE_Base_Class) {
1783
-                        $related_object->clear_cache(
1784
-                            $model->get_this_model_name(),
1785
-                            $this
1786
-                        );
1787
-                    }
1788
-                }
1789
-            }
1790
-        }
1791
-    }
1792
-
1793
-
1794
-    /**
1795
-     *        Saves this object to the database. An array may be supplied to set some values on this
1796
-     * object just before saving.
1797
-     *
1798
-     * @access public
1799
-     * @param array $set_cols_n_values  keys are field names, values are their new values,
1800
-     *                                  if provided during the save() method
1801
-     *                                  (often client code will change the fields' values before calling save)
1802
-     * @return false|int|string         1 on a successful update;
1803
-     *                                  the ID of the new entry on insert;
1804
-     *                                  0 on failure, or if the model object isn't allowed to persist
1805
-     *                                  (as determined by EE_Base_Class::allow_persist())
1806
-     * @throws InvalidInterfaceException
1807
-     * @throws InvalidDataTypeException
1808
-     * @throws EE_Error
1809
-     * @throws InvalidArgumentException
1810
-     * @throws ReflectionException
1811
-     * @throws ReflectionException
1812
-     * @throws ReflectionException
1813
-     */
1814
-    public function save($set_cols_n_values = array())
1815
-    {
1816
-        $model = $this->get_model();
1817
-        /**
1818
-         * Filters the fields we're about to save on the model object
1819
-         *
1820
-         * @param array         $set_cols_n_values
1821
-         * @param EE_Base_Class $model_object
1822
-         */
1823
-        $set_cols_n_values = (array) apply_filters(
1824
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1825
-            $set_cols_n_values,
1826
-            $this
1827
-        );
1828
-        // set attributes as provided in $set_cols_n_values
1829
-        foreach ($set_cols_n_values as $column => $value) {
1830
-            $this->set($column, $value);
1831
-        }
1832
-        // no changes ? then don't do anything
1833
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834
-            return 0;
1835
-        }
1836
-        /**
1837
-         * Saving a model object.
1838
-         * Before we perform a save, this action is fired.
1839
-         *
1840
-         * @param EE_Base_Class $model_object the model object about to be saved.
1841
-         */
1842
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
-        if (! $this->allow_persist()) {
1844
-            return 0;
1845
-        }
1846
-        // now get current attribute values
1847
-        $save_cols_n_values = $this->_fields;
1848
-        // if the object already has an ID, update it. Otherwise, insert it
1849
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1850
-        // They have been
1851
-        $old_assumption_concerning_value_preparation = $model
1852
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1853
-        $model->assume_values_already_prepared_by_model_object(true);
1854
-        // does this model have an autoincrement PK?
1855
-        if ($model->has_primary_key_field()) {
1856
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1857
-                // ok check if it's set, if so: update; if not, insert
1858
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1859
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860
-                } else {
1861
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1862
-                    $results = $model->insert($save_cols_n_values);
1863
-                    if ($results) {
1864
-                        // if successful, set the primary key
1865
-                        // but don't use the normal SET method, because it will check if
1866
-                        // an item with the same ID exists in the mapper & db, then
1867
-                        // will find it in the db (because we just added it) and THAT object
1868
-                        // will get added to the mapper before we can add this one!
1869
-                        // but if we just avoid using the SET method, all that headache can be avoided
1870
-                        $pk_field_name = $model->primary_key_name();
1871
-                        $this->_fields[ $pk_field_name ] = $results;
1872
-                        $this->_clear_cached_property($pk_field_name);
1873
-                        $model->add_to_entity_map($this);
1874
-                        $this->_update_cached_related_model_objs_fks();
1875
-                    }
1876
-                }
1877
-            } else {// PK is NOT auto-increment
1878
-                // so check if one like it already exists in the db
1879
-                if ($model->exists_by_ID($this->ID())) {
1880
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1881
-                        throw new EE_Error(
1882
-                            sprintf(
1883
-                                esc_html__(
1884
-                                    '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',
1885
-                                    'event_espresso'
1886
-                                ),
1887
-                                get_class($this),
1888
-                                get_class($model) . '::instance()->add_to_entity_map()',
1889
-                                get_class($model) . '::instance()->get_one_by_ID()',
1890
-                                '<br />'
1891
-                            )
1892
-                        );
1893
-                    }
1894
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1895
-                } else {
1896
-                    $results = $model->insert($save_cols_n_values);
1897
-                    $this->_update_cached_related_model_objs_fks();
1898
-                }
1899
-            }
1900
-        } else {// there is NO primary key
1901
-            $already_in_db = false;
1902
-            foreach ($model->unique_indexes() as $index) {
1903
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1904
-                if ($model->exists(array($uniqueness_where_params))) {
1905
-                    $already_in_db = true;
1906
-                }
1907
-            }
1908
-            if ($already_in_db) {
1909
-                $combined_pk_fields_n_values = array_intersect_key(
1910
-                    $save_cols_n_values,
1911
-                    $model->get_combined_primary_key_fields()
1912
-                );
1913
-                $results = $model->update(
1914
-                    $save_cols_n_values,
1915
-                    $combined_pk_fields_n_values
1916
-                );
1917
-            } else {
1918
-                $results = $model->insert($save_cols_n_values);
1919
-            }
1920
-        }
1921
-        // restore the old assumption about values being prepared by the model object
1922
-        $model->assume_values_already_prepared_by_model_object(
1923
-            $old_assumption_concerning_value_preparation
1924
-        );
1925
-        /**
1926
-         * After saving the model object this action is called
1927
-         *
1928
-         * @param EE_Base_Class $model_object which was just saved
1929
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1930
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1931
-         */
1932
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1933
-        $this->_has_changes = false;
1934
-        return $results;
1935
-    }
1936
-
1937
-
1938
-    /**
1939
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1940
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1941
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1942
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1943
-     * 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
1944
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1945
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1946
-     *
1947
-     * @return void
1948
-     * @throws ReflectionException
1949
-     * @throws InvalidArgumentException
1950
-     * @throws InvalidInterfaceException
1951
-     * @throws InvalidDataTypeException
1952
-     * @throws EE_Error
1953
-     */
1954
-    protected function _update_cached_related_model_objs_fks()
1955
-    {
1956
-        $model = $this->get_model();
1957
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1958
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1959
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1960
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1961
-                        $model->get_this_model_name()
1962
-                    );
1963
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1964
-                    if ($related_model_obj_in_cache->ID()) {
1965
-                        $related_model_obj_in_cache->save();
1966
-                    }
1967
-                }
1968
-            }
1969
-        }
1970
-    }
1971
-
1972
-
1973
-    /**
1974
-     * Saves this model object and its NEW cached relations to the database.
1975
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1976
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1977
-     * because otherwise, there's a potential for infinite looping of saving
1978
-     * Saves the cached related model objects, and ensures the relation between them
1979
-     * and this object and properly setup
1980
-     *
1981
-     * @return int ID of new model object on save; 0 on failure+
1982
-     * @throws ReflectionException
1983
-     * @throws InvalidArgumentException
1984
-     * @throws InvalidInterfaceException
1985
-     * @throws InvalidDataTypeException
1986
-     * @throws EE_Error
1987
-     */
1988
-    public function save_new_cached_related_model_objs()
1989
-    {
1990
-        // make sure this has been saved
1991
-        if (! $this->ID()) {
1992
-            $id = $this->save();
1993
-        } else {
1994
-            $id = $this->ID();
1995
-        }
1996
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1997
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
-            if ($this->_model_relations[ $relationName ]) {
1999
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001
-                /* @var $related_model_obj EE_Base_Class */
2002
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
2003
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
2004
-                    // but ONLY if it DOES NOT exist in the DB
2005
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2006
-                    // if( ! $related_model_obj->ID()){
2007
-                    $this->_add_relation_to($related_model_obj, $relationName);
2008
-                    $related_model_obj->save_new_cached_related_model_objs();
2009
-                    // }
2010
-                } else {
2011
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2012
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2013
-                        // but ONLY if it DOES NOT exist in the DB
2014
-                        // if( ! $related_model_obj->ID()){
2015
-                        $this->_add_relation_to($related_model_obj, $relationName);
2016
-                        $related_model_obj->save_new_cached_related_model_objs();
2017
-                        // }
2018
-                    }
2019
-                }
2020
-            }
2021
-        }
2022
-        return $id;
2023
-    }
2024
-
2025
-
2026
-    /**
2027
-     * for getting a model while instantiated.
2028
-     *
2029
-     * @return EEM_Base | EEM_CPT_Base
2030
-     * @throws ReflectionException
2031
-     * @throws InvalidArgumentException
2032
-     * @throws InvalidInterfaceException
2033
-     * @throws InvalidDataTypeException
2034
-     * @throws EE_Error
2035
-     */
2036
-    public function get_model()
2037
-    {
2038
-        if (! $this->_model) {
2039
-            $modelName = self::_get_model_classname(get_class($this));
2040
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041
-        } else {
2042
-            $this->_model->set_timezone($this->_timezone);
2043
-        }
2044
-        return $this->_model;
2045
-    }
2046
-
2047
-
2048
-    /**
2049
-     * @param $props_n_values
2050
-     * @param $classname
2051
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2052
-     * @throws ReflectionException
2053
-     * @throws InvalidArgumentException
2054
-     * @throws InvalidInterfaceException
2055
-     * @throws InvalidDataTypeException
2056
-     * @throws EE_Error
2057
-     */
2058
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2059
-    {
2060
-        // TODO: will not work for Term_Relationships because they have no PK!
2061
-        $primary_id_ref = self::_get_primary_key_name($classname);
2062
-        if (
2063
-            array_key_exists($primary_id_ref, $props_n_values)
2064
-            && ! empty($props_n_values[ $primary_id_ref ])
2065
-        ) {
2066
-            $id = $props_n_values[ $primary_id_ref ];
2067
-            return self::_get_model($classname)->get_from_entity_map($id);
2068
-        }
2069
-        return false;
2070
-    }
2071
-
2072
-
2073
-    /**
2074
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2075
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2076
-     * 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
2077
-     * we return false.
2078
-     *
2079
-     * @param  array  $props_n_values   incoming array of properties and their values
2080
-     * @param  string $classname        the classname of the child class
2081
-     * @param null    $timezone
2082
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2083
-     *                                  date_format and the second value is the time format
2084
-     * @return mixed (EE_Base_Class|bool)
2085
-     * @throws InvalidArgumentException
2086
-     * @throws InvalidInterfaceException
2087
-     * @throws InvalidDataTypeException
2088
-     * @throws EE_Error
2089
-     * @throws ReflectionException
2090
-     * @throws ReflectionException
2091
-     * @throws ReflectionException
2092
-     */
2093
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2094
-    {
2095
-        $existing = null;
2096
-        $model = self::_get_model($classname, $timezone);
2097
-        if ($model->has_primary_key_field()) {
2098
-            $primary_id_ref = self::_get_primary_key_name($classname);
2099
-            if (
2100
-                array_key_exists($primary_id_ref, $props_n_values)
2101
-                && ! empty($props_n_values[ $primary_id_ref ])
2102
-            ) {
2103
-                $existing = $model->get_one_by_ID(
2104
-                    $props_n_values[ $primary_id_ref ]
2105
-                );
2106
-            }
2107
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2108
-            // no primary key on this model, but there's still a matching item in the DB
2109
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2110
-                self::_get_model($classname, $timezone)
2111
-                    ->get_index_primary_key_string($props_n_values)
2112
-            );
2113
-        }
2114
-        if ($existing) {
2115
-            // set date formats if present before setting values
2116
-            if (! empty($date_formats) && is_array($date_formats)) {
2117
-                $existing->set_date_format($date_formats[0]);
2118
-                $existing->set_time_format($date_formats[1]);
2119
-            } else {
2120
-                // set default formats for date and time
2121
-                $existing->set_date_format(get_option('date_format'));
2122
-                $existing->set_time_format(get_option('time_format'));
2123
-            }
2124
-            foreach ($props_n_values as $property => $field_value) {
2125
-                $existing->set($property, $field_value);
2126
-            }
2127
-            return $existing;
2128
-        }
2129
-        return false;
2130
-    }
2131
-
2132
-
2133
-    /**
2134
-     * Gets the EEM_*_Model for this class
2135
-     *
2136
-     * @access public now, as this is more convenient
2137
-     * @param      $classname
2138
-     * @param null $timezone
2139
-     * @throws ReflectionException
2140
-     * @throws InvalidArgumentException
2141
-     * @throws InvalidInterfaceException
2142
-     * @throws InvalidDataTypeException
2143
-     * @throws EE_Error
2144
-     * @return EEM_Base
2145
-     */
2146
-    protected static function _get_model($classname, $timezone = null)
2147
-    {
2148
-        // find model for this class
2149
-        if (! $classname) {
2150
-            throw new EE_Error(
2151
-                sprintf(
2152
-                    esc_html__(
2153
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2154
-                        'event_espresso'
2155
-                    ),
2156
-                    $classname
2157
-                )
2158
-            );
2159
-        }
2160
-        $modelName = self::_get_model_classname($classname);
2161
-        return self::_get_model_instance_with_name($modelName, $timezone);
2162
-    }
2163
-
2164
-
2165
-    /**
2166
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2167
-     *
2168
-     * @param string $model_classname
2169
-     * @param null   $timezone
2170
-     * @return EEM_Base
2171
-     * @throws ReflectionException
2172
-     * @throws InvalidArgumentException
2173
-     * @throws InvalidInterfaceException
2174
-     * @throws InvalidDataTypeException
2175
-     * @throws EE_Error
2176
-     */
2177
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2178
-    {
2179
-        $model_classname = str_replace('EEM_', '', $model_classname);
2180
-        $model = EE_Registry::instance()->load_model($model_classname);
2181
-        $model->set_timezone($timezone);
2182
-        return $model;
2183
-    }
2184
-
2185
-
2186
-    /**
2187
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2188
-     * Also works if a model class's classname is provided (eg EE_Registration).
2189
-     *
2190
-     * @param null $model_name
2191
-     * @return string like EEM_Attendee
2192
-     */
2193
-    private static function _get_model_classname($model_name = null)
2194
-    {
2195
-        if (strpos($model_name, 'EE_') === 0) {
2196
-            $model_classname = str_replace('EE_', 'EEM_', $model_name);
2197
-        } else {
2198
-            $model_classname = 'EEM_' . $model_name;
2199
-        }
2200
-        return $model_classname;
2201
-    }
2202
-
2203
-
2204
-    /**
2205
-     * returns the name of the primary key attribute
2206
-     *
2207
-     * @param null $classname
2208
-     * @throws ReflectionException
2209
-     * @throws InvalidArgumentException
2210
-     * @throws InvalidInterfaceException
2211
-     * @throws InvalidDataTypeException
2212
-     * @throws EE_Error
2213
-     * @return string
2214
-     */
2215
-    protected static function _get_primary_key_name($classname = null)
2216
-    {
2217
-        if (! $classname) {
2218
-            throw new EE_Error(
2219
-                sprintf(
2220
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2221
-                    $classname
2222
-                )
2223
-            );
2224
-        }
2225
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2226
-    }
2227
-
2228
-
2229
-    /**
2230
-     * Gets the value of the primary key.
2231
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2232
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2233
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2234
-     *
2235
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2236
-     * @throws ReflectionException
2237
-     * @throws InvalidArgumentException
2238
-     * @throws InvalidInterfaceException
2239
-     * @throws InvalidDataTypeException
2240
-     * @throws EE_Error
2241
-     */
2242
-    public function ID()
2243
-    {
2244
-        $model = $this->get_model();
2245
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2246
-        if ($model->has_primary_key_field()) {
2247
-            return $this->_fields[ $model->primary_key_name() ];
2248
-        }
2249
-        return $model->get_index_primary_key_string($this->_fields);
2250
-    }
2251
-
2252
-
2253
-    /**
2254
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2255
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2256
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2257
-     *
2258
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2259
-     * @param string $relationName                     eg 'Events','Question',etc.
2260
-     *                                                 an attendee to a group, you also want to specify which role they
2261
-     *                                                 will have in that group. So you would use this parameter to
2262
-     *                                                 specify array('role-column-name'=>'role-id')
2263
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2264
-     *                                                 allow you to further constrict the relation to being added.
2265
-     *                                                 However, keep in mind that the columns (keys) given must match a
2266
-     *                                                 column on the JOIN table and currently only the HABTM models
2267
-     *                                                 accept these additional conditions.  Also remember that if an
2268
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2269
-     *                                                 NEW row is created in the join table.
2270
-     * @param null   $cache_id
2271
-     * @throws ReflectionException
2272
-     * @throws InvalidArgumentException
2273
-     * @throws InvalidInterfaceException
2274
-     * @throws InvalidDataTypeException
2275
-     * @throws EE_Error
2276
-     * @return EE_Base_Class the object the relation was added to
2277
-     */
2278
-    public function _add_relation_to(
2279
-        $otherObjectModelObjectOrID,
2280
-        $relationName,
2281
-        $extra_join_model_fields_n_values = array(),
2282
-        $cache_id = null
2283
-    ) {
2284
-        $model = $this->get_model();
2285
-        // if this thing exists in the DB, save the relation to the DB
2286
-        if ($this->ID()) {
2287
-            $otherObject = $model->add_relationship_to(
2288
-                $this,
2289
-                $otherObjectModelObjectOrID,
2290
-                $relationName,
2291
-                $extra_join_model_fields_n_values
2292
-            );
2293
-            // clear cache so future get_many_related and get_first_related() return new results.
2294
-            $this->clear_cache($relationName, $otherObject, true);
2295
-            if ($otherObject instanceof EE_Base_Class) {
2296
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2297
-            }
2298
-        } else {
2299
-            // this thing doesn't exist in the DB,  so just cache it
2300
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2301
-                throw new EE_Error(
2302
-                    sprintf(
2303
-                        esc_html__(
2304
-                            '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',
2305
-                            'event_espresso'
2306
-                        ),
2307
-                        $otherObjectModelObjectOrID,
2308
-                        get_class($this)
2309
-                    )
2310
-                );
2311
-            }
2312
-            $otherObject = $otherObjectModelObjectOrID;
2313
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2314
-        }
2315
-        if ($otherObject instanceof EE_Base_Class) {
2316
-            // fix the reciprocal relation too
2317
-            if ($otherObject->ID()) {
2318
-                // its saved so assumed relations exist in the DB, so we can just
2319
-                // clear the cache so future queries use the updated info in the DB
2320
-                $otherObject->clear_cache(
2321
-                    $model->get_this_model_name(),
2322
-                    null,
2323
-                    true
2324
-                );
2325
-            } else {
2326
-                // it's not saved, so it caches relations like this
2327
-                $otherObject->cache($model->get_this_model_name(), $this);
2328
-            }
2329
-        }
2330
-        return $otherObject;
2331
-    }
2332
-
2333
-
2334
-    /**
2335
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2336
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2337
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2338
-     * from the cache
2339
-     *
2340
-     * @param mixed  $otherObjectModelObjectOrID
2341
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2342
-     *                to the DB yet
2343
-     * @param string $relationName
2344
-     * @param array  $where_query
2345
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2346
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2347
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2348
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2349
-     *                deleted.
2350
-     * @return EE_Base_Class the relation was removed from
2351
-     * @throws ReflectionException
2352
-     * @throws InvalidArgumentException
2353
-     * @throws InvalidInterfaceException
2354
-     * @throws InvalidDataTypeException
2355
-     * @throws EE_Error
2356
-     */
2357
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2358
-    {
2359
-        if ($this->ID()) {
2360
-            // if this exists in the DB, save the relation change to the DB too
2361
-            $otherObject = $this->get_model()->remove_relationship_to(
2362
-                $this,
2363
-                $otherObjectModelObjectOrID,
2364
-                $relationName,
2365
-                $where_query
2366
-            );
2367
-            $this->clear_cache(
2368
-                $relationName,
2369
-                $otherObject
2370
-            );
2371
-        } else {
2372
-            // this doesn't exist in the DB, just remove it from the cache
2373
-            $otherObject = $this->clear_cache(
2374
-                $relationName,
2375
-                $otherObjectModelObjectOrID
2376
-            );
2377
-        }
2378
-        if ($otherObject instanceof EE_Base_Class) {
2379
-            $otherObject->clear_cache(
2380
-                $this->get_model()->get_this_model_name(),
2381
-                $this
2382
-            );
2383
-        }
2384
-        return $otherObject;
2385
-    }
2386
-
2387
-
2388
-    /**
2389
-     * Removes ALL the related things for the $relationName.
2390
-     *
2391
-     * @param string $relationName
2392
-     * @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
2393
-     * @return EE_Base_Class
2394
-     * @throws ReflectionException
2395
-     * @throws InvalidArgumentException
2396
-     * @throws InvalidInterfaceException
2397
-     * @throws InvalidDataTypeException
2398
-     * @throws EE_Error
2399
-     */
2400
-    public function _remove_relations($relationName, $where_query_params = array())
2401
-    {
2402
-        if ($this->ID()) {
2403
-            // if this exists in the DB, save the relation change to the DB too
2404
-            $otherObjects = $this->get_model()->remove_relations(
2405
-                $this,
2406
-                $relationName,
2407
-                $where_query_params
2408
-            );
2409
-            $this->clear_cache(
2410
-                $relationName,
2411
-                null,
2412
-                true
2413
-            );
2414
-        } else {
2415
-            // this doesn't exist in the DB, just remove it from the cache
2416
-            $otherObjects = $this->clear_cache(
2417
-                $relationName,
2418
-                null,
2419
-                true
2420
-            );
2421
-        }
2422
-        if (is_array($otherObjects)) {
2423
-            foreach ($otherObjects as $otherObject) {
2424
-                $otherObject->clear_cache(
2425
-                    $this->get_model()->get_this_model_name(),
2426
-                    $this
2427
-                );
2428
-            }
2429
-        }
2430
-        return $otherObjects;
2431
-    }
2432
-
2433
-
2434
-    /**
2435
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2436
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2437
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2438
-     * because we want to get even deleted items etc.
2439
-     *
2440
-     * @param string $relationName key in the model's _model_relations array
2441
-     * @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
2442
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2443
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2444
-     *                             results if you want IDs
2445
-     * @throws ReflectionException
2446
-     * @throws InvalidArgumentException
2447
-     * @throws InvalidInterfaceException
2448
-     * @throws InvalidDataTypeException
2449
-     * @throws EE_Error
2450
-     */
2451
-    public function get_many_related($relationName, $query_params = array())
2452
-    {
2453
-        if ($this->ID()) {
2454
-            // this exists in the DB, so get the related things from either the cache or the DB
2455
-            // if there are query parameters, forget about caching the related model objects.
2456
-            if ($query_params) {
2457
-                $related_model_objects = $this->get_model()->get_all_related(
2458
-                    $this,
2459
-                    $relationName,
2460
-                    $query_params
2461
-                );
2462
-            } else {
2463
-                // did we already cache the result of this query?
2464
-                $cached_results = $this->get_all_from_cache($relationName);
2465
-                if (! $cached_results) {
2466
-                    $related_model_objects = $this->get_model()->get_all_related(
2467
-                        $this,
2468
-                        $relationName,
2469
-                        $query_params
2470
-                    );
2471
-                    // if no query parameters were passed, then we got all the related model objects
2472
-                    // for that relation. We can cache them then.
2473
-                    foreach ($related_model_objects as $related_model_object) {
2474
-                        $this->cache($relationName, $related_model_object);
2475
-                    }
2476
-                } else {
2477
-                    $related_model_objects = $cached_results;
2478
-                }
2479
-            }
2480
-        } else {
2481
-            // this doesn't exist in the DB, so just get the related things from the cache
2482
-            $related_model_objects = $this->get_all_from_cache($relationName);
2483
-        }
2484
-        return $related_model_objects;
2485
-    }
2486
-
2487
-
2488
-    /**
2489
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2490
-     * unless otherwise specified in the $query_params
2491
-     *
2492
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2493
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2494
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2495
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2496
-     *                               that by the setting $distinct to TRUE;
2497
-     * @return int
2498
-     * @throws ReflectionException
2499
-     * @throws InvalidArgumentException
2500
-     * @throws InvalidInterfaceException
2501
-     * @throws InvalidDataTypeException
2502
-     * @throws EE_Error
2503
-     */
2504
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2505
-    {
2506
-        return $this->get_model()->count_related(
2507
-            $this,
2508
-            $relation_name,
2509
-            $query_params,
2510
-            $field_to_count,
2511
-            $distinct
2512
-        );
2513
-    }
2514
-
2515
-
2516
-    /**
2517
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2518
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2519
-     *
2520
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2521
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2522
-     * @param string $field_to_sum  name of field to count by.
2523
-     *                              By default, uses primary key
2524
-     *                              (which doesn't make much sense, so you should probably change it)
2525
-     * @return int
2526
-     * @throws ReflectionException
2527
-     * @throws InvalidArgumentException
2528
-     * @throws InvalidInterfaceException
2529
-     * @throws InvalidDataTypeException
2530
-     * @throws EE_Error
2531
-     */
2532
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2533
-    {
2534
-        return $this->get_model()->sum_related(
2535
-            $this,
2536
-            $relation_name,
2537
-            $query_params,
2538
-            $field_to_sum
2539
-        );
2540
-    }
2541
-
2542
-
2543
-    /**
2544
-     * Gets the first (ie, one) related model object of the specified type.
2545
-     *
2546
-     * @param string $relationName key in the model's _model_relations array
2547
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2548
-     * @return EE_Base_Class (not an array, a single object)
2549
-     * @throws ReflectionException
2550
-     * @throws InvalidArgumentException
2551
-     * @throws InvalidInterfaceException
2552
-     * @throws InvalidDataTypeException
2553
-     * @throws EE_Error
2554
-     */
2555
-    public function get_first_related($relationName, $query_params = array())
2556
-    {
2557
-        $model = $this->get_model();
2558
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2559
-            // if they've provided some query parameters, don't bother trying to cache the result
2560
-            // also make sure we're not caching the result of get_first_related
2561
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2562
-            if (
2563
-                $query_params
2564
-                || ! $model->related_settings_for($relationName)
2565
-                     instanceof
2566
-                     EE_Belongs_To_Relation
2567
-            ) {
2568
-                $related_model_object = $model->get_first_related(
2569
-                    $this,
2570
-                    $relationName,
2571
-                    $query_params
2572
-                );
2573
-            } else {
2574
-                // first, check if we've already cached the result of this query
2575
-                $cached_result = $this->get_one_from_cache($relationName);
2576
-                if (! $cached_result) {
2577
-                    $related_model_object = $model->get_first_related(
2578
-                        $this,
2579
-                        $relationName,
2580
-                        $query_params
2581
-                    );
2582
-                    $this->cache($relationName, $related_model_object);
2583
-                } else {
2584
-                    $related_model_object = $cached_result;
2585
-                }
2586
-            }
2587
-        } else {
2588
-            $related_model_object = null;
2589
-            // this doesn't exist in the Db,
2590
-            // but maybe the relation is of type belongs to, and so the related thing might
2591
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2592
-                $related_model_object = $model->get_first_related(
2593
-                    $this,
2594
-                    $relationName,
2595
-                    $query_params
2596
-                );
2597
-            }
2598
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2599
-            // just get what's cached on this object
2600
-            if (! $related_model_object) {
2601
-                $related_model_object = $this->get_one_from_cache($relationName);
2602
-            }
2603
-        }
2604
-        return $related_model_object;
2605
-    }
2606
-
2607
-
2608
-    /**
2609
-     * Does a delete on all related objects of type $relationName and removes
2610
-     * the current model object's relation to them. If they can't be deleted (because
2611
-     * of blocking related model objects) does nothing. If the related model objects are
2612
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2613
-     * If this model object doesn't exist yet in the DB, just removes its related things
2614
-     *
2615
-     * @param string $relationName
2616
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2617
-     * @return int how many deleted
2618
-     * @throws ReflectionException
2619
-     * @throws InvalidArgumentException
2620
-     * @throws InvalidInterfaceException
2621
-     * @throws InvalidDataTypeException
2622
-     * @throws EE_Error
2623
-     */
2624
-    public function delete_related($relationName, $query_params = array())
2625
-    {
2626
-        if ($this->ID()) {
2627
-            $count = $this->get_model()->delete_related(
2628
-                $this,
2629
-                $relationName,
2630
-                $query_params
2631
-            );
2632
-        } else {
2633
-            $count = count($this->get_all_from_cache($relationName));
2634
-            $this->clear_cache($relationName, null, true);
2635
-        }
2636
-        return $count;
2637
-    }
2638
-
2639
-
2640
-    /**
2641
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2642
-     * the current model object's relation to them. If they can't be deleted (because
2643
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2644
-     * If the related thing isn't a soft-deletable model object, this function is identical
2645
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2646
-     *
2647
-     * @param string $relationName
2648
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2649
-     * @return int how many deleted (including those soft deleted)
2650
-     * @throws ReflectionException
2651
-     * @throws InvalidArgumentException
2652
-     * @throws InvalidInterfaceException
2653
-     * @throws InvalidDataTypeException
2654
-     * @throws EE_Error
2655
-     */
2656
-    public function delete_related_permanently($relationName, $query_params = array())
2657
-    {
2658
-        if ($this->ID()) {
2659
-            $count = $this->get_model()->delete_related_permanently(
2660
-                $this,
2661
-                $relationName,
2662
-                $query_params
2663
-            );
2664
-        } else {
2665
-            $count = count($this->get_all_from_cache($relationName));
2666
-        }
2667
-        $this->clear_cache($relationName, null, true);
2668
-        return $count;
2669
-    }
2670
-
2671
-
2672
-    /**
2673
-     * is_set
2674
-     * Just a simple utility function children can use for checking if property exists
2675
-     *
2676
-     * @access  public
2677
-     * @param  string $field_name property to check
2678
-     * @return bool                              TRUE if existing,FALSE if not.
2679
-     */
2680
-    public function is_set($field_name)
2681
-    {
2682
-        return isset($this->_fields[ $field_name ]);
2683
-    }
2684
-
2685
-
2686
-    /**
2687
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2688
-     * EE_Error exception if they don't
2689
-     *
2690
-     * @param  mixed (string|array) $properties properties to check
2691
-     * @throws EE_Error
2692
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2693
-     */
2694
-    protected function _property_exists($properties)
2695
-    {
2696
-        foreach ((array) $properties as $property_name) {
2697
-            // first make sure this property exists
2698
-            if (! $this->_fields[ $property_name ]) {
2699
-                throw new EE_Error(
2700
-                    sprintf(
2701
-                        esc_html__(
2702
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2703
-                            'event_espresso'
2704
-                        ),
2705
-                        $property_name
2706
-                    )
2707
-                );
2708
-            }
2709
-        }
2710
-        return true;
2711
-    }
2712
-
2713
-
2714
-    /**
2715
-     * This simply returns an array of model fields for this object
2716
-     *
2717
-     * @return array
2718
-     * @throws ReflectionException
2719
-     * @throws InvalidArgumentException
2720
-     * @throws InvalidInterfaceException
2721
-     * @throws InvalidDataTypeException
2722
-     * @throws EE_Error
2723
-     */
2724
-    public function model_field_array()
2725
-    {
2726
-        $fields = $this->get_model()->field_settings(false);
2727
-        $properties = array();
2728
-        // remove prepended underscore
2729
-        foreach ($fields as $field_name => $settings) {
2730
-            $properties[ $field_name ] = $this->get($field_name);
2731
-        }
2732
-        return $properties;
2733
-    }
2734
-
2735
-
2736
-    /**
2737
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2738
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2739
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2740
-     * Instead of requiring a plugin to extend the EE_Base_Class
2741
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2742
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2743
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2744
-     * and accepts 2 arguments: the object on which the function was called,
2745
-     * and an array of the original arguments passed to the function.
2746
-     * Whatever their callback function returns will be returned by this function.
2747
-     * Example: in functions.php (or in a plugin):
2748
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2749
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2750
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2751
-     *          return $previousReturnValue.$returnString;
2752
-     *      }
2753
-     * require('EE_Answer.class.php');
2754
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2755
-     * echo $answer->my_callback('monkeys',100);
2756
-     * //will output "you called my_callback! and passed args:monkeys,100"
2757
-     *
2758
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2759
-     * @param array  $args       array of original arguments passed to the function
2760
-     * @throws EE_Error
2761
-     * @return mixed whatever the plugin which calls add_filter decides
2762
-     */
2763
-    public function __call($methodName, $args)
2764
-    {
2765
-        $className = get_class($this);
2766
-        $tagName = "FHEE__{$className}__{$methodName}";
2767
-        if (! has_filter($tagName)) {
2768
-            throw new EE_Error(
2769
-                sprintf(
2770
-                    esc_html__(
2771
-                        "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;}",
2772
-                        'event_espresso'
2773
-                    ),
2774
-                    $methodName,
2775
-                    $className,
2776
-                    $tagName
2777
-                )
2778
-            );
2779
-        }
2780
-        return apply_filters($tagName, null, $this, $args);
2781
-    }
2782
-
2783
-
2784
-    /**
2785
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2786
-     * A $previous_value can be specified in case there are many meta rows with the same key
2787
-     *
2788
-     * @param string $meta_key
2789
-     * @param mixed  $meta_value
2790
-     * @param mixed  $previous_value
2791
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2792
-     *                  NOTE: if the values haven't changed, returns 0
2793
-     * @throws InvalidArgumentException
2794
-     * @throws InvalidInterfaceException
2795
-     * @throws InvalidDataTypeException
2796
-     * @throws EE_Error
2797
-     * @throws ReflectionException
2798
-     */
2799
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2800
-    {
2801
-        $query_params = array(
2802
-            array(
2803
-                'EXM_key'  => $meta_key,
2804
-                'OBJ_ID'   => $this->ID(),
2805
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2806
-            ),
2807
-        );
2808
-        if ($previous_value !== null) {
2809
-            $query_params[0]['EXM_value'] = $meta_value;
2810
-        }
2811
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2812
-        if (! $existing_rows_like_that) {
2813
-            return $this->add_extra_meta($meta_key, $meta_value);
2814
-        }
2815
-        foreach ($existing_rows_like_that as $existing_row) {
2816
-            $existing_row->save(array('EXM_value' => $meta_value));
2817
-        }
2818
-        return count($existing_rows_like_that);
2819
-    }
2820
-
2821
-
2822
-    /**
2823
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2824
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2825
-     * extra meta row was entered, false if not
2826
-     *
2827
-     * @param string  $meta_key
2828
-     * @param mixed   $meta_value
2829
-     * @param boolean $unique
2830
-     * @return boolean
2831
-     * @throws InvalidArgumentException
2832
-     * @throws InvalidInterfaceException
2833
-     * @throws InvalidDataTypeException
2834
-     * @throws EE_Error
2835
-     * @throws ReflectionException
2836
-     * @throws ReflectionException
2837
-     */
2838
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2839
-    {
2840
-        if ($unique) {
2841
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2842
-                array(
2843
-                    array(
2844
-                        'EXM_key'  => $meta_key,
2845
-                        'OBJ_ID'   => $this->ID(),
2846
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2847
-                    ),
2848
-                )
2849
-            );
2850
-            if ($existing_extra_meta) {
2851
-                return false;
2852
-            }
2853
-        }
2854
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2855
-            array(
2856
-                'EXM_key'   => $meta_key,
2857
-                'EXM_value' => $meta_value,
2858
-                'OBJ_ID'    => $this->ID(),
2859
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2860
-            )
2861
-        );
2862
-        $new_extra_meta->save();
2863
-        return true;
2864
-    }
2865
-
2866
-
2867
-    /**
2868
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2869
-     * is specified, only deletes extra meta records with that value.
2870
-     *
2871
-     * @param string $meta_key
2872
-     * @param mixed  $meta_value
2873
-     * @return int number of extra meta rows deleted
2874
-     * @throws InvalidArgumentException
2875
-     * @throws InvalidInterfaceException
2876
-     * @throws InvalidDataTypeException
2877
-     * @throws EE_Error
2878
-     * @throws ReflectionException
2879
-     */
2880
-    public function delete_extra_meta($meta_key, $meta_value = null)
2881
-    {
2882
-        $query_params = array(
2883
-            array(
2884
-                'EXM_key'  => $meta_key,
2885
-                'OBJ_ID'   => $this->ID(),
2886
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2887
-            ),
2888
-        );
2889
-        if ($meta_value !== null) {
2890
-            $query_params[0]['EXM_value'] = $meta_value;
2891
-        }
2892
-        return EEM_Extra_Meta::instance()->delete($query_params);
2893
-    }
2894
-
2895
-
2896
-    /**
2897
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2898
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2899
-     * You can specify $default is case you haven't found the extra meta
2900
-     *
2901
-     * @param string  $meta_key
2902
-     * @param boolean $single
2903
-     * @param mixed   $default if we don't find anything, what should we return?
2904
-     * @return mixed single value if $single; array if ! $single
2905
-     * @throws ReflectionException
2906
-     * @throws InvalidArgumentException
2907
-     * @throws InvalidInterfaceException
2908
-     * @throws InvalidDataTypeException
2909
-     * @throws EE_Error
2910
-     */
2911
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2912
-    {
2913
-        if ($single) {
2914
-            $result = $this->get_first_related(
2915
-                'Extra_Meta',
2916
-                array(array('EXM_key' => $meta_key))
2917
-            );
2918
-            if ($result instanceof EE_Extra_Meta) {
2919
-                return $result->value();
2920
-            }
2921
-        } else {
2922
-            $results = $this->get_many_related(
2923
-                'Extra_Meta',
2924
-                array(array('EXM_key' => $meta_key))
2925
-            );
2926
-            if ($results) {
2927
-                $values = array();
2928
-                foreach ($results as $result) {
2929
-                    if ($result instanceof EE_Extra_Meta) {
2930
-                        $values[ $result->ID() ] = $result->value();
2931
-                    }
2932
-                }
2933
-                return $values;
2934
-            }
2935
-        }
2936
-        // if nothing discovered yet return default.
2937
-        return apply_filters(
2938
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2939
-            $default,
2940
-            $meta_key,
2941
-            $single,
2942
-            $this
2943
-        );
2944
-    }
2945
-
2946
-
2947
-    /**
2948
-     * Returns a simple array of all the extra meta associated with this model object.
2949
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2950
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2951
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2952
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2953
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2954
-     * finally the extra meta's value as each sub-value. (eg
2955
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2956
-     *
2957
-     * @param boolean $one_of_each_key
2958
-     * @return array
2959
-     * @throws ReflectionException
2960
-     * @throws InvalidArgumentException
2961
-     * @throws InvalidInterfaceException
2962
-     * @throws InvalidDataTypeException
2963
-     * @throws EE_Error
2964
-     */
2965
-    public function all_extra_meta_array($one_of_each_key = true)
2966
-    {
2967
-        $return_array = array();
2968
-        if ($one_of_each_key) {
2969
-            $extra_meta_objs = $this->get_many_related(
2970
-                'Extra_Meta',
2971
-                array('group_by' => 'EXM_key')
2972
-            );
2973
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2974
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2975
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2976
-                }
2977
-            }
2978
-        } else {
2979
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2980
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2981
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2982
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2983
-                        $return_array[ $extra_meta_obj->key() ] = array();
2984
-                    }
2985
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2986
-                }
2987
-            }
2988
-        }
2989
-        return $return_array;
2990
-    }
2991
-
2992
-
2993
-    /**
2994
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2995
-     *
2996
-     * @return string
2997
-     * @throws ReflectionException
2998
-     * @throws InvalidArgumentException
2999
-     * @throws InvalidInterfaceException
3000
-     * @throws InvalidDataTypeException
3001
-     * @throws EE_Error
3002
-     */
3003
-    public function name()
3004
-    {
3005
-        // find a field that's not a text field
3006
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3007
-        if ($field_we_can_use) {
3008
-            return $this->get($field_we_can_use->get_name());
3009
-        }
3010
-        $first_few_properties = $this->model_field_array();
3011
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3012
-        $name_parts = array();
3013
-        foreach ($first_few_properties as $name => $value) {
3014
-            $name_parts[] = "$name:$value";
3015
-        }
3016
-        return implode(',', $name_parts);
3017
-    }
3018
-
3019
-
3020
-    /**
3021
-     * in_entity_map
3022
-     * Checks if this model object has been proven to already be in the entity map
3023
-     *
3024
-     * @return boolean
3025
-     * @throws ReflectionException
3026
-     * @throws InvalidArgumentException
3027
-     * @throws InvalidInterfaceException
3028
-     * @throws InvalidDataTypeException
3029
-     * @throws EE_Error
3030
-     */
3031
-    public function in_entity_map()
3032
-    {
3033
-        // well, if we looked, did we find it in the entity map?
3034
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3035
-    }
3036
-
3037
-
3038
-    /**
3039
-     * refresh_from_db
3040
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3041
-     *
3042
-     * @throws ReflectionException
3043
-     * @throws InvalidArgumentException
3044
-     * @throws InvalidInterfaceException
3045
-     * @throws InvalidDataTypeException
3046
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3047
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3048
-     */
3049
-    public function refresh_from_db()
3050
-    {
3051
-        if ($this->ID() && $this->in_entity_map()) {
3052
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3053
-        } else {
3054
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3055
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3056
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3057
-            // absolutely nothing in it for this ID
3058
-            if (WP_DEBUG) {
3059
-                throw new EE_Error(
3060
-                    sprintf(
3061
-                        esc_html__(
3062
-                            '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.',
3063
-                            'event_espresso'
3064
-                        ),
3065
-                        $this->ID(),
3066
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3067
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3068
-                    )
3069
-                );
3070
-            }
3071
-        }
3072
-    }
3073
-
3074
-
3075
-    /**
3076
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3077
-     *
3078
-     * @since 4.9.80.p
3079
-     * @param EE_Model_Field_Base[] $fields
3080
-     * @param string $new_value_sql
3081
-     *      example: 'column_name=123',
3082
-     *      or 'column_name=column_name+1',
3083
-     *      or 'column_name= CASE
3084
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3085
-     *          THEN `column_name` + 5
3086
-     *          ELSE `column_name`
3087
-     *      END'
3088
-     *      Also updates $field on this model object with the latest value from the database.
3089
-     * @return bool
3090
-     * @throws EE_Error
3091
-     * @throws InvalidArgumentException
3092
-     * @throws InvalidDataTypeException
3093
-     * @throws InvalidInterfaceException
3094
-     * @throws ReflectionException
3095
-     */
3096
-    protected function updateFieldsInDB($fields, $new_value_sql)
3097
-    {
3098
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3099
-        // if it wasn't even there to start off.
3100
-        if (! $this->ID()) {
3101
-            $this->save();
3102
-        }
3103
-        global $wpdb;
3104
-        if (empty($fields)) {
3105
-            throw new InvalidArgumentException(
3106
-                esc_html__(
3107
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3108
-                    'event_espresso'
3109
-                )
3110
-            );
3111
-        }
3112
-        $first_field = reset($fields);
3113
-        $table_alias = $first_field->get_table_alias();
3114
-        foreach ($fields as $field) {
3115
-            if ($table_alias !== $field->get_table_alias()) {
3116
-                throw new InvalidArgumentException(
3117
-                    sprintf(
3118
-                        esc_html__(
3119
-                            // @codingStandardsIgnoreStart
3120
-                            '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.',
3121
-                            // @codingStandardsIgnoreEnd
3122
-                            'event_espresso'
3123
-                        ),
3124
-                        $table_alias,
3125
-                        $field->get_table_alias()
3126
-                    )
3127
-                );
3128
-            }
3129
-        }
3130
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3131
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3132
-        $table_pk_value = $this->ID();
3133
-        $table_name = $table_obj->get_table_name();
3134
-        if ($table_obj instanceof EE_Secondary_Table) {
3135
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3136
-        } else {
3137
-            $table_pk_field_name = $table_obj->get_pk_column();
3138
-        }
3139
-
3140
-        $query =
3141
-            "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 $this->get_pretty($field_name, $extra_cache_ref); // sanitized
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 = 'T', $datetime_value, $fieldname)
1582
+	{
1583
+		$field = $this->_get_dtt_field_settings($fieldname);
1584
+		$field->set_timezone($this->_timezone);
1585
+		$field->set_date_format($this->_dt_frmt);
1586
+		$field->set_time_format($this->_tm_frmt);
1587
+		switch ($what) {
1588
+			case 'T':
1589
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1590
+					$datetime_value,
1591
+					$this->_fields[ $fieldname ]
1592
+				);
1593
+				$this->_has_changes = true;
1594
+				break;
1595
+			case 'D':
1596
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1597
+					$datetime_value,
1598
+					$this->_fields[ $fieldname ]
1599
+				);
1600
+				$this->_has_changes = true;
1601
+				break;
1602
+			case 'B':
1603
+				$this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1604
+				$this->_has_changes = true;
1605
+				break;
1606
+		}
1607
+		$this->_clear_cached_property($fieldname);
1608
+	}
1609
+
1610
+
1611
+	/**
1612
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1613
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1614
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1615
+	 * that could lead to some unexpected results!
1616
+	 *
1617
+	 * @access public
1618
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1619
+	 *                                         value being returned.
1620
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1621
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1622
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1623
+	 * @param string $append                   You can include something to append on the timestamp
1624
+	 * @throws ReflectionException
1625
+	 * @throws InvalidArgumentException
1626
+	 * @throws InvalidInterfaceException
1627
+	 * @throws InvalidDataTypeException
1628
+	 * @throws EE_Error
1629
+	 * @return string timestamp
1630
+	 */
1631
+	public function display_in_my_timezone(
1632
+		$field_name,
1633
+		$callback = 'get_datetime',
1634
+		$args = null,
1635
+		$prepend = '',
1636
+		$append = ''
1637
+	) {
1638
+		$timezone = EEH_DTT_Helper::get_timezone();
1639
+		if ($timezone === $this->_timezone) {
1640
+			return '';
1641
+		}
1642
+		$original_timezone = $this->_timezone;
1643
+		$this->set_timezone($timezone);
1644
+		$fn = (array) $field_name;
1645
+		$args = array_merge($fn, (array) $args);
1646
+		if (! method_exists($this, $callback)) {
1647
+			throw new EE_Error(
1648
+				sprintf(
1649
+					esc_html__(
1650
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1651
+						'event_espresso'
1652
+					),
1653
+					$callback
1654
+				)
1655
+			);
1656
+		}
1657
+		$args = (array) $args;
1658
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1659
+		$this->set_timezone($original_timezone);
1660
+		return $return;
1661
+	}
1662
+
1663
+
1664
+	/**
1665
+	 * Deletes this model object.
1666
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1667
+	 * override
1668
+	 * `EE_Base_Class::_delete` NOT this class.
1669
+	 *
1670
+	 * @return boolean | int
1671
+	 * @throws ReflectionException
1672
+	 * @throws InvalidArgumentException
1673
+	 * @throws InvalidInterfaceException
1674
+	 * @throws InvalidDataTypeException
1675
+	 * @throws EE_Error
1676
+	 */
1677
+	public function delete()
1678
+	{
1679
+		/**
1680
+		 * Called just before the `EE_Base_Class::_delete` method call.
1681
+		 * Note:
1682
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
+		 * should be aware that `_delete` may not always result in a permanent delete.
1684
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1685
+		 * soft deletes (trash) the object and does not permanently delete it.
1686
+		 *
1687
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1688
+		 */
1689
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1690
+		$result = $this->_delete();
1691
+		/**
1692
+		 * Called just after the `EE_Base_Class::_delete` method call.
1693
+		 * Note:
1694
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1695
+		 * should be aware that `_delete` may not always result in a permanent delete.
1696
+		 * For example `EE_Soft_Base_Class::_delete`
1697
+		 * soft deletes (trash) the object and does not permanently delete it.
1698
+		 *
1699
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1700
+		 * @param boolean       $result
1701
+		 */
1702
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1703
+		return $result;
1704
+	}
1705
+
1706
+
1707
+	/**
1708
+	 * Calls the specific delete method for the instantiated class.
1709
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1710
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1711
+	 * `EE_Base_Class::delete`
1712
+	 *
1713
+	 * @return bool|int
1714
+	 * @throws ReflectionException
1715
+	 * @throws InvalidArgumentException
1716
+	 * @throws InvalidInterfaceException
1717
+	 * @throws InvalidDataTypeException
1718
+	 * @throws EE_Error
1719
+	 */
1720
+	protected function _delete()
1721
+	{
1722
+		return $this->delete_permanently();
1723
+	}
1724
+
1725
+
1726
+	/**
1727
+	 * Deletes this model object permanently from db
1728
+	 * (but keep in mind related models may block the delete and return an error)
1729
+	 *
1730
+	 * @return bool | int
1731
+	 * @throws ReflectionException
1732
+	 * @throws InvalidArgumentException
1733
+	 * @throws InvalidInterfaceException
1734
+	 * @throws InvalidDataTypeException
1735
+	 * @throws EE_Error
1736
+	 */
1737
+	public function delete_permanently()
1738
+	{
1739
+		/**
1740
+		 * Called just before HARD deleting a model object
1741
+		 *
1742
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1743
+		 */
1744
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1745
+		$model = $this->get_model();
1746
+		$result = $model->delete_permanently_by_ID($this->ID());
1747
+		$this->refresh_cache_of_related_objects();
1748
+		/**
1749
+		 * Called just after HARD deleting a model object
1750
+		 *
1751
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1752
+		 * @param boolean       $result
1753
+		 */
1754
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1755
+		return $result;
1756
+	}
1757
+
1758
+
1759
+	/**
1760
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1761
+	 * related model objects
1762
+	 *
1763
+	 * @throws ReflectionException
1764
+	 * @throws InvalidArgumentException
1765
+	 * @throws InvalidInterfaceException
1766
+	 * @throws InvalidDataTypeException
1767
+	 * @throws EE_Error
1768
+	 */
1769
+	public function refresh_cache_of_related_objects()
1770
+	{
1771
+		$model = $this->get_model();
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 ];
1775
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776
+					// this relation only stores a single model object, not an array
1777
+					// but let's make it consistent
1778
+					$related_objects = array($related_objects);
1779
+				}
1780
+				foreach ($related_objects as $related_object) {
1781
+					// only refresh their cache if they're in memory
1782
+					if ($related_object instanceof EE_Base_Class) {
1783
+						$related_object->clear_cache(
1784
+							$model->get_this_model_name(),
1785
+							$this
1786
+						);
1787
+					}
1788
+				}
1789
+			}
1790
+		}
1791
+	}
1792
+
1793
+
1794
+	/**
1795
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1796
+	 * object just before saving.
1797
+	 *
1798
+	 * @access public
1799
+	 * @param array $set_cols_n_values  keys are field names, values are their new values,
1800
+	 *                                  if provided during the save() method
1801
+	 *                                  (often client code will change the fields' values before calling save)
1802
+	 * @return false|int|string         1 on a successful update;
1803
+	 *                                  the ID of the new entry on insert;
1804
+	 *                                  0 on failure, or if the model object isn't allowed to persist
1805
+	 *                                  (as determined by EE_Base_Class::allow_persist())
1806
+	 * @throws InvalidInterfaceException
1807
+	 * @throws InvalidDataTypeException
1808
+	 * @throws EE_Error
1809
+	 * @throws InvalidArgumentException
1810
+	 * @throws ReflectionException
1811
+	 * @throws ReflectionException
1812
+	 * @throws ReflectionException
1813
+	 */
1814
+	public function save($set_cols_n_values = array())
1815
+	{
1816
+		$model = $this->get_model();
1817
+		/**
1818
+		 * Filters the fields we're about to save on the model object
1819
+		 *
1820
+		 * @param array         $set_cols_n_values
1821
+		 * @param EE_Base_Class $model_object
1822
+		 */
1823
+		$set_cols_n_values = (array) apply_filters(
1824
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1825
+			$set_cols_n_values,
1826
+			$this
1827
+		);
1828
+		// set attributes as provided in $set_cols_n_values
1829
+		foreach ($set_cols_n_values as $column => $value) {
1830
+			$this->set($column, $value);
1831
+		}
1832
+		// no changes ? then don't do anything
1833
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834
+			return 0;
1835
+		}
1836
+		/**
1837
+		 * Saving a model object.
1838
+		 * Before we perform a save, this action is fired.
1839
+		 *
1840
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1841
+		 */
1842
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
+		if (! $this->allow_persist()) {
1844
+			return 0;
1845
+		}
1846
+		// now get current attribute values
1847
+		$save_cols_n_values = $this->_fields;
1848
+		// if the object already has an ID, update it. Otherwise, insert it
1849
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1850
+		// They have been
1851
+		$old_assumption_concerning_value_preparation = $model
1852
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1853
+		$model->assume_values_already_prepared_by_model_object(true);
1854
+		// does this model have an autoincrement PK?
1855
+		if ($model->has_primary_key_field()) {
1856
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1857
+				// ok check if it's set, if so: update; if not, insert
1858
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1859
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860
+				} else {
1861
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1862
+					$results = $model->insert($save_cols_n_values);
1863
+					if ($results) {
1864
+						// if successful, set the primary key
1865
+						// but don't use the normal SET method, because it will check if
1866
+						// an item with the same ID exists in the mapper & db, then
1867
+						// will find it in the db (because we just added it) and THAT object
1868
+						// will get added to the mapper before we can add this one!
1869
+						// but if we just avoid using the SET method, all that headache can be avoided
1870
+						$pk_field_name = $model->primary_key_name();
1871
+						$this->_fields[ $pk_field_name ] = $results;
1872
+						$this->_clear_cached_property($pk_field_name);
1873
+						$model->add_to_entity_map($this);
1874
+						$this->_update_cached_related_model_objs_fks();
1875
+					}
1876
+				}
1877
+			} else {// PK is NOT auto-increment
1878
+				// so check if one like it already exists in the db
1879
+				if ($model->exists_by_ID($this->ID())) {
1880
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1881
+						throw new EE_Error(
1882
+							sprintf(
1883
+								esc_html__(
1884
+									'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',
1885
+									'event_espresso'
1886
+								),
1887
+								get_class($this),
1888
+								get_class($model) . '::instance()->add_to_entity_map()',
1889
+								get_class($model) . '::instance()->get_one_by_ID()',
1890
+								'<br />'
1891
+							)
1892
+						);
1893
+					}
1894
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1895
+				} else {
1896
+					$results = $model->insert($save_cols_n_values);
1897
+					$this->_update_cached_related_model_objs_fks();
1898
+				}
1899
+			}
1900
+		} else {// there is NO primary key
1901
+			$already_in_db = false;
1902
+			foreach ($model->unique_indexes() as $index) {
1903
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1904
+				if ($model->exists(array($uniqueness_where_params))) {
1905
+					$already_in_db = true;
1906
+				}
1907
+			}
1908
+			if ($already_in_db) {
1909
+				$combined_pk_fields_n_values = array_intersect_key(
1910
+					$save_cols_n_values,
1911
+					$model->get_combined_primary_key_fields()
1912
+				);
1913
+				$results = $model->update(
1914
+					$save_cols_n_values,
1915
+					$combined_pk_fields_n_values
1916
+				);
1917
+			} else {
1918
+				$results = $model->insert($save_cols_n_values);
1919
+			}
1920
+		}
1921
+		// restore the old assumption about values being prepared by the model object
1922
+		$model->assume_values_already_prepared_by_model_object(
1923
+			$old_assumption_concerning_value_preparation
1924
+		);
1925
+		/**
1926
+		 * After saving the model object this action is called
1927
+		 *
1928
+		 * @param EE_Base_Class $model_object which was just saved
1929
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1930
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1931
+		 */
1932
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1933
+		$this->_has_changes = false;
1934
+		return $results;
1935
+	}
1936
+
1937
+
1938
+	/**
1939
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1940
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1941
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1942
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1943
+	 * 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
1944
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1945
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1946
+	 *
1947
+	 * @return void
1948
+	 * @throws ReflectionException
1949
+	 * @throws InvalidArgumentException
1950
+	 * @throws InvalidInterfaceException
1951
+	 * @throws InvalidDataTypeException
1952
+	 * @throws EE_Error
1953
+	 */
1954
+	protected function _update_cached_related_model_objs_fks()
1955
+	{
1956
+		$model = $this->get_model();
1957
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1958
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1959
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1960
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1961
+						$model->get_this_model_name()
1962
+					);
1963
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1964
+					if ($related_model_obj_in_cache->ID()) {
1965
+						$related_model_obj_in_cache->save();
1966
+					}
1967
+				}
1968
+			}
1969
+		}
1970
+	}
1971
+
1972
+
1973
+	/**
1974
+	 * Saves this model object and its NEW cached relations to the database.
1975
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1976
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1977
+	 * because otherwise, there's a potential for infinite looping of saving
1978
+	 * Saves the cached related model objects, and ensures the relation between them
1979
+	 * and this object and properly setup
1980
+	 *
1981
+	 * @return int ID of new model object on save; 0 on failure+
1982
+	 * @throws ReflectionException
1983
+	 * @throws InvalidArgumentException
1984
+	 * @throws InvalidInterfaceException
1985
+	 * @throws InvalidDataTypeException
1986
+	 * @throws EE_Error
1987
+	 */
1988
+	public function save_new_cached_related_model_objs()
1989
+	{
1990
+		// make sure this has been saved
1991
+		if (! $this->ID()) {
1992
+			$id = $this->save();
1993
+		} else {
1994
+			$id = $this->ID();
1995
+		}
1996
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1997
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
+			if ($this->_model_relations[ $relationName ]) {
1999
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001
+				/* @var $related_model_obj EE_Base_Class */
2002
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
2003
+					// add a relation to that relation type (which saves the appropriate thing in the process)
2004
+					// but ONLY if it DOES NOT exist in the DB
2005
+					$related_model_obj = $this->_model_relations[ $relationName ];
2006
+					// if( ! $related_model_obj->ID()){
2007
+					$this->_add_relation_to($related_model_obj, $relationName);
2008
+					$related_model_obj->save_new_cached_related_model_objs();
2009
+					// }
2010
+				} else {
2011
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2012
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2013
+						// but ONLY if it DOES NOT exist in the DB
2014
+						// if( ! $related_model_obj->ID()){
2015
+						$this->_add_relation_to($related_model_obj, $relationName);
2016
+						$related_model_obj->save_new_cached_related_model_objs();
2017
+						// }
2018
+					}
2019
+				}
2020
+			}
2021
+		}
2022
+		return $id;
2023
+	}
2024
+
2025
+
2026
+	/**
2027
+	 * for getting a model while instantiated.
2028
+	 *
2029
+	 * @return EEM_Base | EEM_CPT_Base
2030
+	 * @throws ReflectionException
2031
+	 * @throws InvalidArgumentException
2032
+	 * @throws InvalidInterfaceException
2033
+	 * @throws InvalidDataTypeException
2034
+	 * @throws EE_Error
2035
+	 */
2036
+	public function get_model()
2037
+	{
2038
+		if (! $this->_model) {
2039
+			$modelName = self::_get_model_classname(get_class($this));
2040
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041
+		} else {
2042
+			$this->_model->set_timezone($this->_timezone);
2043
+		}
2044
+		return $this->_model;
2045
+	}
2046
+
2047
+
2048
+	/**
2049
+	 * @param $props_n_values
2050
+	 * @param $classname
2051
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2052
+	 * @throws ReflectionException
2053
+	 * @throws InvalidArgumentException
2054
+	 * @throws InvalidInterfaceException
2055
+	 * @throws InvalidDataTypeException
2056
+	 * @throws EE_Error
2057
+	 */
2058
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2059
+	{
2060
+		// TODO: will not work for Term_Relationships because they have no PK!
2061
+		$primary_id_ref = self::_get_primary_key_name($classname);
2062
+		if (
2063
+			array_key_exists($primary_id_ref, $props_n_values)
2064
+			&& ! empty($props_n_values[ $primary_id_ref ])
2065
+		) {
2066
+			$id = $props_n_values[ $primary_id_ref ];
2067
+			return self::_get_model($classname)->get_from_entity_map($id);
2068
+		}
2069
+		return false;
2070
+	}
2071
+
2072
+
2073
+	/**
2074
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2075
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2076
+	 * 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
2077
+	 * we return false.
2078
+	 *
2079
+	 * @param  array  $props_n_values   incoming array of properties and their values
2080
+	 * @param  string $classname        the classname of the child class
2081
+	 * @param null    $timezone
2082
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2083
+	 *                                  date_format and the second value is the time format
2084
+	 * @return mixed (EE_Base_Class|bool)
2085
+	 * @throws InvalidArgumentException
2086
+	 * @throws InvalidInterfaceException
2087
+	 * @throws InvalidDataTypeException
2088
+	 * @throws EE_Error
2089
+	 * @throws ReflectionException
2090
+	 * @throws ReflectionException
2091
+	 * @throws ReflectionException
2092
+	 */
2093
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2094
+	{
2095
+		$existing = null;
2096
+		$model = self::_get_model($classname, $timezone);
2097
+		if ($model->has_primary_key_field()) {
2098
+			$primary_id_ref = self::_get_primary_key_name($classname);
2099
+			if (
2100
+				array_key_exists($primary_id_ref, $props_n_values)
2101
+				&& ! empty($props_n_values[ $primary_id_ref ])
2102
+			) {
2103
+				$existing = $model->get_one_by_ID(
2104
+					$props_n_values[ $primary_id_ref ]
2105
+				);
2106
+			}
2107
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2108
+			// no primary key on this model, but there's still a matching item in the DB
2109
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2110
+				self::_get_model($classname, $timezone)
2111
+					->get_index_primary_key_string($props_n_values)
2112
+			);
2113
+		}
2114
+		if ($existing) {
2115
+			// set date formats if present before setting values
2116
+			if (! empty($date_formats) && is_array($date_formats)) {
2117
+				$existing->set_date_format($date_formats[0]);
2118
+				$existing->set_time_format($date_formats[1]);
2119
+			} else {
2120
+				// set default formats for date and time
2121
+				$existing->set_date_format(get_option('date_format'));
2122
+				$existing->set_time_format(get_option('time_format'));
2123
+			}
2124
+			foreach ($props_n_values as $property => $field_value) {
2125
+				$existing->set($property, $field_value);
2126
+			}
2127
+			return $existing;
2128
+		}
2129
+		return false;
2130
+	}
2131
+
2132
+
2133
+	/**
2134
+	 * Gets the EEM_*_Model for this class
2135
+	 *
2136
+	 * @access public now, as this is more convenient
2137
+	 * @param      $classname
2138
+	 * @param null $timezone
2139
+	 * @throws ReflectionException
2140
+	 * @throws InvalidArgumentException
2141
+	 * @throws InvalidInterfaceException
2142
+	 * @throws InvalidDataTypeException
2143
+	 * @throws EE_Error
2144
+	 * @return EEM_Base
2145
+	 */
2146
+	protected static function _get_model($classname, $timezone = null)
2147
+	{
2148
+		// find model for this class
2149
+		if (! $classname) {
2150
+			throw new EE_Error(
2151
+				sprintf(
2152
+					esc_html__(
2153
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2154
+						'event_espresso'
2155
+					),
2156
+					$classname
2157
+				)
2158
+			);
2159
+		}
2160
+		$modelName = self::_get_model_classname($classname);
2161
+		return self::_get_model_instance_with_name($modelName, $timezone);
2162
+	}
2163
+
2164
+
2165
+	/**
2166
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2167
+	 *
2168
+	 * @param string $model_classname
2169
+	 * @param null   $timezone
2170
+	 * @return EEM_Base
2171
+	 * @throws ReflectionException
2172
+	 * @throws InvalidArgumentException
2173
+	 * @throws InvalidInterfaceException
2174
+	 * @throws InvalidDataTypeException
2175
+	 * @throws EE_Error
2176
+	 */
2177
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2178
+	{
2179
+		$model_classname = str_replace('EEM_', '', $model_classname);
2180
+		$model = EE_Registry::instance()->load_model($model_classname);
2181
+		$model->set_timezone($timezone);
2182
+		return $model;
2183
+	}
2184
+
2185
+
2186
+	/**
2187
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2188
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2189
+	 *
2190
+	 * @param null $model_name
2191
+	 * @return string like EEM_Attendee
2192
+	 */
2193
+	private static function _get_model_classname($model_name = null)
2194
+	{
2195
+		if (strpos($model_name, 'EE_') === 0) {
2196
+			$model_classname = str_replace('EE_', 'EEM_', $model_name);
2197
+		} else {
2198
+			$model_classname = 'EEM_' . $model_name;
2199
+		}
2200
+		return $model_classname;
2201
+	}
2202
+
2203
+
2204
+	/**
2205
+	 * returns the name of the primary key attribute
2206
+	 *
2207
+	 * @param null $classname
2208
+	 * @throws ReflectionException
2209
+	 * @throws InvalidArgumentException
2210
+	 * @throws InvalidInterfaceException
2211
+	 * @throws InvalidDataTypeException
2212
+	 * @throws EE_Error
2213
+	 * @return string
2214
+	 */
2215
+	protected static function _get_primary_key_name($classname = null)
2216
+	{
2217
+		if (! $classname) {
2218
+			throw new EE_Error(
2219
+				sprintf(
2220
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2221
+					$classname
2222
+				)
2223
+			);
2224
+		}
2225
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2226
+	}
2227
+
2228
+
2229
+	/**
2230
+	 * Gets the value of the primary key.
2231
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2232
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2233
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2234
+	 *
2235
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2236
+	 * @throws ReflectionException
2237
+	 * @throws InvalidArgumentException
2238
+	 * @throws InvalidInterfaceException
2239
+	 * @throws InvalidDataTypeException
2240
+	 * @throws EE_Error
2241
+	 */
2242
+	public function ID()
2243
+	{
2244
+		$model = $this->get_model();
2245
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2246
+		if ($model->has_primary_key_field()) {
2247
+			return $this->_fields[ $model->primary_key_name() ];
2248
+		}
2249
+		return $model->get_index_primary_key_string($this->_fields);
2250
+	}
2251
+
2252
+
2253
+	/**
2254
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2255
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2256
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2257
+	 *
2258
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2259
+	 * @param string $relationName                     eg 'Events','Question',etc.
2260
+	 *                                                 an attendee to a group, you also want to specify which role they
2261
+	 *                                                 will have in that group. So you would use this parameter to
2262
+	 *                                                 specify array('role-column-name'=>'role-id')
2263
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2264
+	 *                                                 allow you to further constrict the relation to being added.
2265
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2266
+	 *                                                 column on the JOIN table and currently only the HABTM models
2267
+	 *                                                 accept these additional conditions.  Also remember that if an
2268
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2269
+	 *                                                 NEW row is created in the join table.
2270
+	 * @param null   $cache_id
2271
+	 * @throws ReflectionException
2272
+	 * @throws InvalidArgumentException
2273
+	 * @throws InvalidInterfaceException
2274
+	 * @throws InvalidDataTypeException
2275
+	 * @throws EE_Error
2276
+	 * @return EE_Base_Class the object the relation was added to
2277
+	 */
2278
+	public function _add_relation_to(
2279
+		$otherObjectModelObjectOrID,
2280
+		$relationName,
2281
+		$extra_join_model_fields_n_values = array(),
2282
+		$cache_id = null
2283
+	) {
2284
+		$model = $this->get_model();
2285
+		// if this thing exists in the DB, save the relation to the DB
2286
+		if ($this->ID()) {
2287
+			$otherObject = $model->add_relationship_to(
2288
+				$this,
2289
+				$otherObjectModelObjectOrID,
2290
+				$relationName,
2291
+				$extra_join_model_fields_n_values
2292
+			);
2293
+			// clear cache so future get_many_related and get_first_related() return new results.
2294
+			$this->clear_cache($relationName, $otherObject, true);
2295
+			if ($otherObject instanceof EE_Base_Class) {
2296
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2297
+			}
2298
+		} else {
2299
+			// this thing doesn't exist in the DB,  so just cache it
2300
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2301
+				throw new EE_Error(
2302
+					sprintf(
2303
+						esc_html__(
2304
+							'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',
2305
+							'event_espresso'
2306
+						),
2307
+						$otherObjectModelObjectOrID,
2308
+						get_class($this)
2309
+					)
2310
+				);
2311
+			}
2312
+			$otherObject = $otherObjectModelObjectOrID;
2313
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2314
+		}
2315
+		if ($otherObject instanceof EE_Base_Class) {
2316
+			// fix the reciprocal relation too
2317
+			if ($otherObject->ID()) {
2318
+				// its saved so assumed relations exist in the DB, so we can just
2319
+				// clear the cache so future queries use the updated info in the DB
2320
+				$otherObject->clear_cache(
2321
+					$model->get_this_model_name(),
2322
+					null,
2323
+					true
2324
+				);
2325
+			} else {
2326
+				// it's not saved, so it caches relations like this
2327
+				$otherObject->cache($model->get_this_model_name(), $this);
2328
+			}
2329
+		}
2330
+		return $otherObject;
2331
+	}
2332
+
2333
+
2334
+	/**
2335
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2336
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2337
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2338
+	 * from the cache
2339
+	 *
2340
+	 * @param mixed  $otherObjectModelObjectOrID
2341
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2342
+	 *                to the DB yet
2343
+	 * @param string $relationName
2344
+	 * @param array  $where_query
2345
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2346
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2347
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2348
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2349
+	 *                deleted.
2350
+	 * @return EE_Base_Class the relation was removed from
2351
+	 * @throws ReflectionException
2352
+	 * @throws InvalidArgumentException
2353
+	 * @throws InvalidInterfaceException
2354
+	 * @throws InvalidDataTypeException
2355
+	 * @throws EE_Error
2356
+	 */
2357
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2358
+	{
2359
+		if ($this->ID()) {
2360
+			// if this exists in the DB, save the relation change to the DB too
2361
+			$otherObject = $this->get_model()->remove_relationship_to(
2362
+				$this,
2363
+				$otherObjectModelObjectOrID,
2364
+				$relationName,
2365
+				$where_query
2366
+			);
2367
+			$this->clear_cache(
2368
+				$relationName,
2369
+				$otherObject
2370
+			);
2371
+		} else {
2372
+			// this doesn't exist in the DB, just remove it from the cache
2373
+			$otherObject = $this->clear_cache(
2374
+				$relationName,
2375
+				$otherObjectModelObjectOrID
2376
+			);
2377
+		}
2378
+		if ($otherObject instanceof EE_Base_Class) {
2379
+			$otherObject->clear_cache(
2380
+				$this->get_model()->get_this_model_name(),
2381
+				$this
2382
+			);
2383
+		}
2384
+		return $otherObject;
2385
+	}
2386
+
2387
+
2388
+	/**
2389
+	 * Removes ALL the related things for the $relationName.
2390
+	 *
2391
+	 * @param string $relationName
2392
+	 * @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
2393
+	 * @return EE_Base_Class
2394
+	 * @throws ReflectionException
2395
+	 * @throws InvalidArgumentException
2396
+	 * @throws InvalidInterfaceException
2397
+	 * @throws InvalidDataTypeException
2398
+	 * @throws EE_Error
2399
+	 */
2400
+	public function _remove_relations($relationName, $where_query_params = array())
2401
+	{
2402
+		if ($this->ID()) {
2403
+			// if this exists in the DB, save the relation change to the DB too
2404
+			$otherObjects = $this->get_model()->remove_relations(
2405
+				$this,
2406
+				$relationName,
2407
+				$where_query_params
2408
+			);
2409
+			$this->clear_cache(
2410
+				$relationName,
2411
+				null,
2412
+				true
2413
+			);
2414
+		} else {
2415
+			// this doesn't exist in the DB, just remove it from the cache
2416
+			$otherObjects = $this->clear_cache(
2417
+				$relationName,
2418
+				null,
2419
+				true
2420
+			);
2421
+		}
2422
+		if (is_array($otherObjects)) {
2423
+			foreach ($otherObjects as $otherObject) {
2424
+				$otherObject->clear_cache(
2425
+					$this->get_model()->get_this_model_name(),
2426
+					$this
2427
+				);
2428
+			}
2429
+		}
2430
+		return $otherObjects;
2431
+	}
2432
+
2433
+
2434
+	/**
2435
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2436
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2437
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2438
+	 * because we want to get even deleted items etc.
2439
+	 *
2440
+	 * @param string $relationName key in the model's _model_relations array
2441
+	 * @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
2442
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2443
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2444
+	 *                             results if you want IDs
2445
+	 * @throws ReflectionException
2446
+	 * @throws InvalidArgumentException
2447
+	 * @throws InvalidInterfaceException
2448
+	 * @throws InvalidDataTypeException
2449
+	 * @throws EE_Error
2450
+	 */
2451
+	public function get_many_related($relationName, $query_params = array())
2452
+	{
2453
+		if ($this->ID()) {
2454
+			// this exists in the DB, so get the related things from either the cache or the DB
2455
+			// if there are query parameters, forget about caching the related model objects.
2456
+			if ($query_params) {
2457
+				$related_model_objects = $this->get_model()->get_all_related(
2458
+					$this,
2459
+					$relationName,
2460
+					$query_params
2461
+				);
2462
+			} else {
2463
+				// did we already cache the result of this query?
2464
+				$cached_results = $this->get_all_from_cache($relationName);
2465
+				if (! $cached_results) {
2466
+					$related_model_objects = $this->get_model()->get_all_related(
2467
+						$this,
2468
+						$relationName,
2469
+						$query_params
2470
+					);
2471
+					// if no query parameters were passed, then we got all the related model objects
2472
+					// for that relation. We can cache them then.
2473
+					foreach ($related_model_objects as $related_model_object) {
2474
+						$this->cache($relationName, $related_model_object);
2475
+					}
2476
+				} else {
2477
+					$related_model_objects = $cached_results;
2478
+				}
2479
+			}
2480
+		} else {
2481
+			// this doesn't exist in the DB, so just get the related things from the cache
2482
+			$related_model_objects = $this->get_all_from_cache($relationName);
2483
+		}
2484
+		return $related_model_objects;
2485
+	}
2486
+
2487
+
2488
+	/**
2489
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2490
+	 * unless otherwise specified in the $query_params
2491
+	 *
2492
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2493
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2494
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2495
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2496
+	 *                               that by the setting $distinct to TRUE;
2497
+	 * @return int
2498
+	 * @throws ReflectionException
2499
+	 * @throws InvalidArgumentException
2500
+	 * @throws InvalidInterfaceException
2501
+	 * @throws InvalidDataTypeException
2502
+	 * @throws EE_Error
2503
+	 */
2504
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2505
+	{
2506
+		return $this->get_model()->count_related(
2507
+			$this,
2508
+			$relation_name,
2509
+			$query_params,
2510
+			$field_to_count,
2511
+			$distinct
2512
+		);
2513
+	}
2514
+
2515
+
2516
+	/**
2517
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2518
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2519
+	 *
2520
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2521
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2522
+	 * @param string $field_to_sum  name of field to count by.
2523
+	 *                              By default, uses primary key
2524
+	 *                              (which doesn't make much sense, so you should probably change it)
2525
+	 * @return int
2526
+	 * @throws ReflectionException
2527
+	 * @throws InvalidArgumentException
2528
+	 * @throws InvalidInterfaceException
2529
+	 * @throws InvalidDataTypeException
2530
+	 * @throws EE_Error
2531
+	 */
2532
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2533
+	{
2534
+		return $this->get_model()->sum_related(
2535
+			$this,
2536
+			$relation_name,
2537
+			$query_params,
2538
+			$field_to_sum
2539
+		);
2540
+	}
2541
+
2542
+
2543
+	/**
2544
+	 * Gets the first (ie, one) related model object of the specified type.
2545
+	 *
2546
+	 * @param string $relationName key in the model's _model_relations array
2547
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2548
+	 * @return EE_Base_Class (not an array, a single object)
2549
+	 * @throws ReflectionException
2550
+	 * @throws InvalidArgumentException
2551
+	 * @throws InvalidInterfaceException
2552
+	 * @throws InvalidDataTypeException
2553
+	 * @throws EE_Error
2554
+	 */
2555
+	public function get_first_related($relationName, $query_params = array())
2556
+	{
2557
+		$model = $this->get_model();
2558
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2559
+			// if they've provided some query parameters, don't bother trying to cache the result
2560
+			// also make sure we're not caching the result of get_first_related
2561
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2562
+			if (
2563
+				$query_params
2564
+				|| ! $model->related_settings_for($relationName)
2565
+					 instanceof
2566
+					 EE_Belongs_To_Relation
2567
+			) {
2568
+				$related_model_object = $model->get_first_related(
2569
+					$this,
2570
+					$relationName,
2571
+					$query_params
2572
+				);
2573
+			} else {
2574
+				// first, check if we've already cached the result of this query
2575
+				$cached_result = $this->get_one_from_cache($relationName);
2576
+				if (! $cached_result) {
2577
+					$related_model_object = $model->get_first_related(
2578
+						$this,
2579
+						$relationName,
2580
+						$query_params
2581
+					);
2582
+					$this->cache($relationName, $related_model_object);
2583
+				} else {
2584
+					$related_model_object = $cached_result;
2585
+				}
2586
+			}
2587
+		} else {
2588
+			$related_model_object = null;
2589
+			// this doesn't exist in the Db,
2590
+			// but maybe the relation is of type belongs to, and so the related thing might
2591
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2592
+				$related_model_object = $model->get_first_related(
2593
+					$this,
2594
+					$relationName,
2595
+					$query_params
2596
+				);
2597
+			}
2598
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2599
+			// just get what's cached on this object
2600
+			if (! $related_model_object) {
2601
+				$related_model_object = $this->get_one_from_cache($relationName);
2602
+			}
2603
+		}
2604
+		return $related_model_object;
2605
+	}
2606
+
2607
+
2608
+	/**
2609
+	 * Does a delete on all related objects of type $relationName and removes
2610
+	 * the current model object's relation to them. If they can't be deleted (because
2611
+	 * of blocking related model objects) does nothing. If the related model objects are
2612
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2613
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2614
+	 *
2615
+	 * @param string $relationName
2616
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2617
+	 * @return int how many deleted
2618
+	 * @throws ReflectionException
2619
+	 * @throws InvalidArgumentException
2620
+	 * @throws InvalidInterfaceException
2621
+	 * @throws InvalidDataTypeException
2622
+	 * @throws EE_Error
2623
+	 */
2624
+	public function delete_related($relationName, $query_params = array())
2625
+	{
2626
+		if ($this->ID()) {
2627
+			$count = $this->get_model()->delete_related(
2628
+				$this,
2629
+				$relationName,
2630
+				$query_params
2631
+			);
2632
+		} else {
2633
+			$count = count($this->get_all_from_cache($relationName));
2634
+			$this->clear_cache($relationName, null, true);
2635
+		}
2636
+		return $count;
2637
+	}
2638
+
2639
+
2640
+	/**
2641
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2642
+	 * the current model object's relation to them. If they can't be deleted (because
2643
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2644
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2645
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2646
+	 *
2647
+	 * @param string $relationName
2648
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2649
+	 * @return int how many deleted (including those soft deleted)
2650
+	 * @throws ReflectionException
2651
+	 * @throws InvalidArgumentException
2652
+	 * @throws InvalidInterfaceException
2653
+	 * @throws InvalidDataTypeException
2654
+	 * @throws EE_Error
2655
+	 */
2656
+	public function delete_related_permanently($relationName, $query_params = array())
2657
+	{
2658
+		if ($this->ID()) {
2659
+			$count = $this->get_model()->delete_related_permanently(
2660
+				$this,
2661
+				$relationName,
2662
+				$query_params
2663
+			);
2664
+		} else {
2665
+			$count = count($this->get_all_from_cache($relationName));
2666
+		}
2667
+		$this->clear_cache($relationName, null, true);
2668
+		return $count;
2669
+	}
2670
+
2671
+
2672
+	/**
2673
+	 * is_set
2674
+	 * Just a simple utility function children can use for checking if property exists
2675
+	 *
2676
+	 * @access  public
2677
+	 * @param  string $field_name property to check
2678
+	 * @return bool                              TRUE if existing,FALSE if not.
2679
+	 */
2680
+	public function is_set($field_name)
2681
+	{
2682
+		return isset($this->_fields[ $field_name ]);
2683
+	}
2684
+
2685
+
2686
+	/**
2687
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2688
+	 * EE_Error exception if they don't
2689
+	 *
2690
+	 * @param  mixed (string|array) $properties properties to check
2691
+	 * @throws EE_Error
2692
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2693
+	 */
2694
+	protected function _property_exists($properties)
2695
+	{
2696
+		foreach ((array) $properties as $property_name) {
2697
+			// first make sure this property exists
2698
+			if (! $this->_fields[ $property_name ]) {
2699
+				throw new EE_Error(
2700
+					sprintf(
2701
+						esc_html__(
2702
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2703
+							'event_espresso'
2704
+						),
2705
+						$property_name
2706
+					)
2707
+				);
2708
+			}
2709
+		}
2710
+		return true;
2711
+	}
2712
+
2713
+
2714
+	/**
2715
+	 * This simply returns an array of model fields for this object
2716
+	 *
2717
+	 * @return array
2718
+	 * @throws ReflectionException
2719
+	 * @throws InvalidArgumentException
2720
+	 * @throws InvalidInterfaceException
2721
+	 * @throws InvalidDataTypeException
2722
+	 * @throws EE_Error
2723
+	 */
2724
+	public function model_field_array()
2725
+	{
2726
+		$fields = $this->get_model()->field_settings(false);
2727
+		$properties = array();
2728
+		// remove prepended underscore
2729
+		foreach ($fields as $field_name => $settings) {
2730
+			$properties[ $field_name ] = $this->get($field_name);
2731
+		}
2732
+		return $properties;
2733
+	}
2734
+
2735
+
2736
+	/**
2737
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2738
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2739
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2740
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2741
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2742
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2743
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2744
+	 * and accepts 2 arguments: the object on which the function was called,
2745
+	 * and an array of the original arguments passed to the function.
2746
+	 * Whatever their callback function returns will be returned by this function.
2747
+	 * Example: in functions.php (or in a plugin):
2748
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2749
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2750
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2751
+	 *          return $previousReturnValue.$returnString;
2752
+	 *      }
2753
+	 * require('EE_Answer.class.php');
2754
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2755
+	 * echo $answer->my_callback('monkeys',100);
2756
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2757
+	 *
2758
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2759
+	 * @param array  $args       array of original arguments passed to the function
2760
+	 * @throws EE_Error
2761
+	 * @return mixed whatever the plugin which calls add_filter decides
2762
+	 */
2763
+	public function __call($methodName, $args)
2764
+	{
2765
+		$className = get_class($this);
2766
+		$tagName = "FHEE__{$className}__{$methodName}";
2767
+		if (! has_filter($tagName)) {
2768
+			throw new EE_Error(
2769
+				sprintf(
2770
+					esc_html__(
2771
+						"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;}",
2772
+						'event_espresso'
2773
+					),
2774
+					$methodName,
2775
+					$className,
2776
+					$tagName
2777
+				)
2778
+			);
2779
+		}
2780
+		return apply_filters($tagName, null, $this, $args);
2781
+	}
2782
+
2783
+
2784
+	/**
2785
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2786
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2787
+	 *
2788
+	 * @param string $meta_key
2789
+	 * @param mixed  $meta_value
2790
+	 * @param mixed  $previous_value
2791
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2792
+	 *                  NOTE: if the values haven't changed, returns 0
2793
+	 * @throws InvalidArgumentException
2794
+	 * @throws InvalidInterfaceException
2795
+	 * @throws InvalidDataTypeException
2796
+	 * @throws EE_Error
2797
+	 * @throws ReflectionException
2798
+	 */
2799
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2800
+	{
2801
+		$query_params = array(
2802
+			array(
2803
+				'EXM_key'  => $meta_key,
2804
+				'OBJ_ID'   => $this->ID(),
2805
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2806
+			),
2807
+		);
2808
+		if ($previous_value !== null) {
2809
+			$query_params[0]['EXM_value'] = $meta_value;
2810
+		}
2811
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2812
+		if (! $existing_rows_like_that) {
2813
+			return $this->add_extra_meta($meta_key, $meta_value);
2814
+		}
2815
+		foreach ($existing_rows_like_that as $existing_row) {
2816
+			$existing_row->save(array('EXM_value' => $meta_value));
2817
+		}
2818
+		return count($existing_rows_like_that);
2819
+	}
2820
+
2821
+
2822
+	/**
2823
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2824
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2825
+	 * extra meta row was entered, false if not
2826
+	 *
2827
+	 * @param string  $meta_key
2828
+	 * @param mixed   $meta_value
2829
+	 * @param boolean $unique
2830
+	 * @return boolean
2831
+	 * @throws InvalidArgumentException
2832
+	 * @throws InvalidInterfaceException
2833
+	 * @throws InvalidDataTypeException
2834
+	 * @throws EE_Error
2835
+	 * @throws ReflectionException
2836
+	 * @throws ReflectionException
2837
+	 */
2838
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2839
+	{
2840
+		if ($unique) {
2841
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2842
+				array(
2843
+					array(
2844
+						'EXM_key'  => $meta_key,
2845
+						'OBJ_ID'   => $this->ID(),
2846
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2847
+					),
2848
+				)
2849
+			);
2850
+			if ($existing_extra_meta) {
2851
+				return false;
2852
+			}
2853
+		}
2854
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2855
+			array(
2856
+				'EXM_key'   => $meta_key,
2857
+				'EXM_value' => $meta_value,
2858
+				'OBJ_ID'    => $this->ID(),
2859
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2860
+			)
2861
+		);
2862
+		$new_extra_meta->save();
2863
+		return true;
2864
+	}
2865
+
2866
+
2867
+	/**
2868
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2869
+	 * is specified, only deletes extra meta records with that value.
2870
+	 *
2871
+	 * @param string $meta_key
2872
+	 * @param mixed  $meta_value
2873
+	 * @return int number of extra meta rows deleted
2874
+	 * @throws InvalidArgumentException
2875
+	 * @throws InvalidInterfaceException
2876
+	 * @throws InvalidDataTypeException
2877
+	 * @throws EE_Error
2878
+	 * @throws ReflectionException
2879
+	 */
2880
+	public function delete_extra_meta($meta_key, $meta_value = null)
2881
+	{
2882
+		$query_params = array(
2883
+			array(
2884
+				'EXM_key'  => $meta_key,
2885
+				'OBJ_ID'   => $this->ID(),
2886
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2887
+			),
2888
+		);
2889
+		if ($meta_value !== null) {
2890
+			$query_params[0]['EXM_value'] = $meta_value;
2891
+		}
2892
+		return EEM_Extra_Meta::instance()->delete($query_params);
2893
+	}
2894
+
2895
+
2896
+	/**
2897
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2898
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2899
+	 * You can specify $default is case you haven't found the extra meta
2900
+	 *
2901
+	 * @param string  $meta_key
2902
+	 * @param boolean $single
2903
+	 * @param mixed   $default if we don't find anything, what should we return?
2904
+	 * @return mixed single value if $single; array if ! $single
2905
+	 * @throws ReflectionException
2906
+	 * @throws InvalidArgumentException
2907
+	 * @throws InvalidInterfaceException
2908
+	 * @throws InvalidDataTypeException
2909
+	 * @throws EE_Error
2910
+	 */
2911
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2912
+	{
2913
+		if ($single) {
2914
+			$result = $this->get_first_related(
2915
+				'Extra_Meta',
2916
+				array(array('EXM_key' => $meta_key))
2917
+			);
2918
+			if ($result instanceof EE_Extra_Meta) {
2919
+				return $result->value();
2920
+			}
2921
+		} else {
2922
+			$results = $this->get_many_related(
2923
+				'Extra_Meta',
2924
+				array(array('EXM_key' => $meta_key))
2925
+			);
2926
+			if ($results) {
2927
+				$values = array();
2928
+				foreach ($results as $result) {
2929
+					if ($result instanceof EE_Extra_Meta) {
2930
+						$values[ $result->ID() ] = $result->value();
2931
+					}
2932
+				}
2933
+				return $values;
2934
+			}
2935
+		}
2936
+		// if nothing discovered yet return default.
2937
+		return apply_filters(
2938
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2939
+			$default,
2940
+			$meta_key,
2941
+			$single,
2942
+			$this
2943
+		);
2944
+	}
2945
+
2946
+
2947
+	/**
2948
+	 * Returns a simple array of all the extra meta associated with this model object.
2949
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2950
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2951
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2952
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2953
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2954
+	 * finally the extra meta's value as each sub-value. (eg
2955
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2956
+	 *
2957
+	 * @param boolean $one_of_each_key
2958
+	 * @return array
2959
+	 * @throws ReflectionException
2960
+	 * @throws InvalidArgumentException
2961
+	 * @throws InvalidInterfaceException
2962
+	 * @throws InvalidDataTypeException
2963
+	 * @throws EE_Error
2964
+	 */
2965
+	public function all_extra_meta_array($one_of_each_key = true)
2966
+	{
2967
+		$return_array = array();
2968
+		if ($one_of_each_key) {
2969
+			$extra_meta_objs = $this->get_many_related(
2970
+				'Extra_Meta',
2971
+				array('group_by' => 'EXM_key')
2972
+			);
2973
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2974
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2975
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2976
+				}
2977
+			}
2978
+		} else {
2979
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2980
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2981
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2982
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2983
+						$return_array[ $extra_meta_obj->key() ] = array();
2984
+					}
2985
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2986
+				}
2987
+			}
2988
+		}
2989
+		return $return_array;
2990
+	}
2991
+
2992
+
2993
+	/**
2994
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2995
+	 *
2996
+	 * @return string
2997
+	 * @throws ReflectionException
2998
+	 * @throws InvalidArgumentException
2999
+	 * @throws InvalidInterfaceException
3000
+	 * @throws InvalidDataTypeException
3001
+	 * @throws EE_Error
3002
+	 */
3003
+	public function name()
3004
+	{
3005
+		// find a field that's not a text field
3006
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3007
+		if ($field_we_can_use) {
3008
+			return $this->get($field_we_can_use->get_name());
3009
+		}
3010
+		$first_few_properties = $this->model_field_array();
3011
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3012
+		$name_parts = array();
3013
+		foreach ($first_few_properties as $name => $value) {
3014
+			$name_parts[] = "$name:$value";
3015
+		}
3016
+		return implode(',', $name_parts);
3017
+	}
3018
+
3019
+
3020
+	/**
3021
+	 * in_entity_map
3022
+	 * Checks if this model object has been proven to already be in the entity map
3023
+	 *
3024
+	 * @return boolean
3025
+	 * @throws ReflectionException
3026
+	 * @throws InvalidArgumentException
3027
+	 * @throws InvalidInterfaceException
3028
+	 * @throws InvalidDataTypeException
3029
+	 * @throws EE_Error
3030
+	 */
3031
+	public function in_entity_map()
3032
+	{
3033
+		// well, if we looked, did we find it in the entity map?
3034
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3035
+	}
3036
+
3037
+
3038
+	/**
3039
+	 * refresh_from_db
3040
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3041
+	 *
3042
+	 * @throws ReflectionException
3043
+	 * @throws InvalidArgumentException
3044
+	 * @throws InvalidInterfaceException
3045
+	 * @throws InvalidDataTypeException
3046
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3047
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3048
+	 */
3049
+	public function refresh_from_db()
3050
+	{
3051
+		if ($this->ID() && $this->in_entity_map()) {
3052
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3053
+		} else {
3054
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3055
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3056
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3057
+			// absolutely nothing in it for this ID
3058
+			if (WP_DEBUG) {
3059
+				throw new EE_Error(
3060
+					sprintf(
3061
+						esc_html__(
3062
+							'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.',
3063
+							'event_espresso'
3064
+						),
3065
+						$this->ID(),
3066
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3067
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3068
+					)
3069
+				);
3070
+			}
3071
+		}
3072
+	}
3073
+
3074
+
3075
+	/**
3076
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3077
+	 *
3078
+	 * @since 4.9.80.p
3079
+	 * @param EE_Model_Field_Base[] $fields
3080
+	 * @param string $new_value_sql
3081
+	 *      example: 'column_name=123',
3082
+	 *      or 'column_name=column_name+1',
3083
+	 *      or 'column_name= CASE
3084
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3085
+	 *          THEN `column_name` + 5
3086
+	 *          ELSE `column_name`
3087
+	 *      END'
3088
+	 *      Also updates $field on this model object with the latest value from the database.
3089
+	 * @return bool
3090
+	 * @throws EE_Error
3091
+	 * @throws InvalidArgumentException
3092
+	 * @throws InvalidDataTypeException
3093
+	 * @throws InvalidInterfaceException
3094
+	 * @throws ReflectionException
3095
+	 */
3096
+	protected function updateFieldsInDB($fields, $new_value_sql)
3097
+	{
3098
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3099
+		// if it wasn't even there to start off.
3100
+		if (! $this->ID()) {
3101
+			$this->save();
3102
+		}
3103
+		global $wpdb;
3104
+		if (empty($fields)) {
3105
+			throw new InvalidArgumentException(
3106
+				esc_html__(
3107
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3108
+					'event_espresso'
3109
+				)
3110
+			);
3111
+		}
3112
+		$first_field = reset($fields);
3113
+		$table_alias = $first_field->get_table_alias();
3114
+		foreach ($fields as $field) {
3115
+			if ($table_alias !== $field->get_table_alias()) {
3116
+				throw new InvalidArgumentException(
3117
+					sprintf(
3118
+						esc_html__(
3119
+							// @codingStandardsIgnoreStart
3120
+							'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.',
3121
+							// @codingStandardsIgnoreEnd
3122
+							'event_espresso'
3123
+						),
3124
+						$table_alias,
3125
+						$field->get_table_alias()
3126
+					)
3127
+				);
3128
+			}
3129
+		}
3130
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3131
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3132
+		$table_pk_value = $this->ID();
3133
+		$table_name = $table_obj->get_table_name();
3134
+		if ($table_obj instanceof EE_Secondary_Table) {
3135
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3136
+		} else {
3137
+			$table_pk_field_name = $table_obj->get_pk_column();
3138
+		}
3139
+
3140
+		$query =
3141
+			"UPDATE `{$table_name}`
3142 3142
             SET "
3143
-            . $new_value_sql
3144
-            . $wpdb->prepare(
3145
-                "
3143
+			. $new_value_sql
3144
+			. $wpdb->prepare(
3145
+				"
3146 3146
             WHERE `{$table_pk_field_name}` = %d;",
3147
-                $table_pk_value
3148
-            );
3149
-        $result = $wpdb->query($query);
3150
-        foreach ($fields as $field) {
3151
-            // If it was successful, we'd like to know the new value.
3152
-            // If it failed, we'd also like to know the new value.
3153
-            $new_value = $this->get_model()->get_var(
3154
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3155
-                    $this->get_model()->get_index_primary_key_string(
3156
-                        $this->model_field_array()
3157
-                    ),
3158
-                    array(
3159
-                        'default_where_conditions' => 'minimum',
3160
-                    )
3161
-                ),
3162
-                $field->get_name()
3163
-            );
3164
-            $this->set_from_db(
3165
-                $field->get_name(),
3166
-                $new_value
3167
-            );
3168
-        }
3169
-        return (bool) $result;
3170
-    }
3171
-
3172
-
3173
-    /**
3174
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3175
-     * Does not allow negative values, however.
3176
-     *
3177
-     * @since 4.9.80.p
3178
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3179
-     *                                   (positive or negative). One important gotcha: all these values must be
3180
-     *                                   on the same table (eg don't pass in one field for the posts table and
3181
-     *                                   another for the event meta table.)
3182
-     * @return bool
3183
-     * @throws EE_Error
3184
-     * @throws InvalidArgumentException
3185
-     * @throws InvalidDataTypeException
3186
-     * @throws InvalidInterfaceException
3187
-     * @throws ReflectionException
3188
-     */
3189
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3190
-    {
3191
-        global $wpdb;
3192
-        if (empty($fields_n_quantities)) {
3193
-            // No fields to update? Well sure, we updated them to that value just fine.
3194
-            return true;
3195
-        }
3196
-        $fields = [];
3197
-        $set_sql_statements = [];
3198
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3199
-            $field = $this->get_model()->field_settings_for($field_name, true);
3200
-            $fields[] = $field;
3201
-            $column_name = $field->get_table_column();
3202
-
3203
-            $abs_qty = absint($quantity);
3204
-            if ($quantity > 0) {
3205
-                // don't let the value be negative as often these fields are unsigned
3206
-                $set_sql_statements[] = $wpdb->prepare(
3207
-                    "`{$column_name}` = `{$column_name}` + %d",
3208
-                    $abs_qty
3209
-                );
3210
-            } else {
3211
-                $set_sql_statements[] = $wpdb->prepare(
3212
-                    "`{$column_name}` = CASE
3147
+				$table_pk_value
3148
+			);
3149
+		$result = $wpdb->query($query);
3150
+		foreach ($fields as $field) {
3151
+			// If it was successful, we'd like to know the new value.
3152
+			// If it failed, we'd also like to know the new value.
3153
+			$new_value = $this->get_model()->get_var(
3154
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3155
+					$this->get_model()->get_index_primary_key_string(
3156
+						$this->model_field_array()
3157
+					),
3158
+					array(
3159
+						'default_where_conditions' => 'minimum',
3160
+					)
3161
+				),
3162
+				$field->get_name()
3163
+			);
3164
+			$this->set_from_db(
3165
+				$field->get_name(),
3166
+				$new_value
3167
+			);
3168
+		}
3169
+		return (bool) $result;
3170
+	}
3171
+
3172
+
3173
+	/**
3174
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3175
+	 * Does not allow negative values, however.
3176
+	 *
3177
+	 * @since 4.9.80.p
3178
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3179
+	 *                                   (positive or negative). One important gotcha: all these values must be
3180
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3181
+	 *                                   another for the event meta table.)
3182
+	 * @return bool
3183
+	 * @throws EE_Error
3184
+	 * @throws InvalidArgumentException
3185
+	 * @throws InvalidDataTypeException
3186
+	 * @throws InvalidInterfaceException
3187
+	 * @throws ReflectionException
3188
+	 */
3189
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3190
+	{
3191
+		global $wpdb;
3192
+		if (empty($fields_n_quantities)) {
3193
+			// No fields to update? Well sure, we updated them to that value just fine.
3194
+			return true;
3195
+		}
3196
+		$fields = [];
3197
+		$set_sql_statements = [];
3198
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3199
+			$field = $this->get_model()->field_settings_for($field_name, true);
3200
+			$fields[] = $field;
3201
+			$column_name = $field->get_table_column();
3202
+
3203
+			$abs_qty = absint($quantity);
3204
+			if ($quantity > 0) {
3205
+				// don't let the value be negative as often these fields are unsigned
3206
+				$set_sql_statements[] = $wpdb->prepare(
3207
+					"`{$column_name}` = `{$column_name}` + %d",
3208
+					$abs_qty
3209
+				);
3210
+			} else {
3211
+				$set_sql_statements[] = $wpdb->prepare(
3212
+					"`{$column_name}` = CASE
3213 3213
                        WHEN (`{$column_name}` >= %d)
3214 3214
                        THEN `{$column_name}` - %d
3215 3215
                        ELSE 0
3216 3216
                     END",
3217
-                    $abs_qty,
3218
-                    $abs_qty
3219
-                );
3220
-            }
3221
-        }
3222
-        return $this->updateFieldsInDB(
3223
-            $fields,
3224
-            implode(', ', $set_sql_statements)
3225
-        );
3226
-    }
3227
-
3228
-
3229
-    /**
3230
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3231
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3232
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3233
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3234
-     * Otherwise returns false.
3235
-     *
3236
-     * @since 4.9.80.p
3237
-     * @param string $field_name_to_bump
3238
-     * @param string $field_name_affecting_total
3239
-     * @param string $limit_field_name
3240
-     * @param int    $quantity
3241
-     * @return bool
3242
-     * @throws EE_Error
3243
-     * @throws InvalidArgumentException
3244
-     * @throws InvalidDataTypeException
3245
-     * @throws InvalidInterfaceException
3246
-     * @throws ReflectionException
3247
-     */
3248
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3249
-    {
3250
-        global $wpdb;
3251
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3252
-        $column_name = $field->get_table_column();
3253
-
3254
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3255
-        $column_affecting_total = $field_affecting_total->get_table_column();
3256
-
3257
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3258
-        $limiting_column = $limiting_field->get_table_column();
3259
-        return $this->updateFieldsInDB(
3260
-            [$field],
3261
-            $wpdb->prepare(
3262
-                "`{$column_name}` =
3217
+					$abs_qty,
3218
+					$abs_qty
3219
+				);
3220
+			}
3221
+		}
3222
+		return $this->updateFieldsInDB(
3223
+			$fields,
3224
+			implode(', ', $set_sql_statements)
3225
+		);
3226
+	}
3227
+
3228
+
3229
+	/**
3230
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3231
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3232
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3233
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3234
+	 * Otherwise returns false.
3235
+	 *
3236
+	 * @since 4.9.80.p
3237
+	 * @param string $field_name_to_bump
3238
+	 * @param string $field_name_affecting_total
3239
+	 * @param string $limit_field_name
3240
+	 * @param int    $quantity
3241
+	 * @return bool
3242
+	 * @throws EE_Error
3243
+	 * @throws InvalidArgumentException
3244
+	 * @throws InvalidDataTypeException
3245
+	 * @throws InvalidInterfaceException
3246
+	 * @throws ReflectionException
3247
+	 */
3248
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3249
+	{
3250
+		global $wpdb;
3251
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3252
+		$column_name = $field->get_table_column();
3253
+
3254
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3255
+		$column_affecting_total = $field_affecting_total->get_table_column();
3256
+
3257
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3258
+		$limiting_column = $limiting_field->get_table_column();
3259
+		return $this->updateFieldsInDB(
3260
+			[$field],
3261
+			$wpdb->prepare(
3262
+				"`{$column_name}` =
3263 3263
             CASE
3264 3264
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3265 3265
                THEN `{$column_name}` + %d
3266 3266
                ELSE `{$column_name}`
3267 3267
             END",
3268
-                $quantity,
3269
-                EE_INF_IN_DB,
3270
-                $quantity
3271
-            )
3272
-        );
3273
-    }
3274
-
3275
-
3276
-    /**
3277
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3278
-     * (probably a bad assumption they have made, oh well)
3279
-     *
3280
-     * @return string
3281
-     */
3282
-    public function __toString()
3283
-    {
3284
-        try {
3285
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3286
-        } catch (Exception $e) {
3287
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3288
-            return '';
3289
-        }
3290
-    }
3291
-
3292
-
3293
-    /**
3294
-     * Clear related model objects if they're already in the DB, because otherwise when we
3295
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3296
-     * This means if we have made changes to those related model objects, and want to unserialize
3297
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3298
-     * Instead, those related model objects should be directly serialized and stored.
3299
-     * Eg, the following won't work:
3300
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3301
-     * $att = $reg->attendee();
3302
-     * $att->set( 'ATT_fname', 'Dirk' );
3303
-     * update_option( 'my_option', serialize( $reg ) );
3304
-     * //END REQUEST
3305
-     * //START NEXT REQUEST
3306
-     * $reg = get_option( 'my_option' );
3307
-     * $reg->attendee()->save();
3308
-     * And would need to be replace with:
3309
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3310
-     * $att = $reg->attendee();
3311
-     * $att->set( 'ATT_fname', 'Dirk' );
3312
-     * update_option( 'my_option', serialize( $reg ) );
3313
-     * //END REQUEST
3314
-     * //START NEXT REQUEST
3315
-     * $att = get_option( 'my_option' );
3316
-     * $att->save();
3317
-     *
3318
-     * @return array
3319
-     * @throws ReflectionException
3320
-     * @throws InvalidArgumentException
3321
-     * @throws InvalidInterfaceException
3322
-     * @throws InvalidDataTypeException
3323
-     * @throws EE_Error
3324
-     */
3325
-    public function __sleep()
3326
-    {
3327
-        $model = $this->get_model();
3328
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3329
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3330
-                $classname = 'EE_' . $model->get_this_model_name();
3331
-                if (
3332
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3333
-                    && $this->get_one_from_cache($relation_name)->ID()
3334
-                ) {
3335
-                    $this->clear_cache(
3336
-                        $relation_name,
3337
-                        $this->get_one_from_cache($relation_name)->ID()
3338
-                    );
3339
-                }
3340
-            }
3341
-        }
3342
-        $this->_props_n_values_provided_in_constructor = array();
3343
-        $properties_to_serialize = get_object_vars($this);
3344
-        // don't serialize the model. It's big and that risks recursion
3345
-        unset($properties_to_serialize['_model']);
3346
-        return array_keys($properties_to_serialize);
3347
-    }
3348
-
3349
-
3350
-    /**
3351
-     * restore _props_n_values_provided_in_constructor
3352
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3353
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3354
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3355
-     */
3356
-    public function __wakeup()
3357
-    {
3358
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3359
-    }
3360
-
3361
-
3362
-    /**
3363
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3364
-     * distinct with the clone host instance are also cloned.
3365
-     */
3366
-    public function __clone()
3367
-    {
3368
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3369
-        foreach ($this->_fields as $field => $value) {
3370
-            if ($value instanceof DateTime) {
3371
-                $this->_fields[ $field ] = clone $value;
3372
-            }
3373
-        }
3374
-    }
3268
+				$quantity,
3269
+				EE_INF_IN_DB,
3270
+				$quantity
3271
+			)
3272
+		);
3273
+	}
3274
+
3275
+
3276
+	/**
3277
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3278
+	 * (probably a bad assumption they have made, oh well)
3279
+	 *
3280
+	 * @return string
3281
+	 */
3282
+	public function __toString()
3283
+	{
3284
+		try {
3285
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3286
+		} catch (Exception $e) {
3287
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3288
+			return '';
3289
+		}
3290
+	}
3291
+
3292
+
3293
+	/**
3294
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3295
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3296
+	 * This means if we have made changes to those related model objects, and want to unserialize
3297
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3298
+	 * Instead, those related model objects should be directly serialized and stored.
3299
+	 * Eg, the following won't work:
3300
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3301
+	 * $att = $reg->attendee();
3302
+	 * $att->set( 'ATT_fname', 'Dirk' );
3303
+	 * update_option( 'my_option', serialize( $reg ) );
3304
+	 * //END REQUEST
3305
+	 * //START NEXT REQUEST
3306
+	 * $reg = get_option( 'my_option' );
3307
+	 * $reg->attendee()->save();
3308
+	 * And would need to be replace with:
3309
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3310
+	 * $att = $reg->attendee();
3311
+	 * $att->set( 'ATT_fname', 'Dirk' );
3312
+	 * update_option( 'my_option', serialize( $reg ) );
3313
+	 * //END REQUEST
3314
+	 * //START NEXT REQUEST
3315
+	 * $att = get_option( 'my_option' );
3316
+	 * $att->save();
3317
+	 *
3318
+	 * @return array
3319
+	 * @throws ReflectionException
3320
+	 * @throws InvalidArgumentException
3321
+	 * @throws InvalidInterfaceException
3322
+	 * @throws InvalidDataTypeException
3323
+	 * @throws EE_Error
3324
+	 */
3325
+	public function __sleep()
3326
+	{
3327
+		$model = $this->get_model();
3328
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3329
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3330
+				$classname = 'EE_' . $model->get_this_model_name();
3331
+				if (
3332
+					$this->get_one_from_cache($relation_name) instanceof $classname
3333
+					&& $this->get_one_from_cache($relation_name)->ID()
3334
+				) {
3335
+					$this->clear_cache(
3336
+						$relation_name,
3337
+						$this->get_one_from_cache($relation_name)->ID()
3338
+					);
3339
+				}
3340
+			}
3341
+		}
3342
+		$this->_props_n_values_provided_in_constructor = array();
3343
+		$properties_to_serialize = get_object_vars($this);
3344
+		// don't serialize the model. It's big and that risks recursion
3345
+		unset($properties_to_serialize['_model']);
3346
+		return array_keys($properties_to_serialize);
3347
+	}
3348
+
3349
+
3350
+	/**
3351
+	 * restore _props_n_values_provided_in_constructor
3352
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3353
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3354
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3355
+	 */
3356
+	public function __wakeup()
3357
+	{
3358
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3359
+	}
3360
+
3361
+
3362
+	/**
3363
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3364
+	 * distinct with the clone host instance are also cloned.
3365
+	 */
3366
+	public function __clone()
3367
+	{
3368
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3369
+		foreach ($this->_fields as $field => $value) {
3370
+			if ($value instanceof DateTime) {
3371
+				$this->_fields[ $field ] = clone $value;
3372
+			}
3373
+		}
3374
+	}
3375 3375
 }
Please login to merge, or discard this patch.
core/EE_Data_Mapper.core.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -16,99 +16,99 @@
 block discarded – undo
16 16
 {
17 17
 
18 18
 
19
-    /**
20
-     * instance of the EE_Data_Mapper Object
21
-     *
22
-     * @private _instance
23
-     */
24
-    private static $_instance = null;
25
-
26
-
27
-    public $data = array();
28
-
29
-
30
-    /**
31
-     *private constructor to prevent direct creation
32
-     *
33
-     * @Constructor
34
-     * @access private
35
-     * @return void
36
-     */
37
-    private function __construct()
38
-    {
39
-    }
40
-
41
-
42
-    /**
43
-     *@ singleton method used to instantiate class object
44
-     *@ access public
45
-     *@ return class instance
46
-     */
47
-    public function &instance()
48
-    {
49
-        // check if class object is instantiated
50
-        if (
51
-            self::$_instance === null
52
-            || ! is_object(self::$_instance)
53
-            || ! self::$_instance instanceof EE_Data_Mapper
54
-        ) {
55
-            self::$_instance = new self();
56
-        }
57
-        return self::$_instance;
58
-    }
59
-
60
-
61
-    /**
62
-     *        @ override magic methods
63
-     *        @ return void
64
-     */
65
-    final public function __destruct()
66
-    {
67
-    }
68
-
69
-    final public function __call($a, $b)
70
-    {
71
-    }
72
-
73
-    public static function __callStatic($a, $b)
74
-    {
75
-    }
76
-
77
-    final public function __get($a)
78
-    {
79
-    }
80
-
81
-    final public function __set($a, $b)
82
-    {
83
-    }
84
-
85
-    final public function __isset($a)
86
-    {
87
-    }
88
-
89
-    final public function __unset($a)
90
-    {
91
-    }
92
-
93
-    final public function __sleep()
94
-    {
95
-        return array();
96
-    }
97
-
98
-    final public function __wakeup()
99
-    {
100
-    }
101
-
102
-    final public function __toString()
103
-    {
104
-        return '';
105
-    }
106
-
107
-    final public function __invoke()
108
-    {
109
-    }
110
-
111
-    final public function __clone()
112
-    {
113
-    }
19
+	/**
20
+	 * instance of the EE_Data_Mapper Object
21
+	 *
22
+	 * @private _instance
23
+	 */
24
+	private static $_instance = null;
25
+
26
+
27
+	public $data = array();
28
+
29
+
30
+	/**
31
+	 *private constructor to prevent direct creation
32
+	 *
33
+	 * @Constructor
34
+	 * @access private
35
+	 * @return void
36
+	 */
37
+	private function __construct()
38
+	{
39
+	}
40
+
41
+
42
+	/**
43
+	 *@ singleton method used to instantiate class object
44
+	 *@ access public
45
+	 *@ return class instance
46
+	 */
47
+	public function &instance()
48
+	{
49
+		// check if class object is instantiated
50
+		if (
51
+			self::$_instance === null
52
+			|| ! is_object(self::$_instance)
53
+			|| ! self::$_instance instanceof EE_Data_Mapper
54
+		) {
55
+			self::$_instance = new self();
56
+		}
57
+		return self::$_instance;
58
+	}
59
+
60
+
61
+	/**
62
+	 *        @ override magic methods
63
+	 *        @ return void
64
+	 */
65
+	final public function __destruct()
66
+	{
67
+	}
68
+
69
+	final public function __call($a, $b)
70
+	{
71
+	}
72
+
73
+	public static function __callStatic($a, $b)
74
+	{
75
+	}
76
+
77
+	final public function __get($a)
78
+	{
79
+	}
80
+
81
+	final public function __set($a, $b)
82
+	{
83
+	}
84
+
85
+	final public function __isset($a)
86
+	{
87
+	}
88
+
89
+	final public function __unset($a)
90
+	{
91
+	}
92
+
93
+	final public function __sleep()
94
+	{
95
+		return array();
96
+	}
97
+
98
+	final public function __wakeup()
99
+	{
100
+	}
101
+
102
+	final public function __toString()
103
+	{
104
+		return '';
105
+	}
106
+
107
+	final public function __invoke()
108
+	{
109
+	}
110
+
111
+	final public function __clone()
112
+	{
113
+	}
114 114
 }
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
@@ -15,894 +15,894 @@
 block discarded – undo
15 15
 abstract class EE_Data_Migration_Script_Base extends EE_Data_Migration_Class_Base
16 16
 {
17 17
 
18
-    /**
19
-     * Set by client code to indicate this DMS is being ran as part of a proper migration,
20
-     * instead of being used to merely setup (or verify) the database structure.
21
-     * Defaults to TRUE, so client code that's NOT using this DMS as part of a proper migration
22
-     * should call EE_Data_Migration_Script_Base::set_migrating( FALSE )
23
-     *
24
-     * @var boolean
25
-     */
26
-    protected $_migrating = true;
27
-
28
-    /**
29
-     * numerically-indexed array where each value is EE_Data_Migration_Script_Stage object
30
-     *
31
-     * @var EE_Data_Migration_Script_Stage[] $migration_functions
32
-     */
33
-    protected $_migration_stages = array();
34
-
35
-    /**
36
-     * Indicates we've already ran the schema changes that needed to happen BEFORE the data migration
37
-     *
38
-     * @var boolean
39
-     */
40
-    protected $_schema_changes_before_migration_ran = null;
41
-
42
-    /**
43
-     * Indicates we've already ran the schema changes that needed to happen AFTER the data migration
44
-     *
45
-     * @var boolean
46
-     */
47
-    protected $_schema_changes_after_migration_ran = null;
48
-
49
-    /**
50
-     * String which describes what's currently happening in this migration
51
-     *
52
-     * @var string
53
-     */
54
-    protected $_feedback_message;
55
-
56
-    /**
57
-     * Indicates the script's priority. Like wp's add_action and add_filter, lower numbers
58
-     * correspond to earlier execution
59
-     *
60
-     * @var int
61
-     */
62
-    protected $_priority = 5;
63
-
64
-    /**
65
-     * Multi-dimensional array that defines the mapping from OLD table Primary Keys
66
-     * to NEW table Primary Keys.
67
-     * Top-level array keys are OLD table names (minus the "wp_" part),
68
-     * 2nd-level array keys are NEW table names (again, minus the "wp_" part),
69
-     * 3rd-level array keys are the OLD table primary keys
70
-     * and 3rd-level array values are the NEW table primary keys
71
-     *
72
-     * @var array
73
-     */
74
-    protected $_mappings = array();
75
-
76
-    /**
77
-     * @var EE_Data_Migration_Script_Base
78
-     */
79
-    protected $previous_dms;
80
-
81
-
82
-    /**
83
-     * Returns whether or not this data migration script can operate on the given version of the database.
84
-     * Eg, if this migration script can migrate from 3.1.26 or higher (but not anything after 4.0.0), and
85
-     * it's passed a string like '3.1.38B', it should return true.
86
-     * If this DMS is to migrate data from an EE3 addon, you will probably want to use
87
-     * EventEspresso\core\services\database\TableAnalysis::tableExists() to check for old EE3 tables, and
88
-     * EE_Data_Migration_Manager::get_migration_ran() to check that core was already
89
-     * migrated from EE3 to EE4 (ie, this DMS probably relies on some migration data generated
90
-     * during the Core 4.1.0 DMS. If core didn't run that DMS, you probably don't want
91
-     * to run this DMS).
92
-     * If this DMS migrates data from a previous version of this EE4 addon, just
93
-     * comparing $current_database_state_of[ $this->slug() ] will probably suffice.
94
-     * If this DMS should never migrate data, because it's only used to define the initial
95
-     * database state, just return FALSE (and core's activation process will take care
96
-     * of calling its schema_changes_before_migration() and
97
-     * schema_changes_after_migration() for you. )
98
-     *
99
-     * @param array $current_database_state_of keys are EE plugin slugs (eg 'Core', 'Calendar', 'Mailchimp', etc)
100
-     * @return boolean
101
-     */
102
-    abstract public function can_migrate_from_version($current_database_state_of);
103
-
104
-
105
-    /**
106
-     * Performs database schema changes that need to occur BEFORE the data is migrated.
107
-     * Eg, if we were going to change user passwords from plaintext to encoded versions
108
-     * during this migration, this would probably add a new column called something like
109
-     * "encoded_password".
110
-     *
111
-     * @return boolean of success
112
-     */
113
-    abstract public function schema_changes_before_migration();
114
-
115
-
116
-    /**
117
-     * Performs the database schema changes that need to occur AFTER the data has been migrated.
118
-     * Usually this will mean we'll be removing old columns. Eg, if we were changing passwords
119
-     * from plaintext to encoded versions, and we had added a column called "encoded_password",
120
-     * this function would probably remove the old column "password" (which still holds the plaintext password)
121
-     * and possibly rename "encoded_password" to "password"
122
-     *
123
-     * @return boolean of success
124
-     */
125
-    abstract public function schema_changes_after_migration();
126
-
127
-
128
-    /**
129
-     * All children of this must call parent::__construct()
130
-     * at the end of their constructor or suffer the consequences!
131
-     *
132
-     * @param TableManager  $table_manager
133
-     * @param TableAnalysis $table_analysis
134
-     */
135
-    public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
136
-    {
137
-        $this->_migration_stages = (array) apply_filters(
138
-            'FHEE__' . get_class($this) . '__construct__migration_stages',
139
-            $this->_migration_stages
140
-        );
141
-        foreach ($this->_migration_stages as $migration_stage) {
142
-            if ($migration_stage instanceof EE_Data_Migration_Script_Stage) {
143
-                $migration_stage->_construct_finalize($this);
144
-            }
145
-        }
146
-        parent::__construct($table_manager, $table_analysis);
147
-    }
148
-
149
-
150
-    /**
151
-     * Place to add hooks and filters for tweaking the migrations page, in order
152
-     * to customize it
153
-     */
154
-    public function migration_page_hooks()
155
-    {
156
-        // by default none are added because we normally like the default look of the migration page
157
-    }
158
-
159
-
160
-    /**
161
-     * Sets the mapping from old table primary keys to new table primary keys.
162
-     * This mapping is automatically persisted as a property on the migration
163
-     *
164
-     * @param string     $old_table with wpdb prefix (wp_). Eg: wp_events_detail
165
-     * @param int|string $old_pk    old primary key. Eg events_detail.id's value
166
-     * @param string     $new_table with wpdb prefix (wp_). Eg: wp_posts
167
-     * @param int|string $new_pk    eg posts.ID
168
-     * @return void
169
-     */
170
-    public function set_mapping($old_table, $old_pk, $new_table, $new_pk)
171
-    {
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);
175
-        }
176
-        $this->_mappings[ $old_table ][ $new_table ][ $old_pk ] = $new_pk;
177
-    }
178
-
179
-
180
-    /**
181
-     * Gets the new primary key, if provided with the OLD table and the primary key
182
-     * of an item in the old table, and the new table
183
-     *
184
-     * @param string     $old_table with wpdb prefix (wp_). Eg: wp_events_detail
185
-     * @param int|string $old_pk    old primary key. Eg events_detail.id's value
186
-     * @param string     $new_table with wpdb prefix (wp_). Eg: wp_posts
187
-     * @return mixed the primary key on the new table
188
-     */
189
-    public function get_mapping_new_pk($old_table, $old_pk, $new_table)
190
-    {
191
-        if (
192
-            ! isset($this->_mappings[ $old_table ]) ||
193
-            ! isset($this->_mappings[ $old_table ][ $new_table ])
194
-        ) {
195
-            // try fetching the option
196
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
197
-        }
198
-        return isset($this->_mappings[ $old_table ][ $new_table ][ $old_pk ])
199
-            ? $this->_mappings[ $old_table ][ $new_table ][ $old_pk ] : null;
200
-    }
201
-
202
-
203
-    /**
204
-     * Gets the old primary key, if provided with the OLD table,
205
-     * and the new table and the primary key of an item in the new table
206
-     *
207
-     * @param string $old_table with wpdb prefix (wp_). Eg: wp_events_detail
208
-     * @param string $new_table with wpdb prefix (wp_). Eg: wp_posts
209
-     * @param mixed  $new_pk
210
-     * @return mixed
211
-     */
212
-    public function get_mapping_old_pk($old_table, $new_table, $new_pk)
213
-    {
214
-        if (
215
-            ! isset($this->_mappings[ $old_table ]) ||
216
-            ! isset($this->_mappings[ $old_table ][ $new_table ])
217
-        ) {
218
-            // try fetching the option
219
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
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 ];
225
-            }
226
-        }
227
-        return null;
228
-    }
229
-
230
-
231
-    /**
232
-     * Gets the mapping array option specified by the table names
233
-     *
234
-     * @param string $old_table_name
235
-     * @param string $new_table_name
236
-     * @return array
237
-     */
238
-    protected function _get_mapping_option($old_table_name, $new_table_name)
239
-    {
240
-        $option = get_option($this->_get_mapping_option_name($old_table_name, $new_table_name), array());
241
-        return $option;
242
-    }
243
-
244
-
245
-    /**
246
-     * Updates the mapping option specified by the table names with the array provided
247
-     *
248
-     * @param string $old_table_name
249
-     * @param string $new_table_name
250
-     * @param array  $mapping_array
251
-     * @return boolean success of updating option
252
-     */
253
-    protected function _set_mapping_option($old_table_name, $new_table_name, $mapping_array)
254
-    {
255
-        $success = update_option($this->_get_mapping_option_name($old_table_name, $new_table_name), $mapping_array, false);
256
-        return $success;
257
-    }
258
-
259
-
260
-    /**
261
-     * Gets the option name for this script to map from $old_table_name to $new_table_name
262
-     *
263
-     * @param string $old_table_name
264
-     * @param string $new_table_name
265
-     * @return string
266
-     */
267
-    protected function _get_mapping_option_name($old_table_name, $new_table_name)
268
-    {
269
-        global $wpdb;
270
-        $old_table_name_sans_wp = str_replace($wpdb->prefix, "", $old_table_name);
271
-        $new_table_name_sans_wp = str_replace($wpdb->prefix, "", $new_table_name);
272
-        $migrates_to = EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
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,
275
-            0,
276
-            64
277
-        );
278
-    }
279
-
280
-
281
-    /**
282
-     * Counts all the records that will be migrated during this data migration.
283
-     * For example, if we were changing old user passwords from plaintext to encoded versions,
284
-     * this would be a count of all users who have passwords. If we were going to also split
285
-     * attendee records into transactions, registrations, and attendee records, this would include
286
-     * the count of all attendees currently in existence in the DB (ie, users + attendees).
287
-     * If you can't determine how many records there are to migrate, just provide a guess: this
288
-     * number will only be used in calculating the percent complete. If you estimate there to be
289
-     * 100 records to migrate, and it turns out there's 120, we'll just show the migration as being at
290
-     * 99% until the function "migration_step" returns EE_Data_Migration_Script_Base::status_complete.
291
-     *
292
-     * @return int
293
-     */
294
-    protected function _count_records_to_migrate()
295
-    {
296
-        $count = 0;
297
-        foreach ($this->stages() as $stage) {
298
-            $count += $stage->count_records_to_migrate();
299
-        }
300
-        return $count;
301
-    }
302
-
303
-
304
-    /**
305
-     * Returns the number of records updated so far. Usually this is easiest to do
306
-     * by just setting a transient and updating it after each migration_step
307
-     *
308
-     * @return int
309
-     */
310
-    public function count_records_migrated()
311
-    {
312
-        $count = 0;
313
-        foreach ($this->stages() as $stage) {
314
-            $count += $stage->count_records_migrated();
315
-        }
316
-        $this->_records_migrated = $count;
317
-        return $count;
318
-    }
319
-
320
-
321
-    /**
322
-     * @param int $num_records_to_migrate_limit
323
-     * @return int
324
-     * @throws EE_Error
325
-     * @throws Exception
326
-     */
327
-    public function migration_step($num_records_to_migrate_limit)
328
-    {
329
-        // reset the feedback message
330
-        $this->_feedback_message = '';
331
-        // if we haven't yet done the 1st schema changes, do them now. buffer any output
332
-        $this->_maybe_do_schema_changes(true);
333
-
334
-        $num_records_actually_migrated = 0;
335
-        $records_migrated_per_stage = array();
336
-        // setup the 'stage' variable, which should hold the last run stage of the migration  (or none at all if nothing runs)
337
-        $stage = null;
338
-        // get the next stage that isn't complete
339
-        foreach ($this->stages() as $stage) {
340
-            if ($stage->get_status() == EE_Data_Migration_Manager::status_continue) {
341
-                try {
342
-                    $records_migrated_during_stage = $stage->migration_step(
343
-                        $num_records_to_migrate_limit - $num_records_actually_migrated
344
-                    );
345
-                    $num_records_actually_migrated += $records_migrated_during_stage;
346
-                    $records_migrated_per_stage[ $stage->pretty_name() ] = $records_migrated_during_stage;
347
-                } catch (Exception $e) {
348
-                    // yes if we catch an exception here, we consider that migration stage borked.
349
-                    $stage->set_status(EE_Data_Migration_Manager::status_fatal_error);
350
-                    $this->set_status(EE_Data_Migration_Manager::status_fatal_error);
351
-                    $stage->add_error($e->getMessage() . ". Stack-trace:" . $e->getTraceAsString());
352
-                    throw $e;
353
-                }
354
-                // check that the migration stage didn't mark itself as having a fatal error
355
-                if ($stage->is_broken()) {
356
-                    $this->set_broken();
357
-                    throw new EE_Error($stage->get_last_error());
358
-                }
359
-            }
360
-            // once we've migrated all the number we intended to (possibly from different stages), stop migrating
361
-            // or if we had a fatal error
362
-            // or if the current script stopped early- its not done, but it's done all it thinks we should do on this step
363
-            if (
364
-                $num_records_actually_migrated >= $num_records_to_migrate_limit
365
-                || $stage->is_broken()
366
-                || $stage->has_more_to_do()
367
-            ) {
368
-                break;
369
-            }
370
-        }
371
-        // check if we're all done this data migration...
372
-        // which is indicated by being done early AND the last stage claims to be done
373
-        if ($stage == null) {
374
-            // this migration script apparently has NO stages... which is super weird, but whatever
375
-            $this->set_completed();
376
-            $this->_maybe_do_schema_changes(false);
377
-        } elseif ($num_records_actually_migrated < $num_records_to_migrate_limit && ! $stage->has_more_to_do()) {
378
-            // apparently we're done, because we couldn't migrate the number we intended to
379
-            $this->set_completed();
380
-            $this->_update_feedback_message(array_reverse($records_migrated_per_stage));
381
-            // do schema changes for after the migration now
382
-            // first double-check we haven't already done this
383
-            $this->_maybe_do_schema_changes(false);
384
-        } else {
385
-            // update feedback message, keeping in mind that we show them with the most recent at the top
386
-            $this->_update_feedback_message(array_reverse($records_migrated_per_stage));
387
-        }
388
-        return $num_records_actually_migrated;
389
-    }
390
-
391
-
392
-    /**
393
-     * Updates the feedback message according to what was done during this migration stage.
394
-     *
395
-     * @param array $records_migrated_per_stage KEYS are pretty names for each stage; values are the count of records
396
-     *                                          migrated from that stage
397
-     * @return void
398
-     */
399
-    private function _update_feedback_message($records_migrated_per_stage)
400
-    {
401
-        $feedback_message_array = array();
402
-        foreach ($records_migrated_per_stage as $migration_stage_name => $num_records_migrated) {
403
-            $feedback_message_array[] = sprintf(
404
-                esc_html__("Migrated %d records successfully during %s", "event_espresso"),
405
-                $num_records_migrated,
406
-                $migration_stage_name
407
-            );
408
-        }
409
-        $this->_feedback_message .= implode("<br>", $feedback_message_array);
410
-    }
411
-
412
-
413
-    /**
414
-     * Calls either schema_changes_before_migration() (if $before==true) or schema_changes_after_migration
415
-     * (if $before==false). Buffers their outputs and stores them on the class.
416
-     *
417
-     * @param boolean $before
418
-     * @throws Exception
419
-     * @return void
420
-     */
421
-    private function _maybe_do_schema_changes($before = true)
422
-    {
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}) {
426
-            try {
427
-                ob_start();
428
-                if ($before) {
429
-                    $this->schema_changes_before_migration();
430
-                } else {
431
-                    $this->schema_changes_after_migration();
432
-                }
433
-                $output = ob_get_contents();
434
-                ob_end_clean();
435
-            } catch (Exception $e) {
436
-                $this->set_status(EE_Data_Migration_Manager::status_fatal_error);
437
-                throw $e;
438
-            }
439
-            // record that we've done these schema changes
440
-            $this->{$property_name} = true;
441
-            // if there were any warnings etc, record them as non-fatal errors
442
-            if ($output) {
443
-                // there were some warnings
444
-                $this->_errors[] = $output;
445
-            }
446
-        }
447
-    }
448
-
449
-
450
-    /**
451
-     * Wrapper for EEH_Activation::create_table. However, takes into account the request type when
452
-     * deciding what to pass for its 4th arg, $drop_pre_existing_tables. Using this function, instead
453
-     * of _table_should_exist_previously, indicates that this table should be new to the EE version being migrated to
454
-     * or
455
-     * activated currently. If this is a brand new activation or a migration, and we're indicating this table should
456
-     * not
457
-     * previously exist, then we want to set $drop_pre_existing_tables to TRUE (ie, we shouldn't discover that this
458
-     * table exists in the DB in EEH_Activation::create_table- if it DOES exist, something's wrong and the old table
459
-     * should be nuked.
460
-     *
461
-     * Just for a bit of context, the migration script's db_schema_changes_* methods
462
-     * are called basically in 3 cases: on brand new activation of EE4 (ie no previous version of EE existed and the
463
-     * plugin is being activated and we want to add all the brand new tables), upon reactivation of EE4 (it was
464
-     * deactivated and then reactivated, in which case we want to just verify the DB structure is ok) that table should
465
-     * be dropped), and during a migration when we're moving the DB to the state of the migration script
466
-     *
467
-     * @param string $table_name
468
-     * @param string $table_definition_sql
469
-     * @param string $engine_string
470
-     */
471
-    protected function _table_is_new_in_this_version(
472
-        $table_name,
473
-        $table_definition_sql,
474
-        $engine_string = 'ENGINE=InnoDB '
475
-    ) {
476
-        $this->_create_table_and_catch_errors(
477
-            $table_name,
478
-            $table_definition_sql,
479
-            $engine_string,
480
-            $this->_pre_existing_table_should_be_dropped(true)
481
-        );
482
-    }
483
-
484
-    /**
485
-     * Like _table_is_new_in_this_version and _table_should_exist_previously, this function verifies the given table
486
-     * exists. But we understand that this table has CHANGED in this version since the previous version. So it's not
487
-     * completely new, but it's different. So we need to treat it like a new table in terms of verifying it's schema is
488
-     * correct on activations, migrations, upgrades; but if it exists when it shouldn't, we need to be as lenient as
489
-     * _table_should_exist_previously.
490
-     * 8656]{Assumes only this plugin could have added this table (ie, if its a new activation of this plugin, the
491
-     * table shouldn't exist).
492
-     *
493
-     * @param string $table_name
494
-     * @param string $table_definition_sql
495
-     * @param string $engine_string
496
-     */
497
-    protected function _table_is_changed_in_this_version(
498
-        $table_name,
499
-        $table_definition_sql,
500
-        $engine_string = 'ENGINE=MyISAM'
501
-    ) {
502
-        $this->_create_table_and_catch_errors(
503
-            $table_name,
504
-            $table_definition_sql,
505
-            $engine_string,
506
-            $this->_pre_existing_table_should_be_dropped(false)
507
-        );
508
-    }
509
-
510
-
511
-    /**
512
-     * _old_table_exists
513
-     * returns TRUE if the requested table exists in the current database
514
-     *
515
-     * @param string $table_name
516
-     * @return boolean
517
-     */
518
-    protected function _old_table_exists($table_name)
519
-    {
520
-        return $this->_get_table_analysis()->tableExists($table_name);
521
-    }
522
-
523
-
524
-    /**
525
-     * _delete_table_if_empty
526
-     * returns TRUE if the requested table was empty and successfully empty
527
-     *
528
-     * @param string $table_name
529
-     * @return boolean
530
-     */
531
-    protected function _delete_table_if_empty($table_name)
532
-    {
533
-        return EEH_Activation::delete_db_table_if_empty($table_name);
534
-    }
535
-
536
-
537
-    /**
538
-     * It is preferred to use _table_has_not_changed_since_previous or _table_is_changed_in_this_version
539
-     * as these are significantly more efficient or explicit.
540
-     * Please see description of _table_is_new_in_this_version. This function will only set
541
-     * EEH_Activation::create_table's $drop_pre_existing_tables to TRUE if it's a brand
542
-     * new activation. ie, a more accurate name for this method would be "_table_added_previously_by_this_plugin"
543
-     * because the table will be cleared out if this is a new activation (ie, if its a new activation, it actually
544
-     * should exist previously). Otherwise, we'll always set $drop_pre_existing_tables to FALSE because the table
545
-     * should have existed. Note, if the table is being MODIFIED in this version being activated or migrated to, then
546
-     * you want _table_is_changed_in_this_version NOT this one. We don't check this table's structure during migrations
547
-     * because apparently it hasn't changed since the previous one, right?
548
-     *
549
-     * @param string $table_name
550
-     * @param string $table_definition_sql
551
-     * @param string $engine_string
552
-     */
553
-    protected function _table_should_exist_previously(
554
-        $table_name,
555
-        $table_definition_sql,
556
-        $engine_string = 'ENGINE=MyISAM'
557
-    ) {
558
-        $this->_create_table_and_catch_errors(
559
-            $table_name,
560
-            $table_definition_sql,
561
-            $engine_string,
562
-            $this->_pre_existing_table_should_be_dropped(false)
563
-        );
564
-    }
565
-
566
-    /**
567
-     * Exactly the same as _table_should_exist_previously(), except if this migration script is currently doing
568
-     * a migration, we skip checking this table's structure in the database and just assume it's correct.
569
-     * So this is useful only to improve efficiency when doing migrations (not a big deal for single site installs,
570
-     * but important for multisite where migrations can take a very long time otherwise).
571
-     * If the table is known to have changed since previous version, use _table_is_changed_in_this_version().
572
-     * Assumes only this plugin could have added this table (ie, if its a new activation of this plugin, the table
573
-     * shouldn't exist).
574
-     *
575
-     * @param string $table_name
576
-     * @param string $table_definition_sql
577
-     * @param string $engine_string
578
-     */
579
-    protected function _table_has_not_changed_since_previous(
580
-        $table_name,
581
-        $table_definition_sql,
582
-        $engine_string = 'ENGINE=MyISAM'
583
-    ) {
584
-        if ($this->_currently_migrating()) {
585
-            // if we're doing a migration, and this table apparently already exists, then we don't need do anything right?
586
-            return;
587
-        }
588
-        $this->_create_table_and_catch_errors(
589
-            $table_name,
590
-            $table_definition_sql,
591
-            $engine_string,
592
-            $this->_pre_existing_table_should_be_dropped(false)
593
-        );
594
-    }
595
-
596
-    /**
597
-     * Returns whether or not this migration script is being used as part of an actual migration
598
-     *
599
-     * @return boolean
600
-     */
601
-    protected function _currently_migrating()
602
-    {
603
-        // 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)
604
-        return $this->_migrating &&
605
-               $this->can_migrate_from_version(
606
-                   EE_Data_Migration_Manager::instance()->ensure_current_database_state_is_set()
607
-               ) &&
608
-               EE_Maintenance_Mode::instance()->real_level() == EE_Maintenance_Mode::level_2_complete_maintenance;
609
-    }
610
-
611
-    /**
612
-     * Determines if a table should be dropped, based on whether it's reported to be new in $table_is_new,
613
-     * and the plugin's request type.
614
-     * Assumes only this plugin could have added the table (ie, if its a new activation of this plugin, the table
615
-     * shouldn't exist no matter what).
616
-     *
617
-     * @param boolean $table_is_new
618
-     * @return boolean
619
-     */
620
-    protected function _pre_existing_table_should_be_dropped($table_is_new)
621
-    {
622
-        if ($table_is_new) {
623
-            if (
624
-                $this->_get_req_type_for_plugin_corresponding_to_this_dms() == EE_System::req_type_new_activation
625
-                || $this->_currently_migrating()
626
-            ) {
627
-                return true;
628
-            } else {
629
-                return false;
630
-            }
631
-        } else {
632
-            if (
633
-                in_array(
634
-                    $this->_get_req_type_for_plugin_corresponding_to_this_dms(),
635
-                    array(EE_System::req_type_new_activation)
636
-                )
637
-            ) {
638
-                return true;
639
-            } else {
640
-                return false;
641
-            }
642
-        }
643
-    }
644
-
645
-    /**
646
-     * Just wraps EEH_Activation::create_table, but catches any errors it may throw and adds them as errors on the DMS
647
-     *
648
-     * @param string  $table_name
649
-     * @param string  $table_definition_sql
650
-     * @param string  $engine_string
651
-     * @param boolean $drop_pre_existing_tables
652
-     */
653
-    private function _create_table_and_catch_errors(
654
-        $table_name,
655
-        $table_definition_sql,
656
-        $engine_string = 'ENGINE=MyISAM',
657
-        $drop_pre_existing_tables = false
658
-    ) {
659
-        try {
660
-            EEH_Activation::create_table($table_name, $table_definition_sql, $engine_string, $drop_pre_existing_tables);
661
-        } catch (EE_Error $e) {
662
-            $message = $e->getMessage() . '<br>Stack Trace:' . $e->getTraceAsString();
663
-            $this->add_error($message);
664
-            $this->_feedback_message .= $message;
665
-        }
666
-    }
667
-
668
-
669
-    /**
670
-     * Gets the request type for the plugin (core or addon) that corresponds to this DMS
671
-     *
672
-     * @return int one of EE_System::_req_type_* constants
673
-     * @throws EE_Error
674
-     */
675
-    private function _get_req_type_for_plugin_corresponding_to_this_dms()
676
-    {
677
-        if ($this->slug() == 'Core') {
678
-            return EE_System::instance()->detect_req_type();
679
-        } else {// it must be for an addon
680
-            $addon_name = $this->slug();
681
-            if (EE_Registry::instance()->get_addon_by_name($addon_name)) {
682
-                return EE_Registry::instance()->get_addon_by_name($addon_name)->detect_req_type();
683
-            } else {
684
-                throw new EE_Error(
685
-                    sprintf(
686
-                        esc_html__(
687
-                            "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",
688
-                            "event_espresso"
689
-                        ),
690
-                        $this->slug(),
691
-                        $addon_name,
692
-                        implode(",", array_keys(EE_Registry::instance()->get_addons_by_name()))
693
-                    )
694
-                );
695
-            }
696
-        }
697
-    }
698
-
699
-
700
-    /**
701
-     * returns an array of strings describing errors by all the script's stages
702
-     *
703
-     * @return array
704
-     */
705
-    public function get_errors()
706
-    {
707
-        $all_errors = $this->_errors;
708
-        if (! is_array($all_errors)) {
709
-            $all_errors = array();
710
-        }
711
-        foreach ($this->stages() as $stage) {
712
-            $all_errors = array_merge($stage->get_errors(), $all_errors);
713
-        }
714
-        return $all_errors;
715
-    }
716
-
717
-
718
-    /**
719
-     * Indicates whether or not this migration script should continue
720
-     *
721
-     * @return boolean
722
-     */
723
-    public function can_continue()
724
-    {
725
-        return in_array(
726
-            $this->get_status(),
727
-            EE_Data_Migration_Manager::instance()->stati_that_indicate_to_continue_single_migration_script
728
-        );
729
-    }
730
-
731
-
732
-    /**
733
-     * Gets all the data migration stages associated with this script. Note:
734
-     * addons can filter this list to add their own stages, and because the list is
735
-     * numerically-indexed, they can insert their stage wherever they like and it will
736
-     * get ordered by the indexes
737
-     *
738
-     * @return EE_Data_Migration_Script_Stage[]
739
-     */
740
-    protected function stages()
741
-    {
742
-        $stages = apply_filters('FHEE__' . get_class($this) . '__stages', $this->_migration_stages);
743
-        ksort($stages);
744
-        return $stages;
745
-    }
746
-
747
-
748
-    /**
749
-     * Gets a string which should describe what's going on currently with this migration, which
750
-     * can be displayed to the user
751
-     *
752
-     * @return string
753
-     */
754
-    public function get_feedback_message()
755
-    {
756
-        return $this->_feedback_message;
757
-    }
758
-
759
-
760
-    /**
761
-     * A lot like "__sleep()" magic method in purpose, this is meant for persisting this class'
762
-     * properties to the DB. However, we don't want to use __sleep() because its quite
763
-     * possible that this class is defined when it goes to sleep, but NOT available when it
764
-     * awakes (eg, this class is part of an addon that is deactivated at some point).
765
-     */
766
-    public function properties_as_array()
767
-    {
768
-        $properties = parent::properties_as_array();
769
-        $properties['_migration_stages'] = array();
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(
772
-            );
773
-        }
774
-        unset($properties['_mappings']);
775
-        unset($properties['previous_dms']);
776
-
777
-        foreach ($this->_mappings as $old_table_name => $mapping_to_new_table) {
778
-            foreach ($mapping_to_new_table as $new_table_name => $mapping) {
779
-                $this->_set_mapping_option($old_table_name, $new_table_name, $mapping);
780
-            }
781
-        }
782
-        return $properties;
783
-    }
784
-
785
-
786
-    /**
787
-     * Sets all of the properties of this script stage to match what's in the array, which is assumed
788
-     * to have been made from the properties_as_array() function.
789
-     *
790
-     * @param array $array_of_properties like what's produced from properties_as_array() method
791
-     * @return void
792
-     */
793
-    public function instantiate_from_array_of_properties($array_of_properties)
794
-    {
795
-        $stages_properties_arrays = $array_of_properties['_migration_stages'];
796
-        unset($array_of_properties['_migration_stages']);
797
-        unset($array_of_properties['class']);
798
-        foreach ($array_of_properties as $property_name => $property_value) {
799
-            $this->{$property_name} = $property_value;
800
-        }
801
-        // _migration_stages are already instantiated, but have only default data
802
-        foreach ($this->_migration_stages as $stage) {
803
-            $stage_data = $this->_find_migration_stage_data_with_classname(
804
-                get_class($stage),
805
-                $stages_properties_arrays
806
-            );
807
-            // SO, if we found the stage data that was saved, use it. Otherwise, I guess the stage is new? (maybe added by
808
-            // an addon? Unlikely... not sure why it wouldn't exist, but if it doesn't just treat it like it was never started yet)
809
-            if ($stage_data) {
810
-                $stage->instantiate_from_array_of_properties($stage_data);
811
-            }
812
-        }
813
-    }
814
-
815
-
816
-    /**
817
-     * Gets the migration data from the array $migration_stage_data_arrays (which is an array of arrays, each of which
818
-     * is pretty well identical to EE_Data_Migration_Stage objects except all their properties are array indexes)
819
-     * for the given classname
820
-     *
821
-     * @param string $classname
822
-     * @param array  $migration_stage_data_arrays
823
-     * @return null
824
-     */
825
-    private function _find_migration_stage_data_with_classname($classname, $migration_stage_data_arrays)
826
-    {
827
-        foreach ($migration_stage_data_arrays as $migration_stage_data_array) {
828
-            if (isset($migration_stage_data_array['class']) && $migration_stage_data_array['class'] == $classname) {
829
-                return $migration_stage_data_array;
830
-            }
831
-        }
832
-        return null;
833
-    }
834
-
835
-
836
-    /**
837
-     * Returns the version that this script migrates to, based on the script's name.
838
-     * Cannot be overwritten because lots of code needs to know which version a script
839
-     * migrates to knowing only its name.
840
-     *
841
-     * @return array where the first key is the plugin's slug, the 2nd is the version of that plugin
842
-     * that will be updated to. Eg array('Core','4.1.0')
843
-     */
844
-    final public function migrates_to_version()
845
-    {
846
-        return EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
847
-    }
848
-
849
-
850
-    /**
851
-     * Gets this addon's slug as it would appear in the current_db_state wp option,
852
-     * and if this migration script is for an addon, it SHOULD match the addon's slug
853
-     * (and also the addon's classname, minus the 'EE_' prefix.). Eg, 'Calendar' for the EE_Calendar addon.
854
-     * Or 'Core' for core (non-addon).
855
-     *
856
-     * @return string
857
-     */
858
-    public function slug()
859
-    {
860
-        $migrates_to_version_info = $this->migrates_to_version();
861
-        // the slug is the first part of the array
862
-        return $migrates_to_version_info['slug'];
863
-    }
864
-
865
-
866
-    /**
867
-     * Returns the script's priority relative to DMSs from other addons. However, when
868
-     * two DMSs from the same addon/core apply, this is ignored (and instead the version that
869
-     * the script migrates to is used to determine which to run first). The default is 5, but all core DMSs
870
-     * normally have priority 10. (So if you want a DMS "A" to run before DMS "B", both of which are from addons,
871
-     * and both of which CAN run at the same time (ie, "B" doesn't depend on "A" to set
872
-     * the database up so it can run), then you can set "A" to priority 3 or something.
873
-     *
874
-     * @return int
875
-     */
876
-    public function priority()
877
-    {
878
-        return $this->_priority;
879
-    }
880
-
881
-
882
-    /**
883
-     * Sets whether or not this DMS is being ran as part of a migration, instead of
884
-     * just being used to setup (or verify) the current database structure matches
885
-     * what the latest DMS indicates it should be
886
-     *
887
-     * @param boolean $migrating
888
-     * @return void
889
-     */
890
-    public function set_migrating($migrating = true)
891
-    {
892
-        $this->_migrating = $migrating;
893
-    }
894
-
895
-    /**
896
-     * Marks that we think this migration class can continue to migrate
897
-     */
898
-    public function reattempt()
899
-    {
900
-        parent::reattempt();
901
-        // also, we want to reattempt any stages that were marked as borked
902
-        foreach ($this->stages() as $stage) {
903
-            if ($stage->is_broken()) {
904
-                $stage->reattempt();
905
-            }
906
-        }
907
-    }
18
+	/**
19
+	 * Set by client code to indicate this DMS is being ran as part of a proper migration,
20
+	 * instead of being used to merely setup (or verify) the database structure.
21
+	 * Defaults to TRUE, so client code that's NOT using this DMS as part of a proper migration
22
+	 * should call EE_Data_Migration_Script_Base::set_migrating( FALSE )
23
+	 *
24
+	 * @var boolean
25
+	 */
26
+	protected $_migrating = true;
27
+
28
+	/**
29
+	 * numerically-indexed array where each value is EE_Data_Migration_Script_Stage object
30
+	 *
31
+	 * @var EE_Data_Migration_Script_Stage[] $migration_functions
32
+	 */
33
+	protected $_migration_stages = array();
34
+
35
+	/**
36
+	 * Indicates we've already ran the schema changes that needed to happen BEFORE the data migration
37
+	 *
38
+	 * @var boolean
39
+	 */
40
+	protected $_schema_changes_before_migration_ran = null;
41
+
42
+	/**
43
+	 * Indicates we've already ran the schema changes that needed to happen AFTER the data migration
44
+	 *
45
+	 * @var boolean
46
+	 */
47
+	protected $_schema_changes_after_migration_ran = null;
48
+
49
+	/**
50
+	 * String which describes what's currently happening in this migration
51
+	 *
52
+	 * @var string
53
+	 */
54
+	protected $_feedback_message;
55
+
56
+	/**
57
+	 * Indicates the script's priority. Like wp's add_action and add_filter, lower numbers
58
+	 * correspond to earlier execution
59
+	 *
60
+	 * @var int
61
+	 */
62
+	protected $_priority = 5;
63
+
64
+	/**
65
+	 * Multi-dimensional array that defines the mapping from OLD table Primary Keys
66
+	 * to NEW table Primary Keys.
67
+	 * Top-level array keys are OLD table names (minus the "wp_" part),
68
+	 * 2nd-level array keys are NEW table names (again, minus the "wp_" part),
69
+	 * 3rd-level array keys are the OLD table primary keys
70
+	 * and 3rd-level array values are the NEW table primary keys
71
+	 *
72
+	 * @var array
73
+	 */
74
+	protected $_mappings = array();
75
+
76
+	/**
77
+	 * @var EE_Data_Migration_Script_Base
78
+	 */
79
+	protected $previous_dms;
80
+
81
+
82
+	/**
83
+	 * Returns whether or not this data migration script can operate on the given version of the database.
84
+	 * Eg, if this migration script can migrate from 3.1.26 or higher (but not anything after 4.0.0), and
85
+	 * it's passed a string like '3.1.38B', it should return true.
86
+	 * If this DMS is to migrate data from an EE3 addon, you will probably want to use
87
+	 * EventEspresso\core\services\database\TableAnalysis::tableExists() to check for old EE3 tables, and
88
+	 * EE_Data_Migration_Manager::get_migration_ran() to check that core was already
89
+	 * migrated from EE3 to EE4 (ie, this DMS probably relies on some migration data generated
90
+	 * during the Core 4.1.0 DMS. If core didn't run that DMS, you probably don't want
91
+	 * to run this DMS).
92
+	 * If this DMS migrates data from a previous version of this EE4 addon, just
93
+	 * comparing $current_database_state_of[ $this->slug() ] will probably suffice.
94
+	 * If this DMS should never migrate data, because it's only used to define the initial
95
+	 * database state, just return FALSE (and core's activation process will take care
96
+	 * of calling its schema_changes_before_migration() and
97
+	 * schema_changes_after_migration() for you. )
98
+	 *
99
+	 * @param array $current_database_state_of keys are EE plugin slugs (eg 'Core', 'Calendar', 'Mailchimp', etc)
100
+	 * @return boolean
101
+	 */
102
+	abstract public function can_migrate_from_version($current_database_state_of);
103
+
104
+
105
+	/**
106
+	 * Performs database schema changes that need to occur BEFORE the data is migrated.
107
+	 * Eg, if we were going to change user passwords from plaintext to encoded versions
108
+	 * during this migration, this would probably add a new column called something like
109
+	 * "encoded_password".
110
+	 *
111
+	 * @return boolean of success
112
+	 */
113
+	abstract public function schema_changes_before_migration();
114
+
115
+
116
+	/**
117
+	 * Performs the database schema changes that need to occur AFTER the data has been migrated.
118
+	 * Usually this will mean we'll be removing old columns. Eg, if we were changing passwords
119
+	 * from plaintext to encoded versions, and we had added a column called "encoded_password",
120
+	 * this function would probably remove the old column "password" (which still holds the plaintext password)
121
+	 * and possibly rename "encoded_password" to "password"
122
+	 *
123
+	 * @return boolean of success
124
+	 */
125
+	abstract public function schema_changes_after_migration();
126
+
127
+
128
+	/**
129
+	 * All children of this must call parent::__construct()
130
+	 * at the end of their constructor or suffer the consequences!
131
+	 *
132
+	 * @param TableManager  $table_manager
133
+	 * @param TableAnalysis $table_analysis
134
+	 */
135
+	public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
136
+	{
137
+		$this->_migration_stages = (array) apply_filters(
138
+			'FHEE__' . get_class($this) . '__construct__migration_stages',
139
+			$this->_migration_stages
140
+		);
141
+		foreach ($this->_migration_stages as $migration_stage) {
142
+			if ($migration_stage instanceof EE_Data_Migration_Script_Stage) {
143
+				$migration_stage->_construct_finalize($this);
144
+			}
145
+		}
146
+		parent::__construct($table_manager, $table_analysis);
147
+	}
148
+
149
+
150
+	/**
151
+	 * Place to add hooks and filters for tweaking the migrations page, in order
152
+	 * to customize it
153
+	 */
154
+	public function migration_page_hooks()
155
+	{
156
+		// by default none are added because we normally like the default look of the migration page
157
+	}
158
+
159
+
160
+	/**
161
+	 * Sets the mapping from old table primary keys to new table primary keys.
162
+	 * This mapping is automatically persisted as a property on the migration
163
+	 *
164
+	 * @param string     $old_table with wpdb prefix (wp_). Eg: wp_events_detail
165
+	 * @param int|string $old_pk    old primary key. Eg events_detail.id's value
166
+	 * @param string     $new_table with wpdb prefix (wp_). Eg: wp_posts
167
+	 * @param int|string $new_pk    eg posts.ID
168
+	 * @return void
169
+	 */
170
+	public function set_mapping($old_table, $old_pk, $new_table, $new_pk)
171
+	{
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);
175
+		}
176
+		$this->_mappings[ $old_table ][ $new_table ][ $old_pk ] = $new_pk;
177
+	}
178
+
179
+
180
+	/**
181
+	 * Gets the new primary key, if provided with the OLD table and the primary key
182
+	 * of an item in the old table, and the new table
183
+	 *
184
+	 * @param string     $old_table with wpdb prefix (wp_). Eg: wp_events_detail
185
+	 * @param int|string $old_pk    old primary key. Eg events_detail.id's value
186
+	 * @param string     $new_table with wpdb prefix (wp_). Eg: wp_posts
187
+	 * @return mixed the primary key on the new table
188
+	 */
189
+	public function get_mapping_new_pk($old_table, $old_pk, $new_table)
190
+	{
191
+		if (
192
+			! isset($this->_mappings[ $old_table ]) ||
193
+			! isset($this->_mappings[ $old_table ][ $new_table ])
194
+		) {
195
+			// try fetching the option
196
+			$this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
197
+		}
198
+		return isset($this->_mappings[ $old_table ][ $new_table ][ $old_pk ])
199
+			? $this->_mappings[ $old_table ][ $new_table ][ $old_pk ] : null;
200
+	}
201
+
202
+
203
+	/**
204
+	 * Gets the old primary key, if provided with the OLD table,
205
+	 * and the new table and the primary key of an item in the new table
206
+	 *
207
+	 * @param string $old_table with wpdb prefix (wp_). Eg: wp_events_detail
208
+	 * @param string $new_table with wpdb prefix (wp_). Eg: wp_posts
209
+	 * @param mixed  $new_pk
210
+	 * @return mixed
211
+	 */
212
+	public function get_mapping_old_pk($old_table, $new_table, $new_pk)
213
+	{
214
+		if (
215
+			! isset($this->_mappings[ $old_table ]) ||
216
+			! isset($this->_mappings[ $old_table ][ $new_table ])
217
+		) {
218
+			// try fetching the option
219
+			$this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
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 ];
225
+			}
226
+		}
227
+		return null;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Gets the mapping array option specified by the table names
233
+	 *
234
+	 * @param string $old_table_name
235
+	 * @param string $new_table_name
236
+	 * @return array
237
+	 */
238
+	protected function _get_mapping_option($old_table_name, $new_table_name)
239
+	{
240
+		$option = get_option($this->_get_mapping_option_name($old_table_name, $new_table_name), array());
241
+		return $option;
242
+	}
243
+
244
+
245
+	/**
246
+	 * Updates the mapping option specified by the table names with the array provided
247
+	 *
248
+	 * @param string $old_table_name
249
+	 * @param string $new_table_name
250
+	 * @param array  $mapping_array
251
+	 * @return boolean success of updating option
252
+	 */
253
+	protected function _set_mapping_option($old_table_name, $new_table_name, $mapping_array)
254
+	{
255
+		$success = update_option($this->_get_mapping_option_name($old_table_name, $new_table_name), $mapping_array, false);
256
+		return $success;
257
+	}
258
+
259
+
260
+	/**
261
+	 * Gets the option name for this script to map from $old_table_name to $new_table_name
262
+	 *
263
+	 * @param string $old_table_name
264
+	 * @param string $new_table_name
265
+	 * @return string
266
+	 */
267
+	protected function _get_mapping_option_name($old_table_name, $new_table_name)
268
+	{
269
+		global $wpdb;
270
+		$old_table_name_sans_wp = str_replace($wpdb->prefix, "", $old_table_name);
271
+		$new_table_name_sans_wp = str_replace($wpdb->prefix, "", $new_table_name);
272
+		$migrates_to = EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
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,
275
+			0,
276
+			64
277
+		);
278
+	}
279
+
280
+
281
+	/**
282
+	 * Counts all the records that will be migrated during this data migration.
283
+	 * For example, if we were changing old user passwords from plaintext to encoded versions,
284
+	 * this would be a count of all users who have passwords. If we were going to also split
285
+	 * attendee records into transactions, registrations, and attendee records, this would include
286
+	 * the count of all attendees currently in existence in the DB (ie, users + attendees).
287
+	 * If you can't determine how many records there are to migrate, just provide a guess: this
288
+	 * number will only be used in calculating the percent complete. If you estimate there to be
289
+	 * 100 records to migrate, and it turns out there's 120, we'll just show the migration as being at
290
+	 * 99% until the function "migration_step" returns EE_Data_Migration_Script_Base::status_complete.
291
+	 *
292
+	 * @return int
293
+	 */
294
+	protected function _count_records_to_migrate()
295
+	{
296
+		$count = 0;
297
+		foreach ($this->stages() as $stage) {
298
+			$count += $stage->count_records_to_migrate();
299
+		}
300
+		return $count;
301
+	}
302
+
303
+
304
+	/**
305
+	 * Returns the number of records updated so far. Usually this is easiest to do
306
+	 * by just setting a transient and updating it after each migration_step
307
+	 *
308
+	 * @return int
309
+	 */
310
+	public function count_records_migrated()
311
+	{
312
+		$count = 0;
313
+		foreach ($this->stages() as $stage) {
314
+			$count += $stage->count_records_migrated();
315
+		}
316
+		$this->_records_migrated = $count;
317
+		return $count;
318
+	}
319
+
320
+
321
+	/**
322
+	 * @param int $num_records_to_migrate_limit
323
+	 * @return int
324
+	 * @throws EE_Error
325
+	 * @throws Exception
326
+	 */
327
+	public function migration_step($num_records_to_migrate_limit)
328
+	{
329
+		// reset the feedback message
330
+		$this->_feedback_message = '';
331
+		// if we haven't yet done the 1st schema changes, do them now. buffer any output
332
+		$this->_maybe_do_schema_changes(true);
333
+
334
+		$num_records_actually_migrated = 0;
335
+		$records_migrated_per_stage = array();
336
+		// setup the 'stage' variable, which should hold the last run stage of the migration  (or none at all if nothing runs)
337
+		$stage = null;
338
+		// get the next stage that isn't complete
339
+		foreach ($this->stages() as $stage) {
340
+			if ($stage->get_status() == EE_Data_Migration_Manager::status_continue) {
341
+				try {
342
+					$records_migrated_during_stage = $stage->migration_step(
343
+						$num_records_to_migrate_limit - $num_records_actually_migrated
344
+					);
345
+					$num_records_actually_migrated += $records_migrated_during_stage;
346
+					$records_migrated_per_stage[ $stage->pretty_name() ] = $records_migrated_during_stage;
347
+				} catch (Exception $e) {
348
+					// yes if we catch an exception here, we consider that migration stage borked.
349
+					$stage->set_status(EE_Data_Migration_Manager::status_fatal_error);
350
+					$this->set_status(EE_Data_Migration_Manager::status_fatal_error);
351
+					$stage->add_error($e->getMessage() . ". Stack-trace:" . $e->getTraceAsString());
352
+					throw $e;
353
+				}
354
+				// check that the migration stage didn't mark itself as having a fatal error
355
+				if ($stage->is_broken()) {
356
+					$this->set_broken();
357
+					throw new EE_Error($stage->get_last_error());
358
+				}
359
+			}
360
+			// once we've migrated all the number we intended to (possibly from different stages), stop migrating
361
+			// or if we had a fatal error
362
+			// or if the current script stopped early- its not done, but it's done all it thinks we should do on this step
363
+			if (
364
+				$num_records_actually_migrated >= $num_records_to_migrate_limit
365
+				|| $stage->is_broken()
366
+				|| $stage->has_more_to_do()
367
+			) {
368
+				break;
369
+			}
370
+		}
371
+		// check if we're all done this data migration...
372
+		// which is indicated by being done early AND the last stage claims to be done
373
+		if ($stage == null) {
374
+			// this migration script apparently has NO stages... which is super weird, but whatever
375
+			$this->set_completed();
376
+			$this->_maybe_do_schema_changes(false);
377
+		} elseif ($num_records_actually_migrated < $num_records_to_migrate_limit && ! $stage->has_more_to_do()) {
378
+			// apparently we're done, because we couldn't migrate the number we intended to
379
+			$this->set_completed();
380
+			$this->_update_feedback_message(array_reverse($records_migrated_per_stage));
381
+			// do schema changes for after the migration now
382
+			// first double-check we haven't already done this
383
+			$this->_maybe_do_schema_changes(false);
384
+		} else {
385
+			// update feedback message, keeping in mind that we show them with the most recent at the top
386
+			$this->_update_feedback_message(array_reverse($records_migrated_per_stage));
387
+		}
388
+		return $num_records_actually_migrated;
389
+	}
390
+
391
+
392
+	/**
393
+	 * Updates the feedback message according to what was done during this migration stage.
394
+	 *
395
+	 * @param array $records_migrated_per_stage KEYS are pretty names for each stage; values are the count of records
396
+	 *                                          migrated from that stage
397
+	 * @return void
398
+	 */
399
+	private function _update_feedback_message($records_migrated_per_stage)
400
+	{
401
+		$feedback_message_array = array();
402
+		foreach ($records_migrated_per_stage as $migration_stage_name => $num_records_migrated) {
403
+			$feedback_message_array[] = sprintf(
404
+				esc_html__("Migrated %d records successfully during %s", "event_espresso"),
405
+				$num_records_migrated,
406
+				$migration_stage_name
407
+			);
408
+		}
409
+		$this->_feedback_message .= implode("<br>", $feedback_message_array);
410
+	}
411
+
412
+
413
+	/**
414
+	 * Calls either schema_changes_before_migration() (if $before==true) or schema_changes_after_migration
415
+	 * (if $before==false). Buffers their outputs and stores them on the class.
416
+	 *
417
+	 * @param boolean $before
418
+	 * @throws Exception
419
+	 * @return void
420
+	 */
421
+	private function _maybe_do_schema_changes($before = true)
422
+	{
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}) {
426
+			try {
427
+				ob_start();
428
+				if ($before) {
429
+					$this->schema_changes_before_migration();
430
+				} else {
431
+					$this->schema_changes_after_migration();
432
+				}
433
+				$output = ob_get_contents();
434
+				ob_end_clean();
435
+			} catch (Exception $e) {
436
+				$this->set_status(EE_Data_Migration_Manager::status_fatal_error);
437
+				throw $e;
438
+			}
439
+			// record that we've done these schema changes
440
+			$this->{$property_name} = true;
441
+			// if there were any warnings etc, record them as non-fatal errors
442
+			if ($output) {
443
+				// there were some warnings
444
+				$this->_errors[] = $output;
445
+			}
446
+		}
447
+	}
448
+
449
+
450
+	/**
451
+	 * Wrapper for EEH_Activation::create_table. However, takes into account the request type when
452
+	 * deciding what to pass for its 4th arg, $drop_pre_existing_tables. Using this function, instead
453
+	 * of _table_should_exist_previously, indicates that this table should be new to the EE version being migrated to
454
+	 * or
455
+	 * activated currently. If this is a brand new activation or a migration, and we're indicating this table should
456
+	 * not
457
+	 * previously exist, then we want to set $drop_pre_existing_tables to TRUE (ie, we shouldn't discover that this
458
+	 * table exists in the DB in EEH_Activation::create_table- if it DOES exist, something's wrong and the old table
459
+	 * should be nuked.
460
+	 *
461
+	 * Just for a bit of context, the migration script's db_schema_changes_* methods
462
+	 * are called basically in 3 cases: on brand new activation of EE4 (ie no previous version of EE existed and the
463
+	 * plugin is being activated and we want to add all the brand new tables), upon reactivation of EE4 (it was
464
+	 * deactivated and then reactivated, in which case we want to just verify the DB structure is ok) that table should
465
+	 * be dropped), and during a migration when we're moving the DB to the state of the migration script
466
+	 *
467
+	 * @param string $table_name
468
+	 * @param string $table_definition_sql
469
+	 * @param string $engine_string
470
+	 */
471
+	protected function _table_is_new_in_this_version(
472
+		$table_name,
473
+		$table_definition_sql,
474
+		$engine_string = 'ENGINE=InnoDB '
475
+	) {
476
+		$this->_create_table_and_catch_errors(
477
+			$table_name,
478
+			$table_definition_sql,
479
+			$engine_string,
480
+			$this->_pre_existing_table_should_be_dropped(true)
481
+		);
482
+	}
483
+
484
+	/**
485
+	 * Like _table_is_new_in_this_version and _table_should_exist_previously, this function verifies the given table
486
+	 * exists. But we understand that this table has CHANGED in this version since the previous version. So it's not
487
+	 * completely new, but it's different. So we need to treat it like a new table in terms of verifying it's schema is
488
+	 * correct on activations, migrations, upgrades; but if it exists when it shouldn't, we need to be as lenient as
489
+	 * _table_should_exist_previously.
490
+	 * 8656]{Assumes only this plugin could have added this table (ie, if its a new activation of this plugin, the
491
+	 * table shouldn't exist).
492
+	 *
493
+	 * @param string $table_name
494
+	 * @param string $table_definition_sql
495
+	 * @param string $engine_string
496
+	 */
497
+	protected function _table_is_changed_in_this_version(
498
+		$table_name,
499
+		$table_definition_sql,
500
+		$engine_string = 'ENGINE=MyISAM'
501
+	) {
502
+		$this->_create_table_and_catch_errors(
503
+			$table_name,
504
+			$table_definition_sql,
505
+			$engine_string,
506
+			$this->_pre_existing_table_should_be_dropped(false)
507
+		);
508
+	}
509
+
510
+
511
+	/**
512
+	 * _old_table_exists
513
+	 * returns TRUE if the requested table exists in the current database
514
+	 *
515
+	 * @param string $table_name
516
+	 * @return boolean
517
+	 */
518
+	protected function _old_table_exists($table_name)
519
+	{
520
+		return $this->_get_table_analysis()->tableExists($table_name);
521
+	}
522
+
523
+
524
+	/**
525
+	 * _delete_table_if_empty
526
+	 * returns TRUE if the requested table was empty and successfully empty
527
+	 *
528
+	 * @param string $table_name
529
+	 * @return boolean
530
+	 */
531
+	protected function _delete_table_if_empty($table_name)
532
+	{
533
+		return EEH_Activation::delete_db_table_if_empty($table_name);
534
+	}
535
+
536
+
537
+	/**
538
+	 * It is preferred to use _table_has_not_changed_since_previous or _table_is_changed_in_this_version
539
+	 * as these are significantly more efficient or explicit.
540
+	 * Please see description of _table_is_new_in_this_version. This function will only set
541
+	 * EEH_Activation::create_table's $drop_pre_existing_tables to TRUE if it's a brand
542
+	 * new activation. ie, a more accurate name for this method would be "_table_added_previously_by_this_plugin"
543
+	 * because the table will be cleared out if this is a new activation (ie, if its a new activation, it actually
544
+	 * should exist previously). Otherwise, we'll always set $drop_pre_existing_tables to FALSE because the table
545
+	 * should have existed. Note, if the table is being MODIFIED in this version being activated or migrated to, then
546
+	 * you want _table_is_changed_in_this_version NOT this one. We don't check this table's structure during migrations
547
+	 * because apparently it hasn't changed since the previous one, right?
548
+	 *
549
+	 * @param string $table_name
550
+	 * @param string $table_definition_sql
551
+	 * @param string $engine_string
552
+	 */
553
+	protected function _table_should_exist_previously(
554
+		$table_name,
555
+		$table_definition_sql,
556
+		$engine_string = 'ENGINE=MyISAM'
557
+	) {
558
+		$this->_create_table_and_catch_errors(
559
+			$table_name,
560
+			$table_definition_sql,
561
+			$engine_string,
562
+			$this->_pre_existing_table_should_be_dropped(false)
563
+		);
564
+	}
565
+
566
+	/**
567
+	 * Exactly the same as _table_should_exist_previously(), except if this migration script is currently doing
568
+	 * a migration, we skip checking this table's structure in the database and just assume it's correct.
569
+	 * So this is useful only to improve efficiency when doing migrations (not a big deal for single site installs,
570
+	 * but important for multisite where migrations can take a very long time otherwise).
571
+	 * If the table is known to have changed since previous version, use _table_is_changed_in_this_version().
572
+	 * Assumes only this plugin could have added this table (ie, if its a new activation of this plugin, the table
573
+	 * shouldn't exist).
574
+	 *
575
+	 * @param string $table_name
576
+	 * @param string $table_definition_sql
577
+	 * @param string $engine_string
578
+	 */
579
+	protected function _table_has_not_changed_since_previous(
580
+		$table_name,
581
+		$table_definition_sql,
582
+		$engine_string = 'ENGINE=MyISAM'
583
+	) {
584
+		if ($this->_currently_migrating()) {
585
+			// if we're doing a migration, and this table apparently already exists, then we don't need do anything right?
586
+			return;
587
+		}
588
+		$this->_create_table_and_catch_errors(
589
+			$table_name,
590
+			$table_definition_sql,
591
+			$engine_string,
592
+			$this->_pre_existing_table_should_be_dropped(false)
593
+		);
594
+	}
595
+
596
+	/**
597
+	 * Returns whether or not this migration script is being used as part of an actual migration
598
+	 *
599
+	 * @return boolean
600
+	 */
601
+	protected function _currently_migrating()
602
+	{
603
+		// 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)
604
+		return $this->_migrating &&
605
+			   $this->can_migrate_from_version(
606
+				   EE_Data_Migration_Manager::instance()->ensure_current_database_state_is_set()
607
+			   ) &&
608
+			   EE_Maintenance_Mode::instance()->real_level() == EE_Maintenance_Mode::level_2_complete_maintenance;
609
+	}
610
+
611
+	/**
612
+	 * Determines if a table should be dropped, based on whether it's reported to be new in $table_is_new,
613
+	 * and the plugin's request type.
614
+	 * Assumes only this plugin could have added the table (ie, if its a new activation of this plugin, the table
615
+	 * shouldn't exist no matter what).
616
+	 *
617
+	 * @param boolean $table_is_new
618
+	 * @return boolean
619
+	 */
620
+	protected function _pre_existing_table_should_be_dropped($table_is_new)
621
+	{
622
+		if ($table_is_new) {
623
+			if (
624
+				$this->_get_req_type_for_plugin_corresponding_to_this_dms() == EE_System::req_type_new_activation
625
+				|| $this->_currently_migrating()
626
+			) {
627
+				return true;
628
+			} else {
629
+				return false;
630
+			}
631
+		} else {
632
+			if (
633
+				in_array(
634
+					$this->_get_req_type_for_plugin_corresponding_to_this_dms(),
635
+					array(EE_System::req_type_new_activation)
636
+				)
637
+			) {
638
+				return true;
639
+			} else {
640
+				return false;
641
+			}
642
+		}
643
+	}
644
+
645
+	/**
646
+	 * Just wraps EEH_Activation::create_table, but catches any errors it may throw and adds them as errors on the DMS
647
+	 *
648
+	 * @param string  $table_name
649
+	 * @param string  $table_definition_sql
650
+	 * @param string  $engine_string
651
+	 * @param boolean $drop_pre_existing_tables
652
+	 */
653
+	private function _create_table_and_catch_errors(
654
+		$table_name,
655
+		$table_definition_sql,
656
+		$engine_string = 'ENGINE=MyISAM',
657
+		$drop_pre_existing_tables = false
658
+	) {
659
+		try {
660
+			EEH_Activation::create_table($table_name, $table_definition_sql, $engine_string, $drop_pre_existing_tables);
661
+		} catch (EE_Error $e) {
662
+			$message = $e->getMessage() . '<br>Stack Trace:' . $e->getTraceAsString();
663
+			$this->add_error($message);
664
+			$this->_feedback_message .= $message;
665
+		}
666
+	}
667
+
668
+
669
+	/**
670
+	 * Gets the request type for the plugin (core or addon) that corresponds to this DMS
671
+	 *
672
+	 * @return int one of EE_System::_req_type_* constants
673
+	 * @throws EE_Error
674
+	 */
675
+	private function _get_req_type_for_plugin_corresponding_to_this_dms()
676
+	{
677
+		if ($this->slug() == 'Core') {
678
+			return EE_System::instance()->detect_req_type();
679
+		} else {// it must be for an addon
680
+			$addon_name = $this->slug();
681
+			if (EE_Registry::instance()->get_addon_by_name($addon_name)) {
682
+				return EE_Registry::instance()->get_addon_by_name($addon_name)->detect_req_type();
683
+			} else {
684
+				throw new EE_Error(
685
+					sprintf(
686
+						esc_html__(
687
+							"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",
688
+							"event_espresso"
689
+						),
690
+						$this->slug(),
691
+						$addon_name,
692
+						implode(",", array_keys(EE_Registry::instance()->get_addons_by_name()))
693
+					)
694
+				);
695
+			}
696
+		}
697
+	}
698
+
699
+
700
+	/**
701
+	 * returns an array of strings describing errors by all the script's stages
702
+	 *
703
+	 * @return array
704
+	 */
705
+	public function get_errors()
706
+	{
707
+		$all_errors = $this->_errors;
708
+		if (! is_array($all_errors)) {
709
+			$all_errors = array();
710
+		}
711
+		foreach ($this->stages() as $stage) {
712
+			$all_errors = array_merge($stage->get_errors(), $all_errors);
713
+		}
714
+		return $all_errors;
715
+	}
716
+
717
+
718
+	/**
719
+	 * Indicates whether or not this migration script should continue
720
+	 *
721
+	 * @return boolean
722
+	 */
723
+	public function can_continue()
724
+	{
725
+		return in_array(
726
+			$this->get_status(),
727
+			EE_Data_Migration_Manager::instance()->stati_that_indicate_to_continue_single_migration_script
728
+		);
729
+	}
730
+
731
+
732
+	/**
733
+	 * Gets all the data migration stages associated with this script. Note:
734
+	 * addons can filter this list to add their own stages, and because the list is
735
+	 * numerically-indexed, they can insert their stage wherever they like and it will
736
+	 * get ordered by the indexes
737
+	 *
738
+	 * @return EE_Data_Migration_Script_Stage[]
739
+	 */
740
+	protected function stages()
741
+	{
742
+		$stages = apply_filters('FHEE__' . get_class($this) . '__stages', $this->_migration_stages);
743
+		ksort($stages);
744
+		return $stages;
745
+	}
746
+
747
+
748
+	/**
749
+	 * Gets a string which should describe what's going on currently with this migration, which
750
+	 * can be displayed to the user
751
+	 *
752
+	 * @return string
753
+	 */
754
+	public function get_feedback_message()
755
+	{
756
+		return $this->_feedback_message;
757
+	}
758
+
759
+
760
+	/**
761
+	 * A lot like "__sleep()" magic method in purpose, this is meant for persisting this class'
762
+	 * properties to the DB. However, we don't want to use __sleep() because its quite
763
+	 * possible that this class is defined when it goes to sleep, but NOT available when it
764
+	 * awakes (eg, this class is part of an addon that is deactivated at some point).
765
+	 */
766
+	public function properties_as_array()
767
+	{
768
+		$properties = parent::properties_as_array();
769
+		$properties['_migration_stages'] = array();
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(
772
+			);
773
+		}
774
+		unset($properties['_mappings']);
775
+		unset($properties['previous_dms']);
776
+
777
+		foreach ($this->_mappings as $old_table_name => $mapping_to_new_table) {
778
+			foreach ($mapping_to_new_table as $new_table_name => $mapping) {
779
+				$this->_set_mapping_option($old_table_name, $new_table_name, $mapping);
780
+			}
781
+		}
782
+		return $properties;
783
+	}
784
+
785
+
786
+	/**
787
+	 * Sets all of the properties of this script stage to match what's in the array, which is assumed
788
+	 * to have been made from the properties_as_array() function.
789
+	 *
790
+	 * @param array $array_of_properties like what's produced from properties_as_array() method
791
+	 * @return void
792
+	 */
793
+	public function instantiate_from_array_of_properties($array_of_properties)
794
+	{
795
+		$stages_properties_arrays = $array_of_properties['_migration_stages'];
796
+		unset($array_of_properties['_migration_stages']);
797
+		unset($array_of_properties['class']);
798
+		foreach ($array_of_properties as $property_name => $property_value) {
799
+			$this->{$property_name} = $property_value;
800
+		}
801
+		// _migration_stages are already instantiated, but have only default data
802
+		foreach ($this->_migration_stages as $stage) {
803
+			$stage_data = $this->_find_migration_stage_data_with_classname(
804
+				get_class($stage),
805
+				$stages_properties_arrays
806
+			);
807
+			// SO, if we found the stage data that was saved, use it. Otherwise, I guess the stage is new? (maybe added by
808
+			// an addon? Unlikely... not sure why it wouldn't exist, but if it doesn't just treat it like it was never started yet)
809
+			if ($stage_data) {
810
+				$stage->instantiate_from_array_of_properties($stage_data);
811
+			}
812
+		}
813
+	}
814
+
815
+
816
+	/**
817
+	 * Gets the migration data from the array $migration_stage_data_arrays (which is an array of arrays, each of which
818
+	 * is pretty well identical to EE_Data_Migration_Stage objects except all their properties are array indexes)
819
+	 * for the given classname
820
+	 *
821
+	 * @param string $classname
822
+	 * @param array  $migration_stage_data_arrays
823
+	 * @return null
824
+	 */
825
+	private function _find_migration_stage_data_with_classname($classname, $migration_stage_data_arrays)
826
+	{
827
+		foreach ($migration_stage_data_arrays as $migration_stage_data_array) {
828
+			if (isset($migration_stage_data_array['class']) && $migration_stage_data_array['class'] == $classname) {
829
+				return $migration_stage_data_array;
830
+			}
831
+		}
832
+		return null;
833
+	}
834
+
835
+
836
+	/**
837
+	 * Returns the version that this script migrates to, based on the script's name.
838
+	 * Cannot be overwritten because lots of code needs to know which version a script
839
+	 * migrates to knowing only its name.
840
+	 *
841
+	 * @return array where the first key is the plugin's slug, the 2nd is the version of that plugin
842
+	 * that will be updated to. Eg array('Core','4.1.0')
843
+	 */
844
+	final public function migrates_to_version()
845
+	{
846
+		return EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
847
+	}
848
+
849
+
850
+	/**
851
+	 * Gets this addon's slug as it would appear in the current_db_state wp option,
852
+	 * and if this migration script is for an addon, it SHOULD match the addon's slug
853
+	 * (and also the addon's classname, minus the 'EE_' prefix.). Eg, 'Calendar' for the EE_Calendar addon.
854
+	 * Or 'Core' for core (non-addon).
855
+	 *
856
+	 * @return string
857
+	 */
858
+	public function slug()
859
+	{
860
+		$migrates_to_version_info = $this->migrates_to_version();
861
+		// the slug is the first part of the array
862
+		return $migrates_to_version_info['slug'];
863
+	}
864
+
865
+
866
+	/**
867
+	 * Returns the script's priority relative to DMSs from other addons. However, when
868
+	 * two DMSs from the same addon/core apply, this is ignored (and instead the version that
869
+	 * the script migrates to is used to determine which to run first). The default is 5, but all core DMSs
870
+	 * normally have priority 10. (So if you want a DMS "A" to run before DMS "B", both of which are from addons,
871
+	 * and both of which CAN run at the same time (ie, "B" doesn't depend on "A" to set
872
+	 * the database up so it can run), then you can set "A" to priority 3 or something.
873
+	 *
874
+	 * @return int
875
+	 */
876
+	public function priority()
877
+	{
878
+		return $this->_priority;
879
+	}
880
+
881
+
882
+	/**
883
+	 * Sets whether or not this DMS is being ran as part of a migration, instead of
884
+	 * just being used to setup (or verify) the current database structure matches
885
+	 * what the latest DMS indicates it should be
886
+	 *
887
+	 * @param boolean $migrating
888
+	 * @return void
889
+	 */
890
+	public function set_migrating($migrating = true)
891
+	{
892
+		$this->_migrating = $migrating;
893
+	}
894
+
895
+	/**
896
+	 * Marks that we think this migration class can continue to migrate
897
+	 */
898
+	public function reattempt()
899
+	{
900
+		parent::reattempt();
901
+		// also, we want to reattempt any stages that were marked as borked
902
+		foreach ($this->stages() as $stage) {
903
+			if ($stage->is_broken()) {
904
+				$stage->reattempt();
905
+			}
906
+		}
907
+	}
908 908
 }
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
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);
@@ -34,68 +34,68 @@  discard block
 block discarded – undo
34 34
 class EE_DMS_Core_4_9_0 extends EE_Data_Migration_Script_Base
35 35
 {
36 36
 
37
-    /**
38
-     * return EE_DMS_Core_4_9_0
39
-     *
40
-     * @param TableManager  $table_manager
41
-     * @param TableAnalysis $table_analysis
42
-     */
43
-    public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
44
-    {
45
-        $this->_pretty_name = esc_html__("Data Update to Event Espresso 4.9.0", "event_espresso");
46
-        $this->_priority = 10;
47
-        $this->_migration_stages = array(
48
-            new EE_DMS_4_9_0_Email_System_Question(),
49
-            new EE_DMS_4_9_0_Answers_With_No_Registration(),
50
-        );
51
-        parent::__construct($table_manager, $table_analysis);
52
-    }
37
+	/**
38
+	 * return EE_DMS_Core_4_9_0
39
+	 *
40
+	 * @param TableManager  $table_manager
41
+	 * @param TableAnalysis $table_analysis
42
+	 */
43
+	public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
44
+	{
45
+		$this->_pretty_name = esc_html__("Data Update to Event Espresso 4.9.0", "event_espresso");
46
+		$this->_priority = 10;
47
+		$this->_migration_stages = array(
48
+			new EE_DMS_4_9_0_Email_System_Question(),
49
+			new EE_DMS_4_9_0_Answers_With_No_Registration(),
50
+		);
51
+		parent::__construct($table_manager, $table_analysis);
52
+	}
53 53
 
54 54
 
55 55
 
56
-    /**
57
-     * Whether to migrate or not.
58
-     *
59
-     * @param array $version_array
60
-     * @return bool
61
-     */
62
-    public function can_migrate_from_version($version_array)
63
-    {
64
-        $version_string = $version_array['Core'];
65
-        if (version_compare($version_string, '4.9.0.decaf', '<') && version_compare($version_string, '4.8.0.decaf', '>=')) {
66
-            //          echo "$version_string can be migrated from";
67
-            return true;
68
-        } elseif (! $version_string) {
69
-            //          echo "no version string provided: $version_string";
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
72
-        } else {
73
-            //          echo "$version_string doesnt apply";
74
-            return false;
75
-        }
76
-    }
56
+	/**
57
+	 * Whether to migrate or not.
58
+	 *
59
+	 * @param array $version_array
60
+	 * @return bool
61
+	 */
62
+	public function can_migrate_from_version($version_array)
63
+	{
64
+		$version_string = $version_array['Core'];
65
+		if (version_compare($version_string, '4.9.0.decaf', '<') && version_compare($version_string, '4.8.0.decaf', '>=')) {
66
+			//          echo "$version_string can be migrated from";
67
+			return true;
68
+		} elseif (! $version_string) {
69
+			//          echo "no version string provided: $version_string";
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
72
+		} else {
73
+			//          echo "$version_string doesnt apply";
74
+			return false;
75
+		}
76
+	}
77 77
 
78 78
 
79 79
 
80
-    /**
81
-     * @return bool
82
-     */
83
-    public function schema_changes_before_migration()
84
-    {
85
-        require_once(EE_HELPERS . 'EEH_Activation.helper.php');
86
-        $now_in_mysql = current_time('mysql', true);
87
-        $table_name = 'esp_answer';
88
-        $sql = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
80
+	/**
81
+	 * @return bool
82
+	 */
83
+	public function schema_changes_before_migration()
84
+	{
85
+		require_once(EE_HELPERS . 'EEH_Activation.helper.php');
86
+		$now_in_mysql = current_time('mysql', true);
87
+		$table_name = 'esp_answer';
88
+		$sql = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
89 89
 					REG_ID int(10) unsigned NOT NULL,
90 90
 					QST_ID int(10) unsigned NOT NULL,
91 91
 					ANS_value text NOT NULL,
92 92
 					PRIMARY KEY  (ANS_ID),
93 93
 					KEY REG_ID (REG_ID),
94 94
 					KEY QST_ID (QST_ID)";
95
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
96
-        $table_name = 'esp_attendee_meta';
97
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'ATT_email');
98
-        $sql = "ATTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
95
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
96
+		$table_name = 'esp_attendee_meta';
97
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'ATT_email');
98
+		$sql = "ATTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
99 99
 				ATT_ID bigint(20) unsigned NOT NULL,
100 100
 				ATT_fname varchar(45) NOT NULL,
101 101
 				ATT_lname varchar(45) NOT NULL,
@@ -112,9 +112,9 @@  discard block
 block discarded – undo
112 112
 				KEY ATT_email (ATT_email(191)),
113 113
 				KEY ATT_lname (ATT_lname),
114 114
 				KEY ATT_fname (ATT_fname)";
115
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
116
-        $table_name = 'esp_checkin';
117
-        $sql = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
115
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
116
+		$table_name = 'esp_checkin';
117
+		$sql = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
118 118
 				REG_ID int(10) unsigned NOT NULL,
119 119
 				DTT_ID int(10) unsigned NOT NULL,
120 120
 				CHK_in tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -122,9 +122,9 @@  discard block
 block discarded – undo
122 122
 				PRIMARY KEY  (CHK_ID),
123 123
 				KEY REG_ID (REG_ID),
124 124
 				KEY DTT_ID (DTT_ID)";
125
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
126
-        $table_name = 'esp_country';
127
-        $sql = "CNT_ISO varchar(2) NOT NULL,
125
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
126
+		$table_name = 'esp_country';
127
+		$sql = "CNT_ISO varchar(2) NOT NULL,
128 128
 				CNT_ISO3 varchar(3) NOT NULL,
129 129
 				RGN_ID tinyint(3) unsigned DEFAULT NULL,
130 130
 				CNT_name varchar(45) NOT NULL,
@@ -140,29 +140,29 @@  discard block
 block discarded – undo
140 140
 				CNT_is_EU tinyint(1) DEFAULT '0',
141 141
 				CNT_active tinyint(1) DEFAULT '0',
142 142
 				PRIMARY KEY  (CNT_ISO)";
143
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
144
-        $table_name = 'esp_currency';
145
-        $sql = "CUR_code varchar(6) NOT NULL,
143
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
144
+		$table_name = 'esp_currency';
145
+		$sql = "CUR_code varchar(6) NOT NULL,
146 146
 				CUR_single varchar(45) DEFAULT 'dollar',
147 147
 				CUR_plural varchar(45) DEFAULT 'dollars',
148 148
 				CUR_sign varchar(45) DEFAULT '$',
149 149
 				CUR_dec_plc varchar(1) NOT NULL DEFAULT '2',
150 150
 				CUR_active tinyint(1) DEFAULT '0',
151 151
 				PRIMARY KEY  (CUR_code)";
152
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
153
-        // note: although this table is no longer in use,
154
-        // it hasn't been removed because then queries to the model will have errors.
155
-        // but you should expect this table and its corresponding model to be removed in
156
-        // the next few months
157
-        $table_name = 'esp_currency_payment_method';
158
-        $sql = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
152
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
153
+		// note: although this table is no longer in use,
154
+		// it hasn't been removed because then queries to the model will have errors.
155
+		// but you should expect this table and its corresponding model to be removed in
156
+		// the next few months
157
+		$table_name = 'esp_currency_payment_method';
158
+		$sql = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
159 159
 				CUR_code varchar(6) NOT NULL,
160 160
 				PMD_ID int(11) NOT NULL,
161 161
 				PRIMARY KEY  (CPM_ID),
162 162
 				KEY PMD_ID (PMD_ID)";
163
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
164
-        $table_name = 'esp_datetime';
165
-        $sql = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
163
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
164
+		$table_name = 'esp_datetime';
165
+		$sql = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
166 166
 				EVT_ID bigint(20) unsigned NOT NULL,
167 167
 				DTT_name varchar(255) NOT NULL DEFAULT '',
168 168
 				DTT_description text NOT NULL,
@@ -179,25 +179,25 @@  discard block
 block discarded – undo
179 179
 				KEY DTT_EVT_start (DTT_EVT_start),
180 180
 				KEY EVT_ID (EVT_ID),
181 181
 				KEY DTT_is_primary (DTT_is_primary)";
182
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
183
-        $table_name = "esp_datetime_ticket";
184
-        $sql = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
182
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
183
+		$table_name = "esp_datetime_ticket";
184
+		$sql = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
185 185
 				DTT_ID int(10) unsigned NOT NULL,
186 186
 				TKT_ID int(10) unsigned NOT NULL,
187 187
 				PRIMARY KEY  (DTK_ID),
188 188
 				KEY DTT_ID (DTT_ID),
189 189
 				KEY TKT_ID (TKT_ID)";
190
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
191
-        $table_name = 'esp_event_message_template';
192
-        $sql = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
190
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
191
+		$table_name = 'esp_event_message_template';
192
+		$sql = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
193 193
 				EVT_ID bigint(20) unsigned NOT NULL DEFAULT 0,
194 194
 				GRP_ID int(10) unsigned NOT NULL DEFAULT 0,
195 195
 				PRIMARY KEY  (EMT_ID),
196 196
 				KEY EVT_ID (EVT_ID),
197 197
 				KEY GRP_ID (GRP_ID)";
198
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
199
-        $table_name = 'esp_event_meta';
200
-        $sql = "EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
198
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
199
+		$table_name = 'esp_event_meta';
200
+		$sql = "EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
201 201
 				EVT_ID bigint(20) unsigned NOT NULL,
202 202
 				EVT_display_desc tinyint(1) unsigned NOT NULL DEFAULT 1,
203 203
 				EVT_display_ticket_selector tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -212,34 +212,34 @@  discard block
 block discarded – undo
212 212
 				EVT_donations tinyint(1) NULL,
213 213
 				PRIMARY KEY  (EVTM_ID),
214 214
 				KEY EVT_ID (EVT_ID)";
215
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
216
-        $table_name = 'esp_event_question_group';
217
-        $sql = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
215
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
216
+		$table_name = 'esp_event_question_group';
217
+		$sql = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
218 218
 				EVT_ID bigint(20) unsigned NOT NULL,
219 219
 				QSG_ID int(10) unsigned NOT NULL,
220 220
 				EQG_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
221 221
 				PRIMARY KEY  (EQG_ID),
222 222
 				KEY EVT_ID (EVT_ID),
223 223
 				KEY QSG_ID (QSG_ID)";
224
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
225
-        $table_name = 'esp_event_venue';
226
-        $sql = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
224
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
225
+		$table_name = 'esp_event_venue';
226
+		$sql = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
227 227
 				EVT_ID bigint(20) unsigned NOT NULL,
228 228
 				VNU_ID bigint(20) unsigned NOT NULL,
229 229
 				EVV_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
230 230
 				PRIMARY KEY  (EVV_ID)";
231
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
232
-        $table_name = 'esp_extra_meta';
233
-        $sql = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
231
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
232
+		$table_name = 'esp_extra_meta';
233
+		$sql = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
234 234
 				OBJ_ID int(11) DEFAULT NULL,
235 235
 				EXM_type varchar(45) DEFAULT NULL,
236 236
 				EXM_key varchar(45) DEFAULT NULL,
237 237
 				EXM_value text,
238 238
 				PRIMARY KEY  (EXM_ID),
239 239
 				KEY EXM_type (EXM_type,OBJ_ID,EXM_key)";
240
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
241
-        $table_name = 'esp_extra_join';
242
-        $sql = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
240
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
241
+		$table_name = 'esp_extra_join';
242
+		$sql = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
243 243
 				EXJ_first_model_id varchar(6) NOT NULL,
244 244
 				EXJ_first_model_name varchar(20) NOT NULL,
245 245
 				EXJ_second_model_id varchar(6) NOT NULL,
@@ -247,9 +247,9 @@  discard block
 block discarded – undo
247 247
 				PRIMARY KEY  (EXJ_ID),
248 248
 				KEY first_model (EXJ_first_model_name,EXJ_first_model_id),
249 249
 				KEY second_model (EXJ_second_model_name,EXJ_second_model_id)";
250
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
251
-        $table_name = 'esp_line_item';
252
-        $sql = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
250
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
251
+		$table_name = 'esp_line_item';
252
+		$sql = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
253 253
 				LIN_code varchar(245) NOT NULL DEFAULT '',
254 254
 				TXN_ID int(11) DEFAULT NULL,
255 255
 				LIN_name varchar(245) NOT NULL DEFAULT '',
@@ -270,11 +270,11 @@  discard block
 block discarded – undo
270 270
 				KEY txn_type_timestamp (TXN_ID,LIN_type,LIN_timestamp),
271 271
 				KEY txn_obj_id_obj_type (TXN_ID,OBJ_ID,OBJ_type),
272 272
 				KEY obj_id_obj_type (OBJ_ID,OBJ_type)";
273
-        $this->_get_table_manager()->dropIndex('esp_line_item', 'TXN_ID');
274
-        $this->_get_table_manager()->dropIndex('esp_line_item', 'LIN_code');
275
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
276
-        $table_name = 'esp_log';
277
-        $sql = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
273
+		$this->_get_table_manager()->dropIndex('esp_line_item', 'TXN_ID');
274
+		$this->_get_table_manager()->dropIndex('esp_line_item', 'LIN_code');
275
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
276
+		$table_name = 'esp_log';
277
+		$sql = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
278 278
 				LOG_time datetime DEFAULT NULL,
279 279
 				OBJ_ID varchar(45) DEFAULT NULL,
280 280
 				OBJ_type varchar(45) DEFAULT NULL,
@@ -285,12 +285,12 @@  discard block
 block discarded – undo
285 285
 				KEY LOG_time (LOG_time),
286 286
 				KEY OBJ (OBJ_type,OBJ_ID),
287 287
 				KEY LOG_type (LOG_type)";
288
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
289
-        $table_name = 'esp_message';
290
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_to');
291
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_from');
292
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_subject');
293
-        $sql = "MSG_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
288
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
289
+		$table_name = 'esp_message';
290
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_to');
291
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_from');
292
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_subject');
293
+		$sql = "MSG_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
294 294
 				GRP_ID int(10) unsigned NULL,
295 295
 				MSG_token varchar(255) NULL,
296 296
 				TXN_ID int(10) unsigned NULL,
@@ -322,18 +322,18 @@  discard block
 block discarded – undo
322 322
 				KEY STS_ID (STS_ID),
323 323
 				KEY MSG_created (MSG_created),
324 324
 				KEY MSG_modified (MSG_modified)";
325
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
326
-        $table_name = 'esp_message_template';
327
-        $sql = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
325
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
326
+		$table_name = 'esp_message_template';
327
+		$sql = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
328 328
 				GRP_ID int(10) unsigned NOT NULL,
329 329
 				MTP_context varchar(50) NOT NULL,
330 330
 				MTP_template_field varchar(30) NOT NULL,
331 331
 				MTP_content text NOT NULL,
332 332
 				PRIMARY KEY  (MTP_ID),
333 333
 				KEY GRP_ID (GRP_ID)";
334
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
335
-        $table_name = 'esp_message_template_group';
336
-        $sql = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
334
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
335
+		$table_name = 'esp_message_template_group';
336
+		$sql = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
337 337
 				MTP_user_id int(10) NOT NULL DEFAULT '1',
338 338
 				MTP_name varchar(245) NOT NULL DEFAULT '',
339 339
 				MTP_description varchar(245) NOT NULL DEFAULT '',
@@ -345,9 +345,9 @@  discard block
 block discarded – undo
345 345
 				MTP_is_active tinyint(1) NOT NULL DEFAULT '1',
346 346
 				PRIMARY KEY  (GRP_ID),
347 347
 				KEY MTP_user_id (MTP_user_id)";
348
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
349
-        $table_name = 'esp_payment';
350
-        $sql = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
348
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
349
+		$table_name = 'esp_payment';
350
+		$sql = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
351 351
 				TXN_ID int(10) unsigned DEFAULT NULL,
352 352
 				STS_ID varchar(3) DEFAULT NULL,
353 353
 				PAY_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -364,9 +364,9 @@  discard block
 block discarded – undo
364 364
 				PRIMARY KEY  (PAY_ID),
365 365
 				KEY PAY_timestamp (PAY_timestamp),
366 366
 				KEY TXN_ID (TXN_ID)";
367
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
368
-        $table_name = 'esp_payment_method';
369
-        $sql = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
367
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
368
+		$table_name = 'esp_payment_method';
369
+		$sql = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
370 370
 				PMD_type varchar(124) DEFAULT NULL,
371 371
 				PMD_name varchar(255) DEFAULT NULL,
372 372
 				PMD_desc text,
@@ -382,24 +382,24 @@  discard block
 block discarded – undo
382 382
 				PRIMARY KEY  (PMD_ID),
383 383
 				UNIQUE KEY PMD_slug_UNIQUE (PMD_slug),
384 384
 				KEY PMD_type (PMD_type)";
385
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
386
-        $table_name = "esp_ticket_price";
387
-        $sql = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
385
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
386
+		$table_name = "esp_ticket_price";
387
+		$sql = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
388 388
 				TKT_ID int(10) unsigned NOT NULL,
389 389
 				PRC_ID int(10) unsigned NOT NULL,
390 390
 				PRIMARY KEY  (TKP_ID),
391 391
 				KEY TKT_ID (TKT_ID),
392 392
 				KEY PRC_ID (PRC_ID)";
393
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
394
-        $table_name = "esp_ticket_template";
395
-        $sql = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
393
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
394
+		$table_name = "esp_ticket_template";
395
+		$sql = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
396 396
 				TTM_name varchar(45) NOT NULL,
397 397
 				TTM_description text,
398 398
 				TTM_file varchar(45),
399 399
 				PRIMARY KEY  (TTM_ID)";
400
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
401
-        $table_name = 'esp_question';
402
-        $sql = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
400
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
401
+		$table_name = 'esp_question';
402
+		$sql = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
403 403
 				QST_display_text text NOT NULL,
404 404
 				QST_admin_label varchar(255) NOT NULL,
405 405
 				QST_system varchar(25) DEFAULT NULL,
@@ -413,18 +413,18 @@  discard block
 block discarded – undo
413 413
 				QST_deleted tinyint(2) unsigned NOT NULL DEFAULT 0,
414 414
 				PRIMARY KEY  (QST_ID),
415 415
 				KEY QST_order (QST_order)';
416
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
417
-        $table_name = 'esp_question_group_question';
418
-        $sql = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
416
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
417
+		$table_name = 'esp_question_group_question';
418
+		$sql = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
419 419
 				QSG_ID int(10) unsigned NOT NULL,
420 420
 				QST_ID int(10) unsigned NOT NULL,
421 421
 				QGQ_order int(10) unsigned NOT NULL DEFAULT 0,
422 422
 				PRIMARY KEY  (QGQ_ID),
423 423
 				KEY QST_ID (QST_ID),
424 424
 				KEY QSG_ID_order (QSG_ID,QGQ_order)";
425
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
426
-        $table_name = 'esp_question_option';
427
-        $sql = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
425
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
426
+		$table_name = 'esp_question_option';
427
+		$sql = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
428 428
 				QSO_value varchar(255) NOT NULL,
429 429
 				QSO_desc text NOT NULL,
430 430
 				QST_ID int(10) unsigned NOT NULL,
@@ -434,9 +434,9 @@  discard block
 block discarded – undo
434 434
 				PRIMARY KEY  (QSO_ID),
435 435
 				KEY QST_ID (QST_ID),
436 436
 				KEY QSO_order (QSO_order)";
437
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
438
-        $table_name = 'esp_registration';
439
-        $sql = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
437
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
438
+		$table_name = 'esp_registration';
439
+		$sql = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
440 440
 				EVT_ID bigint(20) unsigned NOT NULL,
441 441
 				ATT_ID bigint(20) unsigned NOT NULL,
442 442
 				TXN_ID int(10) unsigned NOT NULL,
@@ -460,18 +460,18 @@  discard block
 block discarded – undo
460 460
 				KEY TKT_ID (TKT_ID),
461 461
 				KEY EVT_ID (EVT_ID),
462 462
 				KEY STS_ID (STS_ID)";
463
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
464
-        $table_name = 'esp_registration_payment';
465
-        $sql = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
463
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
464
+		$table_name = 'esp_registration_payment';
465
+		$sql = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
466 466
 					  REG_ID int(10) unsigned NOT NULL,
467 467
 					  PAY_ID int(10) unsigned NULL,
468 468
 					  RPY_amount decimal(12,3) NOT NULL DEFAULT '0.00',
469 469
 					  PRIMARY KEY  (RPY_ID),
470 470
 					  KEY REG_ID (REG_ID),
471 471
 					  KEY PAY_ID (PAY_ID)";
472
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
473
-        $table_name = 'esp_state';
474
-        $sql = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
472
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
473
+		$table_name = 'esp_state';
474
+		$sql = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
475 475
 				CNT_ISO varchar(2) NOT NULL,
476 476
 				STA_abbrev varchar(24) NOT NULL,
477 477
 				STA_name varchar(100) NOT NULL,
@@ -479,9 +479,9 @@  discard block
 block discarded – undo
479 479
 				PRIMARY KEY  (STA_ID),
480 480
 				KEY STA_abbrev (STA_abbrev),
481 481
 				KEY CNT_ISO (CNT_ISO)";
482
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
483
-        $table_name = 'esp_status';
484
-        $sql = "STS_ID varchar(3) NOT NULL,
482
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
483
+		$table_name = 'esp_status';
484
+		$sql = "STS_ID varchar(3) NOT NULL,
485 485
 				STS_code varchar(45) NOT NULL,
486 486
 				STS_type varchar(45) NOT NULL,
487 487
 				STS_can_edit tinyint(1) NOT NULL DEFAULT 0,
@@ -489,9 +489,9 @@  discard block
 block discarded – undo
489 489
 				STS_open tinyint(1) NOT NULL DEFAULT 1,
490 490
 				UNIQUE KEY STS_ID_UNIQUE (STS_ID),
491 491
 				KEY STS_type (STS_type)";
492
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
493
-        $table_name = 'esp_transaction';
494
-        $sql = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
492
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
493
+		$table_name = 'esp_transaction';
494
+		$sql = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
495 495
 				TXN_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
496 496
 				TXN_total decimal(12,3) DEFAULT '0.00',
497 497
 				TXN_paid decimal(12,3) NOT NULL DEFAULT '0.00',
@@ -503,9 +503,9 @@  discard block
 block discarded – undo
503 503
 				PRIMARY KEY  (TXN_ID),
504 504
 				KEY TXN_timestamp (TXN_timestamp),
505 505
 				KEY STS_ID (STS_ID)";
506
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
507
-        $table_name = 'esp_venue_meta';
508
-        $sql = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
506
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
507
+		$table_name = 'esp_venue_meta';
508
+		$sql = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
509 509
 			VNU_ID bigint(20) unsigned NOT NULL DEFAULT 0,
510 510
 			VNU_address varchar(255) DEFAULT NULL,
511 511
 			VNU_address2 varchar(255) DEFAULT NULL,
@@ -524,10 +524,10 @@  discard block
 block discarded – undo
524 524
 			KEY VNU_ID (VNU_ID),
525 525
 			KEY STA_ID (STA_ID),
526 526
 			KEY CNT_ISO (CNT_ISO)";
527
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
528
-        // modified tables
529
-        $table_name = "esp_price";
530
-        $sql = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
527
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
528
+		// modified tables
529
+		$table_name = "esp_price";
530
+		$sql = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
531 531
 				PRT_ID tinyint(3) unsigned NOT NULL,
532 532
 				PRC_amount decimal(12,3) NOT NULL DEFAULT '0.00',
533 533
 				PRC_name varchar(245) NOT NULL,
@@ -540,9 +540,9 @@  discard block
 block discarded – undo
540 540
 				PRC_parent int(10) unsigned DEFAULT 0,
541 541
 				PRIMARY KEY  (PRC_ID),
542 542
 				KEY PRT_ID (PRT_ID)";
543
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
544
-        $table_name = "esp_price_type";
545
-        $sql = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
543
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
544
+		$table_name = "esp_price_type";
545
+		$sql = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
546 546
 				PRT_name varchar(45) NOT NULL,
547 547
 				PBT_ID tinyint(3) unsigned NOT NULL DEFAULT '1',
548 548
 				PRT_is_percent tinyint(1) NOT NULL DEFAULT '0',
@@ -551,9 +551,9 @@  discard block
 block discarded – undo
551 551
 				PRT_deleted tinyint(1) NOT NULL DEFAULT '0',
552 552
 				UNIQUE KEY PRT_name_UNIQUE (PRT_name),
553 553
 				PRIMARY KEY  (PRT_ID)";
554
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
555
-        $table_name = "esp_ticket";
556
-        $sql = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
554
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
555
+		$table_name = "esp_ticket";
556
+		$sql = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
557 557
 				TTM_ID int(10) unsigned NOT NULL,
558 558
 				TKT_name varchar(245) NOT NULL DEFAULT '',
559 559
 				TKT_description text NOT NULL,
@@ -576,9 +576,9 @@  discard block
 block discarded – undo
576 576
 				TKT_deleted tinyint(1) NOT NULL DEFAULT '0',
577 577
 				PRIMARY KEY  (TKT_ID),
578 578
 				KEY TKT_start_date (TKT_start_date)";
579
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
580
-        $table_name = 'esp_question_group';
581
-        $sql = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
579
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
580
+		$table_name = 'esp_question_group';
581
+		$sql = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
582 582
 				QSG_name varchar(255) NOT NULL,
583 583
 				QSG_identifier varchar(100) NOT NULL,
584 584
 				QSG_desc text NULL,
@@ -591,165 +591,165 @@  discard block
 block discarded – undo
591 591
 				PRIMARY KEY  (QSG_ID),
592 592
 				UNIQUE KEY QSG_identifier_UNIQUE (QSG_identifier),
593 593
 				KEY QSG_order (QSG_order)';
594
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
595
-        $this->insert_default_data();
596
-        return true;
597
-    }
594
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
595
+		$this->insert_default_data();
596
+		return true;
597
+	}
598 598
 
599
-    /**
600
-     * Inserts default data after parent was called.
601
-     * @since 4.10.0.p
602
-     * @throws EE_Error
603
-     * @throws InvalidArgumentException
604
-     * @throws ReflectionException
605
-     * @throws InvalidDataTypeException
606
-     * @throws InvalidInterfaceException
607
-     */
608
-    public function insert_default_data()
609
-    {
610
-        /** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
611
-        $script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
612
-        // (because many need to convert old string states to foreign keys into the states table)
613
-        $script_4_1_defaults->insert_default_states();
614
-        $script_4_1_defaults->insert_default_countries();
615
-        /** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
616
-        $script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
617
-        $script_4_5_defaults->insert_default_price_types();
618
-        $script_4_5_defaults->insert_default_prices();
619
-        $script_4_5_defaults->insert_default_tickets();
620
-        /** @var EE_DMS_Core_4_6_0 $script_4_6_defaults */
621
-        $script_4_6_defaults = EE_Registry::instance()->load_dms('Core_4_6_0');
622
-        $script_4_6_defaults->add_default_admin_only_payments();
623
-        $script_4_6_defaults->insert_default_currencies();
624
-        /** @var EE_DMS_Core_4_8_0 $script_4_8_defaults */
625
-        $script_4_8_defaults = EE_Registry::instance()->load_dms('Core_4_8_0');
626
-        $script_4_8_defaults->verify_new_countries();
627
-        $script_4_8_defaults->verify_new_currencies();
628
-        $this->verify_db_collations();
629
-        $this->verify_db_collations_again();
630
-    }
599
+	/**
600
+	 * Inserts default data after parent was called.
601
+	 * @since 4.10.0.p
602
+	 * @throws EE_Error
603
+	 * @throws InvalidArgumentException
604
+	 * @throws ReflectionException
605
+	 * @throws InvalidDataTypeException
606
+	 * @throws InvalidInterfaceException
607
+	 */
608
+	public function insert_default_data()
609
+	{
610
+		/** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
611
+		$script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
612
+		// (because many need to convert old string states to foreign keys into the states table)
613
+		$script_4_1_defaults->insert_default_states();
614
+		$script_4_1_defaults->insert_default_countries();
615
+		/** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
616
+		$script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
617
+		$script_4_5_defaults->insert_default_price_types();
618
+		$script_4_5_defaults->insert_default_prices();
619
+		$script_4_5_defaults->insert_default_tickets();
620
+		/** @var EE_DMS_Core_4_6_0 $script_4_6_defaults */
621
+		$script_4_6_defaults = EE_Registry::instance()->load_dms('Core_4_6_0');
622
+		$script_4_6_defaults->add_default_admin_only_payments();
623
+		$script_4_6_defaults->insert_default_currencies();
624
+		/** @var EE_DMS_Core_4_8_0 $script_4_8_defaults */
625
+		$script_4_8_defaults = EE_Registry::instance()->load_dms('Core_4_8_0');
626
+		$script_4_8_defaults->verify_new_countries();
627
+		$script_4_8_defaults->verify_new_currencies();
628
+		$this->verify_db_collations();
629
+		$this->verify_db_collations_again();
630
+	}
631 631
 
632 632
 
633 633
 
634
-    /**
635
-     * @return boolean
636
-     */
637
-    public function schema_changes_after_migration()
638
-    {
639
-        return true;
640
-    }
634
+	/**
635
+	 * @return boolean
636
+	 */
637
+	public function schema_changes_after_migration()
638
+	{
639
+		return true;
640
+	}
641 641
 
642 642
 
643 643
 
644
-    public function migration_page_hooks()
645
-    {
646
-    }
644
+	public function migration_page_hooks()
645
+	{
646
+	}
647 647
 
648 648
 
649 649
 
650
-    /**
651
-     * Verify all EE4 models' tables use utf8mb4 collation
652
-     *
653
-     * @return void
654
-     */
655
-    public function verify_db_collations()
656
-    {
657
-        global $wpdb;
658
-        // double-check we haven't already done it or that that the DB doesn't support utf8mb4
659
-        if (
660
-            'utf8mb4' !== $wpdb->charset
661
-            || get_option('ee_verified_db_collations', false)
662
-        ) {
663
-            return;
664
-        }
665
-        // grab tables from each model
666
-        $tables_to_check = array();
667
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
668
-            if (method_exists($model_name, 'instance')) {
669
-                $model_obj = call_user_func(array($model_name, 'instance'));
670
-                if ($model_obj instanceof EEM_Base) {
671
-                    foreach ($model_obj->get_tables() as $table) {
672
-                        if (
673
-                            strpos($table->get_table_name(), 'esp_')
674
-                            && (is_main_site()// for main tables, verify global tables
675
-                                || ! $table->is_global()// if not the main site, then only verify non-global tables (avoid doubling up)
676
-                            )
677
-                            && function_exists('maybe_convert_table_to_utf8mb4')
678
-                        ) {
679
-                            $tables_to_check[] = $table->get_table_name();
680
-                        }
681
-                    }
682
-                }
683
-            }
684
-        }
685
-        // and let's just be sure these addons' tables get migrated too. They already get handled if their addons are active
686
-        // when this code is run, but not otherwise. Once we record what tables EE added, we'll be able to use that instead
687
-        // of hard-coding this
688
-        $addon_tables = array(
689
-            // mailchimp
690
-            'esp_event_mailchimp_list_group',
691
-            'esp_event_question_mailchimp_field',
692
-            // multisite
693
-            'esp_blog_meta',
694
-            // people
695
-            'esp_people_to_post',
696
-            // promotions
697
-            'esp_promotion',
698
-            'esp_promotion_object',
699
-        );
700
-        foreach ($addon_tables as $table_name) {
701
-                $tables_to_check[] = $table_name;
702
-        }
703
-        $this->_verify_db_collations_for_tables(array_unique($tables_to_check));
704
-        // ok and now let's remember this was done (without needing to check the db schemas all over again)
705
-        add_option('ee_verified_db_collations', true, null, 'no');
706
-        // seeing how this ran with the fix from 10435, no need to check again
707
-        add_option('ee_verified_db_collations_again', true, null, 'no');
708
-    }
650
+	/**
651
+	 * Verify all EE4 models' tables use utf8mb4 collation
652
+	 *
653
+	 * @return void
654
+	 */
655
+	public function verify_db_collations()
656
+	{
657
+		global $wpdb;
658
+		// double-check we haven't already done it or that that the DB doesn't support utf8mb4
659
+		if (
660
+			'utf8mb4' !== $wpdb->charset
661
+			|| get_option('ee_verified_db_collations', false)
662
+		) {
663
+			return;
664
+		}
665
+		// grab tables from each model
666
+		$tables_to_check = array();
667
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
668
+			if (method_exists($model_name, 'instance')) {
669
+				$model_obj = call_user_func(array($model_name, 'instance'));
670
+				if ($model_obj instanceof EEM_Base) {
671
+					foreach ($model_obj->get_tables() as $table) {
672
+						if (
673
+							strpos($table->get_table_name(), 'esp_')
674
+							&& (is_main_site()// for main tables, verify global tables
675
+								|| ! $table->is_global()// if not the main site, then only verify non-global tables (avoid doubling up)
676
+							)
677
+							&& function_exists('maybe_convert_table_to_utf8mb4')
678
+						) {
679
+							$tables_to_check[] = $table->get_table_name();
680
+						}
681
+					}
682
+				}
683
+			}
684
+		}
685
+		// and let's just be sure these addons' tables get migrated too. They already get handled if their addons are active
686
+		// when this code is run, but not otherwise. Once we record what tables EE added, we'll be able to use that instead
687
+		// of hard-coding this
688
+		$addon_tables = array(
689
+			// mailchimp
690
+			'esp_event_mailchimp_list_group',
691
+			'esp_event_question_mailchimp_field',
692
+			// multisite
693
+			'esp_blog_meta',
694
+			// people
695
+			'esp_people_to_post',
696
+			// promotions
697
+			'esp_promotion',
698
+			'esp_promotion_object',
699
+		);
700
+		foreach ($addon_tables as $table_name) {
701
+				$tables_to_check[] = $table_name;
702
+		}
703
+		$this->_verify_db_collations_for_tables(array_unique($tables_to_check));
704
+		// ok and now let's remember this was done (without needing to check the db schemas all over again)
705
+		add_option('ee_verified_db_collations', true, null, 'no');
706
+		// seeing how this ran with the fix from 10435, no need to check again
707
+		add_option('ee_verified_db_collations_again', true, null, 'no');
708
+	}
709 709
 
710 710
 
711 711
 
712
-    /**
713
-     * Verifies DB collations because a bug was discovered on https://events.codebasehq.com/projects/event-espresso/tickets/10435
714
-     * which meant some DB collations might not have been updated
715
-     * @return void
716
-     */
717
-    public function verify_db_collations_again()
718
-    {
719
-        global $wpdb;
720
-        // double-check we haven't already done this or that the DB doesn't support it
721
-        // compare to how WordPress' upgrade_430() function does this check
722
-        if (
723
-            'utf8mb4' !== $wpdb->charset
724
-            || get_option('ee_verified_db_collations_again', false)
725
-        ) {
726
-            return;
727
-        }
728
-        $tables_to_check = array(
729
-            'esp_attendee_meta',
730
-            'esp_message'
731
-        );
732
-        $this->_verify_db_collations_for_tables(array_unique($tables_to_check));
733
-        add_option('ee_verified_db_collations_again', true, null, 'no');
734
-    }
712
+	/**
713
+	 * Verifies DB collations because a bug was discovered on https://events.codebasehq.com/projects/event-espresso/tickets/10435
714
+	 * which meant some DB collations might not have been updated
715
+	 * @return void
716
+	 */
717
+	public function verify_db_collations_again()
718
+	{
719
+		global $wpdb;
720
+		// double-check we haven't already done this or that the DB doesn't support it
721
+		// compare to how WordPress' upgrade_430() function does this check
722
+		if (
723
+			'utf8mb4' !== $wpdb->charset
724
+			|| get_option('ee_verified_db_collations_again', false)
725
+		) {
726
+			return;
727
+		}
728
+		$tables_to_check = array(
729
+			'esp_attendee_meta',
730
+			'esp_message'
731
+		);
732
+		$this->_verify_db_collations_for_tables(array_unique($tables_to_check));
733
+		add_option('ee_verified_db_collations_again', true, null, 'no');
734
+	}
735 735
 
736 736
 
737 737
 
738
-    /**
739
-     * Runs maybe_convert_table_to_utf8mb4 on the specified tables
740
-     * @param $tables_to_check
741
-     * @return boolean true if logic ran, false if it didn't
742
-     */
743
-    protected function _verify_db_collations_for_tables($tables_to_check)
744
-    {
745
-        foreach ($tables_to_check as $table_name) {
746
-            $table_name = $this->_table_analysis->ensureTableNameHasPrefix($table_name);
747
-            if (
748
-                ! apply_filters('FHEE__EE_DMS_Core_4_9_0__verify_db_collations__check_overridden', false, $table_name)
749
-                && $this->_get_table_analysis()->tableExists($table_name)
750
-            ) {
751
-                maybe_convert_table_to_utf8mb4($table_name);
752
-            }
753
-        }
754
-    }
738
+	/**
739
+	 * Runs maybe_convert_table_to_utf8mb4 on the specified tables
740
+	 * @param $tables_to_check
741
+	 * @return boolean true if logic ran, false if it didn't
742
+	 */
743
+	protected function _verify_db_collations_for_tables($tables_to_check)
744
+	{
745
+		foreach ($tables_to_check as $table_name) {
746
+			$table_name = $this->_table_analysis->ensureTableNameHasPrefix($table_name);
747
+			if (
748
+				! apply_filters('FHEE__EE_DMS_Core_4_9_0__verify_db_collations__check_overridden', false, $table_name)
749
+				&& $this->_get_table_analysis()->tableExists($table_name)
750
+			) {
751
+				maybe_convert_table_to_utf8mb4($table_name);
752
+			}
753
+		}
754
+	}
755 755
 }
Please login to merge, or discard this patch.
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.
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
@@ -28,59 +28,59 @@
 block discarded – undo
28 28
 class EE_DMS_4_6_0_invoice_settings extends EE_Data_Migration_Script_Stage
29 29
 {
30 30
 
31
-    /**
32
-     * Just initializes the status of the migration
33
-     */
34
-    public function __construct()
35
-    {
36
-        $this->_pretty_name = esc_html__('Update Invoice Settings', 'event_espresso');
37
-        parent::__construct();
38
-    }
31
+	/**
32
+	 * Just initializes the status of the migration
33
+	 */
34
+	public function __construct()
35
+	{
36
+		$this->_pretty_name = esc_html__('Update Invoice Settings', 'event_espresso');
37
+		parent::__construct();
38
+	}
39 39
 
40 40
 
41 41
 
42
-    /**
43
-     * _count_records_to_migrate
44
-     * Counts the records to migrate; the public version may cache it
45
-     *
46
-     * @access protected
47
-     * @return int
48
-     */
49
-    protected function _count_records_to_migrate()
50
-    {
51
-        return 1;
52
-    }
42
+	/**
43
+	 * _count_records_to_migrate
44
+	 * Counts the records to migrate; the public version may cache it
45
+	 *
46
+	 * @access protected
47
+	 * @return int
48
+	 */
49
+	protected function _count_records_to_migrate()
50
+	{
51
+		return 1;
52
+	}
53 53
 
54 54
 
55 55
 
56
-    /**
57
-     *    _migration_step
58
-     *
59
-     * @access protected
60
-     * @param int $num_items
61
-     * @throws EE_Error
62
-     * @return int number of items ACTUALLY migrated
63
-     * @throws InvalidDataTypeException
64
-     */
65
-    protected function _migration_step($num_items = 1)
66
-    {
56
+	/**
57
+	 *    _migration_step
58
+	 *
59
+	 * @access protected
60
+	 * @param int $num_items
61
+	 * @throws EE_Error
62
+	 * @return int number of items ACTUALLY migrated
63
+	 * @throws InvalidDataTypeException
64
+	 */
65
+	protected function _migration_step($num_items = 1)
66
+	{
67 67
 
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);
71
-        if ($overridden_invoice_body || $overridden_receipt_body) {
72
-            new PersistentAdminNotice(
73
-                'invoice_overriding_templates',
74
-                esc_html__(
75
-                    '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.',
76
-                    'event_espresso'
77
-                ),
78
-                true
79
-            );
80
-        }
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);
71
+		if ($overridden_invoice_body || $overridden_receipt_body) {
72
+			new PersistentAdminNotice(
73
+				'invoice_overriding_templates',
74
+				esc_html__(
75
+					'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.',
76
+					'event_espresso'
77
+				),
78
+				true
79
+			);
80
+		}
81 81
 
82
-        // regardless of whether it worked or not, we ought to continue the migration
83
-        $this->set_completed();
84
-        return 1;
85
-    }
82
+		// regardless of whether it worked or not, we ought to continue the migration
83
+		$this->set_completed();
84
+		return 1;
85
+	}
86 86
 }
Please login to merge, or discard this patch.
core/EE_Load_Textdomain.core.php 2 patches
Indentation   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -13,105 +13,105 @@
 block discarded – undo
13 13
 class EE_Load_Textdomain extends EE_Base
14 14
 {
15 15
 
16
-    /**
17
-     * holds the current lang in WP
18
-     *
19
-     * @var string
20
-     */
21
-    private static $locale;
16
+	/**
17
+	 * holds the current lang in WP
18
+	 *
19
+	 * @var string
20
+	 */
21
+	private static $locale;
22 22
 
23 23
 
24
-    /**
25
-     * this takes care of retrieving a matching textdomain for event espresso for the current WPLANG from EE GitHub
26
-     * repo (if necessary) and then loading it for translations. should only be called in wp plugins_loaded callback
27
-     *
28
-     * @return void
29
-     * @throws EE_Error
30
-     * @throws InvalidArgumentException
31
-     * @throws ReflectionException
32
-     * @throws InvalidDataTypeException
33
-     * @throws InvalidInterfaceException
34
-     */
35
-    public static function load_textdomain()
36
-    {
37
-        EE_Load_Textdomain::loadTranslationsForLocale();
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';
41
-            if (is_readable($github_mo_path)) {
42
-                load_plugin_textdomain('event_espresso', false, EE_LANGUAGES_SAFE_LOC);
43
-                return;
44
-            }
45
-            $glotpress_mo_path = EE_LANGUAGES_SAFE_DIR . 'event-espresso-4-' . EE_Load_Textdomain::$locale . '.mo';
46
-            if (is_readable($glotpress_mo_path)) {
47
-                load_textdomain('event_espresso', $glotpress_mo_path);
48
-                return;
49
-            }
50
-        }
51
-        load_plugin_textdomain('event_espresso', false, dirname(EE_PLUGIN_BASENAME) . '/languages/');
52
-    }
24
+	/**
25
+	 * this takes care of retrieving a matching textdomain for event espresso for the current WPLANG from EE GitHub
26
+	 * repo (if necessary) and then loading it for translations. should only be called in wp plugins_loaded callback
27
+	 *
28
+	 * @return void
29
+	 * @throws EE_Error
30
+	 * @throws InvalidArgumentException
31
+	 * @throws ReflectionException
32
+	 * @throws InvalidDataTypeException
33
+	 * @throws InvalidInterfaceException
34
+	 */
35
+	public static function load_textdomain()
36
+	{
37
+		EE_Load_Textdomain::loadTranslationsForLocale();
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';
41
+			if (is_readable($github_mo_path)) {
42
+				load_plugin_textdomain('event_espresso', false, EE_LANGUAGES_SAFE_LOC);
43
+				return;
44
+			}
45
+			$glotpress_mo_path = EE_LANGUAGES_SAFE_DIR . 'event-espresso-4-' . EE_Load_Textdomain::$locale . '.mo';
46
+			if (is_readable($glotpress_mo_path)) {
47
+				load_textdomain('event_espresso', $glotpress_mo_path);
48
+				return;
49
+			}
50
+		}
51
+		load_plugin_textdomain('event_espresso', false, dirname(EE_PLUGIN_BASENAME) . '/languages/');
52
+	}
53 53
 
54 54
 
55
-    /**
56
-     * 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).
57
-     *
58
-     * @access private
59
-     * @static
60
-     * @return void
61
-     * @throws EE_Error
62
-     * @throws InvalidArgumentException
63
-     * @throws ReflectionException
64
-     * @throws InvalidDataTypeException
65
-     * @throws InvalidInterfaceException
66
-     */
67
-    private static function loadTranslationsForLocale()
68
-    {
69
-        EE_Load_Textdomain::$locale = get_locale();
70
-        // can't download a language file if a language isn't set <taps temple>
71
-        if (empty(EE_Load_Textdomain::$locale)) {
72
-            return;
73
-        }
74
-        $language_check_option_name = 'ee_lang_check_' . EE_Load_Textdomain::$locale . '_' . EVENT_ESPRESSO_VERSION;
75
-        // check if language files has already been sideloaded
76
-        if (get_option($language_check_option_name)) {
77
-            return;
78
-        }
55
+	/**
56
+	 * 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).
57
+	 *
58
+	 * @access private
59
+	 * @static
60
+	 * @return void
61
+	 * @throws EE_Error
62
+	 * @throws InvalidArgumentException
63
+	 * @throws ReflectionException
64
+	 * @throws InvalidDataTypeException
65
+	 * @throws InvalidInterfaceException
66
+	 */
67
+	private static function loadTranslationsForLocale()
68
+	{
69
+		EE_Load_Textdomain::$locale = get_locale();
70
+		// can't download a language file if a language isn't set <taps temple>
71
+		if (empty(EE_Load_Textdomain::$locale)) {
72
+			return;
73
+		}
74
+		$language_check_option_name = 'ee_lang_check_' . EE_Load_Textdomain::$locale . '_' . EVENT_ESPRESSO_VERSION;
75
+		// check if language files has already been sideloaded
76
+		if (get_option($language_check_option_name)) {
77
+			return;
78
+		}
79 79
 
80
-        $repo_base_URL = 'https://github.com/eventespresso/languages-ee4/blob/master/event_espresso';
80
+		$repo_base_URL = 'https://github.com/eventespresso/languages-ee4/blob/master/event_espresso';
81 81
 
82
-        // load sideloader and sideload the .POT file as this should always be included.
83
-        $sideloader_args = array(
84
-            '_upload_to'     => EE_PLUGIN_DIR_PATH . 'languages/',
85
-            '_download_from'   => $repo_base_URL . '.pot?raw=true',
86
-            '_new_file_name' => 'event_espresso.pot',
87
-        );
88
-        /** @var EEH_Sideloader $sideloader */
89
-        $sideloader = EE_Registry::instance()->load_helper('Sideloader', $sideloader_args, false);
90
-        // sideload the .POT file only for main site of the network, or if not running Multisite.
91
-        if (is_main_site()) {
92
-            $sideloader->sideload();
93
-        }
82
+		// load sideloader and sideload the .POT file as this should always be included.
83
+		$sideloader_args = array(
84
+			'_upload_to'     => EE_PLUGIN_DIR_PATH . 'languages/',
85
+			'_download_from'   => $repo_base_URL . '.pot?raw=true',
86
+			'_new_file_name' => 'event_espresso.pot',
87
+		);
88
+		/** @var EEH_Sideloader $sideloader */
89
+		$sideloader = EE_Registry::instance()->load_helper('Sideloader', $sideloader_args, false);
90
+		// sideload the .POT file only for main site of the network, or if not running Multisite.
91
+		if (is_main_site()) {
92
+			$sideloader->sideload();
93
+		}
94 94
 
95
-        // if locale is "en_US" then lets just get out, since Event Espresso core is already "en_US"
96
-        if (EE_Load_Textdomain::$locale === 'en_US') {
97
-            // but set option first else we'll forever be downloading the pot file
98
-            update_option($language_check_option_name, 1);
99
-            return;
100
-        }
101
-        $repo_locale_URL = $repo_base_URL . '-' . EE_Load_Textdomain::$locale;
102
-        $file_name_base = 'event_espresso-' . EE_Load_Textdomain::$locale;
95
+		// if locale is "en_US" then lets just get out, since Event Espresso core is already "en_US"
96
+		if (EE_Load_Textdomain::$locale === 'en_US') {
97
+			// but set option first else we'll forever be downloading the pot file
98
+			update_option($language_check_option_name, 1);
99
+			return;
100
+		}
101
+		$repo_locale_URL = $repo_base_URL . '-' . EE_Load_Textdomain::$locale;
102
+		$file_name_base = 'event_espresso-' . EE_Load_Textdomain::$locale;
103 103
 
104
-        // made it here so let's get the language files from the github repo, first the .mo file
105
-        $sideloader->set_download_from("{$repo_locale_URL}.mo?raw=true");
106
-        $sideloader->set_new_file_name("{$file_name_base}.mo");
107
-        $sideloader->sideload();
104
+		// made it here so let's get the language files from the github repo, first the .mo file
105
+		$sideloader->set_download_from("{$repo_locale_URL}.mo?raw=true");
106
+		$sideloader->set_new_file_name("{$file_name_base}.mo");
107
+		$sideloader->sideload();
108 108
 
109
-        // now the .po file:
110
-        $sideloader->set_download_from("{$repo_locale_URL}.po?raw=true");
111
-        $sideloader->set_new_file_name("{$file_name_base}.po");
112
-        $sideloader->sideload();
109
+		// now the .po file:
110
+		$sideloader->set_download_from("{$repo_locale_URL}.po?raw=true");
111
+		$sideloader->set_new_file_name("{$file_name_base}.po");
112
+		$sideloader->sideload();
113 113
 
114
-        // set option so the above only runs when EE updates.
115
-        update_option($language_check_option_name, 1);
116
-    }
114
+		// set option so the above only runs when EE updates.
115
+		update_option($language_check_option_name, 1);
116
+	}
117 117
 }
Please login to merge, or discard this patch.
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.