Completed
Branch master (24c3eb)
by
unknown
34:49 queued 28:57
created
core/db_models/EEM_Message.model.php 2 patches
Indentation   +662 added lines, -662 removed lines patch added patch discarded remove patch
@@ -12,674 +12,674 @@
 block discarded – undo
12 12
  */
13 13
 class EEM_Message extends EEM_Base implements EEI_Query_Filter
14 14
 {
15
-    protected static ?EEM_Message $_instance = null;
15
+	protected static ?EEM_Message $_instance = null;
16 16
 
17 17
 
18
-    /**
19
-     * This priority indicates a message should be generated and sent ASAP
20
-     *
21
-     * @type int
22
-     */
23
-    const priority_high = 10;
24
-
18
+	/**
19
+	 * This priority indicates a message should be generated and sent ASAP
20
+	 *
21
+	 * @type int
22
+	 */
23
+	const priority_high = 10;
24
+
25 25
 
26
-    /**
27
-     * This priority indicates a message should be generated ASAP and queued for sending.
28
-     *
29
-     * @type
30
-     */
31
-    const priority_medium = 20;
32
-
33
-
34
-    /**
35
-     * This priority indicates a message should be queued for generating.
36
-     *
37
-     * @type int
38
-     */
39
-    const priority_low = 30;
40
-
41
-
42
-    /**
43
-     * indicates this message was sent at the time modified
44
-     */
45
-    const status_sent = 'MSN';
46
-
47
-
48
-    /**
49
-     * indicates this message is waiting to be sent
50
-     */
51
-    const status_idle = 'MID';
52
-
53
-
54
-    /**
55
-     * indicates an attempt was a made to send this message
56
-     * at the scheduled time, but it failed at the time modified.  This differs from MDO status in that it will ALWAYS
57
-     * appear to the end user.
58
-     */
59
-    const status_failed = 'MFL';
60
-
61
-
62
-    /**
63
-     * indicates the message has been flagged for resending (at the time modified).
64
-     */
65
-    const status_resend = 'MRS';
66
-
67
-
68
-    /**
69
-     * indicates the message has been flagged for generation but has not been generated yet.  Messages always start as
70
-     * this status when added to the queue.
71
-     */
72
-    const status_incomplete = 'MIC';
73
-
74
-
75
-    /**
76
-     * Indicates everything was generated fine for the message, however, the messenger was unable to send.
77
-     * This status means that its possible to retry sending the message.
78
-     */
79
-    const status_retry = 'MRT';
80
-
81
-
82
-    /**
83
-     * This is used for more informational messages that may not indicate anything is broken but still cannot be
84
-     * generated or sent correctly. An example of a message that would get flagged this way would be when a not
85
-     * approved message was queued for generation, but at time of generation, the attached registration(s) are
86
-     * approved. So the message queued for generation is no longer valid.  Messages for this status will only persist
87
-     * in the db and be viewable in the message activity list table when the messages system is in debug mode.
88
-     *
89
-     * @see EEM_Message::debug()
90
-     */
91
-    const status_debug_only = 'MDO';
92
-
93
-
94
-    /**
95
-     * This status is given to messages it is processed by the messenger send method.
96
-     * Messages with this status should rarely be seen in the Message List table, but if they are, that's usually
97
-     * indicative of a PHP timeout or memory limit issue.
98
-     */
99
-    const status_messenger_executing = 'MEX';
100
-
101
-
102
-    /**
103
-     * Private constructor to prevent direct creation.
104
-     *
105
-     * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings (and
106
-     *                              any incoming timezone data that gets saved).  Note this just sends the timezone
107
-     *                              info to the date time model field objects.  Default is null (and will be assumed
108
-     *                              using the set timezone in the 'timezone_string' wp option)
109
-     * @throws EE_Error
110
-     */
111
-    protected function __construct(?string $timezone = '')
112
-    {
113
-        $this->singular_item = esc_html__('Message', 'event_espresso');
114
-        $this->plural_item   = esc_html__('Messages', 'event_espresso');
115
-
116
-        $this->_tables = [
117
-            'Message' => new EE_Primary_Table('esp_message', 'MSG_ID'),
118
-        ];
119
-
120
-        $allowed_priority = [
121
-            self::priority_high   => esc_html__('high', 'event_espresso'),
122
-            self::priority_medium => esc_html__('medium', 'event_espresso'),
123
-            self::priority_low    => esc_html__('low', 'event_espresso'),
124
-        ];
125
-
126
-        $this->_fields          = [
127
-            'Message' => [
128
-                'MSG_ID'             => new EE_Primary_Key_Int_Field(
129
-                    'MSG_ID',
130
-                    esc_html__('Message ID', 'event_espresso')
131
-                ),
132
-                'MSG_token'          => new EE_Plain_Text_Field(
133
-                    'MSG_token',
134
-                    esc_html__(
135
-                        'Unique Token used to represent this row in publicly viewable contexts (eg. a url).',
136
-                        'event_espresso'
137
-                    ),
138
-                    false,
139
-                    EEH_URL::generate_unique_token()
140
-                ),
141
-                'GRP_ID'             => new EE_Foreign_Key_Int_Field(
142
-                    'GRP_ID',
143
-                    esc_html__('Foreign key to the EEM_Message_Template_Group table.', 'event_espresso'),
144
-                    true,
145
-                    0,
146
-                    'Message_Template_Group'
147
-                ),
148
-                'TXN_ID'             => new EE_Foreign_Key_Int_Field(
149
-                    'TXN_ID',
150
-                    esc_html__(
151
-                        'Foreign key to the related EE_Transaction.  This is required to give context for regenerating the specific message',
152
-                        'event_espresso'
153
-                    ),
154
-                    true,
155
-                    0,
156
-                    'Transaction'
157
-                ),
158
-                'MSG_messenger'      => new EE_Plain_Text_Field(
159
-                    'MSG_messenger',
160
-                    esc_html__(
161
-                        'Corresponds to the EE_messenger::name used to send this message. This will also be used to attempt any resending of the message.',
162
-                        'event_espresso'
163
-                    ),
164
-                    false,
165
-                    'email'
166
-                ),
167
-                'MSG_message_type'   => new EE_Plain_Text_Field(
168
-                    'MSG_message_type',
169
-                    esc_html__(
170
-                        'Corresponds to the EE_message_type::name used to generate this message.',
171
-                        'event_espresso'
172
-                    ),
173
-                    false,
174
-                    'receipt'
175
-                ),
176
-                'MSG_context'        => new EE_Plain_Text_Field(
177
-                    'MSG_context',
178
-                    esc_html__('Context', 'event_espresso'),
179
-                    false
180
-                ),
181
-                'MSG_recipient_ID'   => new EE_Foreign_Key_Int_Field(
182
-                    'MSG_recipient_ID',
183
-                    esc_html__('Recipient ID', 'event_espresso'),
184
-                    true,
185
-                    null,
186
-                    ['Registration', 'Attendee', 'WP_User']
187
-                ),
188
-                'MSG_recipient_type' => new EE_Any_Foreign_Model_Name_Field(
189
-                    'MSG_recipient_type',
190
-                    esc_html__('Recipient Type', 'event_espresso'),
191
-                    true,
192
-                    null,
193
-                    ['Registration', 'Attendee', 'WP_User']
194
-                ),
195
-                'MSG_content'        => new EE_Maybe_Serialized_Text_Field(
196
-                    'MSG_content',
197
-                    esc_html__('Content', 'event_espresso'),
198
-                    true,
199
-                    ''
200
-                ),
201
-                'MSG_to'             => new EE_Maybe_Serialized_Text_Field(
202
-                    'MSG_to',
203
-                    esc_html__('Address To', 'event_espresso'),
204
-                    true
205
-                ),
206
-                'MSG_from'           => new EE_Maybe_Serialized_Text_Field(
207
-                    'MSG_from',
208
-                    esc_html__('Address From', 'event_espresso'),
209
-                    true
210
-                ),
211
-                'MSG_subject'        => new EE_Maybe_Serialized_Text_Field(
212
-                    'MSG_subject',
213
-                    esc_html__('Subject', 'event_espresso'),
214
-                    true,
215
-                    ''
216
-                ),
217
-                'MSG_priority'       => new EE_Enum_Integer_Field(
218
-                    'MSG_priority',
219
-                    esc_html__('Priority', 'event_espresso'),
220
-                    false,
221
-                    self::priority_low,
222
-                    $allowed_priority
223
-                ),
224
-                'STS_ID'             => new EE_Foreign_Key_String_Field(
225
-                    'STS_ID',
226
-                    esc_html__('Status', 'event_espresso'),
227
-                    false,
228
-                    self::status_incomplete,
229
-                    'Status'
230
-                ),
231
-                'MSG_created'        => new EE_Datetime_Field(
232
-                    'MSG_created',
233
-                    esc_html__('Created', 'event_espresso'),
234
-                    false,
235
-                    EE_Datetime_Field::now
236
-                ),
237
-                'MSG_modified'       => new EE_Datetime_Field(
238
-                    'MSG_modified',
239
-                    esc_html__('Modified', 'event_espresso'),
240
-                    true,
241
-                    EE_Datetime_Field::now
242
-                ),
243
-            ],
244
-        ];
245
-        $this->_model_relations = [
246
-            'Attendee'               => new EE_Belongs_To_Any_Relation(),
247
-            'Registration'           => new EE_Belongs_To_Any_Relation(),
248
-            'WP_User'                => new EE_Belongs_To_Any_Relation(),
249
-            'Message_Template_Group' => new EE_Belongs_To_Relation(),
250
-            'Transaction'            => new EE_Belongs_To_Relation(),
251
-        ];
252
-        parent::__construct($timezone);
253
-    }
254
-
255
-
256
-    /**
257
-     * @return EE_Message
258
-     * @throws EE_Error
259
-     */
260
-    public function create_default_object()
261
-    {
262
-        /** @type EE_Message $message */
263
-        $message = parent::create_default_object();
264
-        if ($message instanceof EE_Message) {
265
-            return EE_Message_Factory::set_messenger_and_message_type($message);
266
-        }
267
-        return null;
268
-    }
269
-
270
-
271
-    /**
272
-     * @param mixed $cols_n_values
273
-     * @return EE_Message
274
-     * @throws EE_Error
275
-     * @throws EE_Error
276
-     */
277
-    public function instantiate_class_from_array_or_object($cols_n_values)
278
-    {
279
-        /** @type EE_Message $message */
280
-        $message = parent::instantiate_class_from_array_or_object($cols_n_values);
281
-        if ($message instanceof EE_Message) {
282
-            return EE_Message_Factory::set_messenger_and_message_type($message);
283
-        }
284
-        return null;
285
-    }
286
-
287
-
288
-    /**
289
-     * Returns whether or not a message of that type was sent for a given attendee.
290
-     *
291
-     * @param EE_Attendee|int $attendee
292
-     * @param string          $message_type the message type slug
293
-     * @return boolean
294
-     * @throws EE_Error
295
-     * @throws EE_Error
296
-     * @throws EE_Error
297
-     */
298
-    public function message_sent_for_attendee($attendee, $message_type)
299
-    {
300
-        $attendee_ID = EEM_Attendee::instance()->ensure_is_ID($attendee);
301
-        return $this->exists(
302
-            [
303
-                [
304
-                    'Attendee.ATT_ID'  => $attendee_ID,
305
-                    'MSG_message_type' => $message_type,
306
-                    'STS_ID'           => ['IN', $this->stati_indicating_sent()],
307
-                ],
308
-            ]
309
-        );
310
-    }
311
-
312
-
313
-    /**
314
-     * Returns whether or not a message of that type was sent for a given registration
315
-     *
316
-     * @param EE_Registration|int $registration
317
-     * @param string              $message_type the message type slug
318
-     * @return boolean
319
-     * @throws EE_Error
320
-     * @throws EE_Error
321
-     * @throws EE_Error
322
-     */
323
-    public function message_sent_for_registration($registration, $message_type)
324
-    {
325
-        $registrationID = EEM_Registration::instance()->ensure_is_ID($registration);
326
-        return $this->exists(
327
-            [
328
-                [
329
-                    'Registration.REG_ID' => $registrationID,
330
-                    'MSG_message_type'    => $message_type,
331
-                    'STS_ID'              => ['IN', $this->stati_indicating_sent()],
332
-                ],
333
-            ]
334
-        );
335
-    }
336
-
337
-
338
-    /**
339
-     * This retrieves an EE_Message object from the db matching the given token string.
340
-     *
341
-     * @param string $token
342
-     * @return EE_Message
343
-     * @throws EE_Error
344
-     */
345
-    public function get_one_by_token($token)
346
-    {
347
-        return $this->get_one(
348
-            [
349
-                [
350
-                    'MSG_token' => $token,
351
-                ],
352
-            ]
353
-        );
354
-    }
355
-
356
-
357
-    /**
358
-     * Returns stati that indicate the message HAS been sent
359
-     *
360
-     * @return array of strings for possible stati
361
-     */
362
-    public function stati_indicating_sent()
363
-    {
364
-        return apply_filters('FHEE__EEM_Message__stati_indicating_sent', [self::status_sent]);
365
-    }
366
-
367
-
368
-    /**
369
-     * Returns stati that indicate the message is waiting to be sent.
370
-     *
371
-     * @return array of strings for possible stati.
372
-     */
373
-    public function stati_indicating_to_send()
374
-    {
375
-        return apply_filters(
376
-            'FHEE__EEM_Message__stati_indicating_to_send',
377
-            [self::status_idle, self::status_resend]
378
-        );
379
-    }
380
-
381
-
382
-    /**
383
-     * Returns stati that indicate the message has failed sending
384
-     *
385
-     * @return array  array of strings for possible stati.
386
-     */
387
-    public function stati_indicating_failed_sending()
388
-    {
389
-        $failed_stati = [
390
-            self::status_failed,
391
-            self::status_retry,
392
-            self::status_messenger_executing,
393
-        ];
394
-        // if WP_DEBUG is set, then let's include debug_only fails
395
-        if (WP_DEBUG) {
396
-            $failed_stati[] = self::status_debug_only;
397
-        }
398
-        return apply_filters('FHEE__EEM_Message__stati_indicating_failed_sending', $failed_stati);
399
-    }
400
-
401
-
402
-    /**
403
-     * Returns filterable array of all EEM_Message statuses.
404
-     *
405
-     * @return array
406
-     */
407
-    public function all_statuses()
408
-    {
409
-        return apply_filters(
410
-            'FHEE__EEM_Message__all_statuses',
411
-            [
412
-                EEM_Message::status_sent,
413
-                EEM_Message::status_incomplete,
414
-                EEM_Message::status_idle,
415
-                EEM_Message::status_resend,
416
-                EEM_Message::status_retry,
417
-                EEM_Message::status_failed,
418
-                EEM_Message::status_messenger_executing,
419
-                EEM_Message::status_debug_only,
420
-            ]
421
-        );
422
-    }
423
-
424
-
425
-    /**
426
-     * Detects any specific query variables in the request and uses those to setup appropriate
427
-     * filter for any queries.
428
-     *
429
-     * @return array
430
-     */
431
-    public function filter_by_query_params()
432
-    {
433
-        /** @var RequestInterface $request */
434
-        $request = EEM_Base::$loader->getShared(RequestInterface::class);
435
-        // expected possible query_vars, the key in this array matches an expected key in the request,
436
-        // the value, matches the corresponding EEM_Base child reference.
437
-        $expected_vars   = $this->_expected_vars_for_query_inject();
438
-        $query_params[0] = [];
439
-        foreach ($expected_vars as $request_key => $model_name) {
440
-            $request_value = $request->getRequestParam($request_key);
441
-            if ($request_value) {
442
-                // special case
443
-                switch ($request_key) {
444
-                    case '_REG_ID':
445
-                        $query_params[0]['AND**filter_by']['OR**filter_by_REG_ID'] = [
446
-                            'Transaction.Registration.REG_ID' => $request_value,
447
-                        ];
448
-                        break;
449
-                    case 'EVT_ID':
450
-                        $query_params[0]['AND**filter_by']['OR**filter_by_EVT_ID'] = [
451
-                            'Transaction.Registration.EVT_ID' => $request_value,
452
-                        ];
453
-                        break;
454
-                    default:
455
-                        $query_params[0]['AND**filter_by'][ 'OR**filter_by_' . $request_key ][ $model_name . '.' . $request_key ] =
456
-                            $request_value;
457
-                        break;
458
-                }
459
-            }
460
-        }
461
-        return $query_params;
462
-    }
463
-
464
-
465
-    /**
466
-     * @return string
467
-     * @throws EE_Error
468
-     * @throws ReflectionException
469
-     */
470
-    public function get_pretty_label_for_results()
471
-    {
472
-        /** @var RequestInterface $request */
473
-        $request       = EEM_Base::$loader->getShared(RequestInterface::class);
474
-        $expected_vars = $this->_expected_vars_for_query_inject();
475
-        $pretty_label  = '';
476
-        $label_parts   = [];
477
-        foreach ($expected_vars as $request_key => $model_name) {
478
-            $model_name        = strpos($model_name, 'EEM_', true) === 0 ? $model_name : "EEM_{$model_name}";
479
-            $model             = EEM_Base::$loader->getShared($model_name);
480
-            $model_field_value = $request->getRequestParam($request_key);
481
-            if ($model instanceof EEM_Base && $model_field_value !== '') {
482
-                switch ($request_key) {
483
-                    case '_REG_ID':
484
-                        $label_parts[] = sprintf(
485
-                            esc_html__('Registration with the ID: %s', 'event_espresso'),
486
-                            $model_field_value
487
-                        );
488
-                        break;
489
-                    case 'ATT_ID':
490
-                        /** @var EE_Attendee $attendee */
491
-                        $attendee      = $model->get_one_by_ID($model_field_value);
492
-                        $label_parts[] = $attendee instanceof EE_Attendee
493
-                            ? sprintf(esc_html__('Attendee %s', 'event_espresso'), $attendee->full_name())
494
-                            : sprintf(esc_html__('Attendee ID: %s', 'event_espresso'), $model_field_value);
495
-                        break;
496
-                    case 'ID':
497
-                        /** @var EE_WP_User $wpUser */
498
-                        $wpUser        = $model->get_one_by_ID($model_field_value);
499
-                        $label_parts[] = $wpUser instanceof EE_WP_User
500
-                            ? sprintf(esc_html__('WP User: %s', 'event_espresso'), $wpUser->name())
501
-                            : sprintf(esc_html__('WP User ID: %s', 'event_espresso'), $model_field_value);
502
-                        break;
503
-                    case 'TXN_ID':
504
-                        $label_parts[] = sprintf(
505
-                            esc_html__('Transaction with the ID: %s', 'event_espresso'),
506
-                            $model_field_value
507
-                        );
508
-                        break;
509
-                    case 'EVT_ID':
510
-                        /** @var EE_Event $Event */
511
-                        $Event         = $model->get_one_by_ID($model_field_value);
512
-                        $label_parts[] = $Event instanceof EE_Event
513
-                            ? sprintf(esc_html__('for the Event: %s', 'event_espresso'), $Event->name())
514
-                            : sprintf(esc_html__('for the Event with ID: %s', 'event_espresso'), $model_field_value);
515
-                        break;
516
-                }
517
-            }
518
-        }
519
-
520
-        if ($label_parts) {
521
-            // prepend to the last element of $label_parts an "and".
522
-            if (count($label_parts) > 1) {
523
-                $label_parts_index_to_prepend                 = count($label_parts) - 1;
524
-                $label_parts[ $label_parts_index_to_prepend ] = 'and' . $label_parts[ $label_parts_index_to_prepend ];
525
-            }
526
-
527
-            $pretty_label .= sprintf(
528
-                esc_html_x(
529
-                    'Showing messages for %s',
530
-                    'A label for the messages returned in a query that are filtered by items in the query. This could be Transaction, Event, Attendee, Registration, or WP_User.',
531
-                    'event_espresso'
532
-                ),
533
-                implode(', ', $label_parts)
534
-            );
535
-        }
536
-        return $pretty_label;
537
-    }
538
-
539
-
540
-    /**
541
-     * This returns the array of expected variables for the EEI_Query_Filter methods being implemented
542
-     * The array is in the format:
543
-     * array(
544
-     *  {$field_name} => {$model_name}
545
-     * );
546
-     *
547
-     * @return array
548
-     * @since 4.9.0
549
-     */
550
-    protected function _expected_vars_for_query_inject()
551
-    {
552
-        return [
553
-            '_REG_ID' => 'Registration',
554
-            'ATT_ID'  => 'Attendee',
555
-            'ID'      => 'WP_User',
556
-            'TXN_ID'  => 'Transaction',
557
-            'EVT_ID'  => 'Event',
558
-        ];
559
-    }
560
-
561
-
562
-    /**
563
-     * This returns whether EEM_Message is in debug mode or not.
564
-     * Currently "debug mode" is used to control the handling of the EEM_Message::debug_only status when
565
-     * generating/sending messages. Debug mode can be set by either:
566
-     * 1. Sending in a value for the $set_debug argument
567
-     * 2. Defining `EE_DEBUG_MESSAGES` constant in wp-config.php
568
-     * 3. Overriding the above via the provided filter.
569
-     *
570
-     * @param bool|null $set_debug      If provided, then the debug mode will be set internally until reset via the
571
-     *                                  provided boolean. When no argument is provided (default null) then the debug
572
-     *                                  mode will be returned.
573
-     * @return bool         true means Messages is in debug mode.  false means messages system is not in debug mode.
574
-     */
575
-    public static function debug($set_debug = null)
576
-    {
577
-        static $is_debugging = null;
578
-
579
-        // initialize (use constant if set).
580
-        if (is_null($set_debug) && is_null($is_debugging)) {
581
-            $is_debugging = defined('EE_DEBUG_MESSAGES') && EE_DEBUG_MESSAGES;
582
-        }
583
-
584
-        if (! is_null($set_debug)) {
585
-            $is_debugging = filter_var($set_debug, FILTER_VALIDATE_BOOLEAN);
586
-        }
587
-
588
-        // return filtered value
589
-        return apply_filters('FHEE__EEM_Message__debug', $is_debugging);
590
-    }
591
-
592
-
593
-    /**
594
-     * Deletes old messages meeting certain criteria for removal from the database.
595
-     * By default, this will delete messages that:
596
-     * - are older than the value of the delete_threshold in months.
597
-     * - have a STS_ID other than EEM_Message::status_idle
598
-     *
599
-     * @param int $delete_threshold This integer will be used to set the boundary for what messages are deleted in
600
-     *                              months.
601
-     * @return bool|false|int Either the number of records affected or false if there was an error (you can call
602
-     *                              $wpdb->last_error to find out what the error was.
603
-     * @throws EE_Error
604
-     * @throws EE_Error
605
-     * @throws EE_Error
606
-     */
607
-    public function delete_old_messages($delete_threshold = 6)
608
-    {
609
-        $number_deleted = 0;
610
-        /**
611
-         * Allows code to change the boundary for what messages are kept.
612
-         * Uses the value of the `delete_threshold` variable by default.
613
-         *
614
-         * @param int $seconds seconds that will be subtracted from the timestamp for now.
615
-         * @return int
616
-         */
617
-        $time_to_leave_alone = absint(
618
-            apply_filters(
619
-                'FHEE__EEM_Message__delete_old_messages__time_to_leave_alone',
620
-                ((int) $delete_threshold) * MONTH_IN_SECONDS
621
-            )
622
-        );
623
-
624
-
625
-        /**
626
-         * Allows code to change what message stati are ignored when deleting.
627
-         * Defaults to only ignore EEM_Message::status_idle messages.
628
-         *
629
-         * @param string $message_stati_to_keep An array of message statuses that will be ignored when deleting.
630
-         */
631
-        $message_stati_to_keep = (array) apply_filters(
632
-            'FHEE__EEM_Message__delete_old_messages__message_stati_to_keep',
633
-            [
634
-                EEM_Message::status_idle,
635
-            ]
636
-        );
637
-
638
-        // first get all the ids of messages being deleted
639
-        $message_ids_to_delete = EEM_Message::instance()->get_col(
640
-            [
641
-                0       => [
642
-                    'STS_ID'       => ['NOT_IN', $message_stati_to_keep],
643
-                    'MSG_modified' => ['<', time() - $time_to_leave_alone],
644
-                ],
645
-                'limit' => apply_filters(
646
-                    'EEM_Message__delete_old_messages__limit',
647
-                    2000,
648
-                    $delete_threshold
649
-                ),
650
-            ]
651
-        );
652
-
653
-        if (! empty($message_ids_to_delete) && is_array($message_ids_to_delete)) {
654
-            global $wpdb;
655
-            $number_deleted = $wpdb->query(
656
-                '
26
+	/**
27
+	 * This priority indicates a message should be generated ASAP and queued for sending.
28
+	 *
29
+	 * @type
30
+	 */
31
+	const priority_medium = 20;
32
+
33
+
34
+	/**
35
+	 * This priority indicates a message should be queued for generating.
36
+	 *
37
+	 * @type int
38
+	 */
39
+	const priority_low = 30;
40
+
41
+
42
+	/**
43
+	 * indicates this message was sent at the time modified
44
+	 */
45
+	const status_sent = 'MSN';
46
+
47
+
48
+	/**
49
+	 * indicates this message is waiting to be sent
50
+	 */
51
+	const status_idle = 'MID';
52
+
53
+
54
+	/**
55
+	 * indicates an attempt was a made to send this message
56
+	 * at the scheduled time, but it failed at the time modified.  This differs from MDO status in that it will ALWAYS
57
+	 * appear to the end user.
58
+	 */
59
+	const status_failed = 'MFL';
60
+
61
+
62
+	/**
63
+	 * indicates the message has been flagged for resending (at the time modified).
64
+	 */
65
+	const status_resend = 'MRS';
66
+
67
+
68
+	/**
69
+	 * indicates the message has been flagged for generation but has not been generated yet.  Messages always start as
70
+	 * this status when added to the queue.
71
+	 */
72
+	const status_incomplete = 'MIC';
73
+
74
+
75
+	/**
76
+	 * Indicates everything was generated fine for the message, however, the messenger was unable to send.
77
+	 * This status means that its possible to retry sending the message.
78
+	 */
79
+	const status_retry = 'MRT';
80
+
81
+
82
+	/**
83
+	 * This is used for more informational messages that may not indicate anything is broken but still cannot be
84
+	 * generated or sent correctly. An example of a message that would get flagged this way would be when a not
85
+	 * approved message was queued for generation, but at time of generation, the attached registration(s) are
86
+	 * approved. So the message queued for generation is no longer valid.  Messages for this status will only persist
87
+	 * in the db and be viewable in the message activity list table when the messages system is in debug mode.
88
+	 *
89
+	 * @see EEM_Message::debug()
90
+	 */
91
+	const status_debug_only = 'MDO';
92
+
93
+
94
+	/**
95
+	 * This status is given to messages it is processed by the messenger send method.
96
+	 * Messages with this status should rarely be seen in the Message List table, but if they are, that's usually
97
+	 * indicative of a PHP timeout or memory limit issue.
98
+	 */
99
+	const status_messenger_executing = 'MEX';
100
+
101
+
102
+	/**
103
+	 * Private constructor to prevent direct creation.
104
+	 *
105
+	 * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings (and
106
+	 *                              any incoming timezone data that gets saved).  Note this just sends the timezone
107
+	 *                              info to the date time model field objects.  Default is null (and will be assumed
108
+	 *                              using the set timezone in the 'timezone_string' wp option)
109
+	 * @throws EE_Error
110
+	 */
111
+	protected function __construct(?string $timezone = '')
112
+	{
113
+		$this->singular_item = esc_html__('Message', 'event_espresso');
114
+		$this->plural_item   = esc_html__('Messages', 'event_espresso');
115
+
116
+		$this->_tables = [
117
+			'Message' => new EE_Primary_Table('esp_message', 'MSG_ID'),
118
+		];
119
+
120
+		$allowed_priority = [
121
+			self::priority_high   => esc_html__('high', 'event_espresso'),
122
+			self::priority_medium => esc_html__('medium', 'event_espresso'),
123
+			self::priority_low    => esc_html__('low', 'event_espresso'),
124
+		];
125
+
126
+		$this->_fields          = [
127
+			'Message' => [
128
+				'MSG_ID'             => new EE_Primary_Key_Int_Field(
129
+					'MSG_ID',
130
+					esc_html__('Message ID', 'event_espresso')
131
+				),
132
+				'MSG_token'          => new EE_Plain_Text_Field(
133
+					'MSG_token',
134
+					esc_html__(
135
+						'Unique Token used to represent this row in publicly viewable contexts (eg. a url).',
136
+						'event_espresso'
137
+					),
138
+					false,
139
+					EEH_URL::generate_unique_token()
140
+				),
141
+				'GRP_ID'             => new EE_Foreign_Key_Int_Field(
142
+					'GRP_ID',
143
+					esc_html__('Foreign key to the EEM_Message_Template_Group table.', 'event_espresso'),
144
+					true,
145
+					0,
146
+					'Message_Template_Group'
147
+				),
148
+				'TXN_ID'             => new EE_Foreign_Key_Int_Field(
149
+					'TXN_ID',
150
+					esc_html__(
151
+						'Foreign key to the related EE_Transaction.  This is required to give context for regenerating the specific message',
152
+						'event_espresso'
153
+					),
154
+					true,
155
+					0,
156
+					'Transaction'
157
+				),
158
+				'MSG_messenger'      => new EE_Plain_Text_Field(
159
+					'MSG_messenger',
160
+					esc_html__(
161
+						'Corresponds to the EE_messenger::name used to send this message. This will also be used to attempt any resending of the message.',
162
+						'event_espresso'
163
+					),
164
+					false,
165
+					'email'
166
+				),
167
+				'MSG_message_type'   => new EE_Plain_Text_Field(
168
+					'MSG_message_type',
169
+					esc_html__(
170
+						'Corresponds to the EE_message_type::name used to generate this message.',
171
+						'event_espresso'
172
+					),
173
+					false,
174
+					'receipt'
175
+				),
176
+				'MSG_context'        => new EE_Plain_Text_Field(
177
+					'MSG_context',
178
+					esc_html__('Context', 'event_espresso'),
179
+					false
180
+				),
181
+				'MSG_recipient_ID'   => new EE_Foreign_Key_Int_Field(
182
+					'MSG_recipient_ID',
183
+					esc_html__('Recipient ID', 'event_espresso'),
184
+					true,
185
+					null,
186
+					['Registration', 'Attendee', 'WP_User']
187
+				),
188
+				'MSG_recipient_type' => new EE_Any_Foreign_Model_Name_Field(
189
+					'MSG_recipient_type',
190
+					esc_html__('Recipient Type', 'event_espresso'),
191
+					true,
192
+					null,
193
+					['Registration', 'Attendee', 'WP_User']
194
+				),
195
+				'MSG_content'        => new EE_Maybe_Serialized_Text_Field(
196
+					'MSG_content',
197
+					esc_html__('Content', 'event_espresso'),
198
+					true,
199
+					''
200
+				),
201
+				'MSG_to'             => new EE_Maybe_Serialized_Text_Field(
202
+					'MSG_to',
203
+					esc_html__('Address To', 'event_espresso'),
204
+					true
205
+				),
206
+				'MSG_from'           => new EE_Maybe_Serialized_Text_Field(
207
+					'MSG_from',
208
+					esc_html__('Address From', 'event_espresso'),
209
+					true
210
+				),
211
+				'MSG_subject'        => new EE_Maybe_Serialized_Text_Field(
212
+					'MSG_subject',
213
+					esc_html__('Subject', 'event_espresso'),
214
+					true,
215
+					''
216
+				),
217
+				'MSG_priority'       => new EE_Enum_Integer_Field(
218
+					'MSG_priority',
219
+					esc_html__('Priority', 'event_espresso'),
220
+					false,
221
+					self::priority_low,
222
+					$allowed_priority
223
+				),
224
+				'STS_ID'             => new EE_Foreign_Key_String_Field(
225
+					'STS_ID',
226
+					esc_html__('Status', 'event_espresso'),
227
+					false,
228
+					self::status_incomplete,
229
+					'Status'
230
+				),
231
+				'MSG_created'        => new EE_Datetime_Field(
232
+					'MSG_created',
233
+					esc_html__('Created', 'event_espresso'),
234
+					false,
235
+					EE_Datetime_Field::now
236
+				),
237
+				'MSG_modified'       => new EE_Datetime_Field(
238
+					'MSG_modified',
239
+					esc_html__('Modified', 'event_espresso'),
240
+					true,
241
+					EE_Datetime_Field::now
242
+				),
243
+			],
244
+		];
245
+		$this->_model_relations = [
246
+			'Attendee'               => new EE_Belongs_To_Any_Relation(),
247
+			'Registration'           => new EE_Belongs_To_Any_Relation(),
248
+			'WP_User'                => new EE_Belongs_To_Any_Relation(),
249
+			'Message_Template_Group' => new EE_Belongs_To_Relation(),
250
+			'Transaction'            => new EE_Belongs_To_Relation(),
251
+		];
252
+		parent::__construct($timezone);
253
+	}
254
+
255
+
256
+	/**
257
+	 * @return EE_Message
258
+	 * @throws EE_Error
259
+	 */
260
+	public function create_default_object()
261
+	{
262
+		/** @type EE_Message $message */
263
+		$message = parent::create_default_object();
264
+		if ($message instanceof EE_Message) {
265
+			return EE_Message_Factory::set_messenger_and_message_type($message);
266
+		}
267
+		return null;
268
+	}
269
+
270
+
271
+	/**
272
+	 * @param mixed $cols_n_values
273
+	 * @return EE_Message
274
+	 * @throws EE_Error
275
+	 * @throws EE_Error
276
+	 */
277
+	public function instantiate_class_from_array_or_object($cols_n_values)
278
+	{
279
+		/** @type EE_Message $message */
280
+		$message = parent::instantiate_class_from_array_or_object($cols_n_values);
281
+		if ($message instanceof EE_Message) {
282
+			return EE_Message_Factory::set_messenger_and_message_type($message);
283
+		}
284
+		return null;
285
+	}
286
+
287
+
288
+	/**
289
+	 * Returns whether or not a message of that type was sent for a given attendee.
290
+	 *
291
+	 * @param EE_Attendee|int $attendee
292
+	 * @param string          $message_type the message type slug
293
+	 * @return boolean
294
+	 * @throws EE_Error
295
+	 * @throws EE_Error
296
+	 * @throws EE_Error
297
+	 */
298
+	public function message_sent_for_attendee($attendee, $message_type)
299
+	{
300
+		$attendee_ID = EEM_Attendee::instance()->ensure_is_ID($attendee);
301
+		return $this->exists(
302
+			[
303
+				[
304
+					'Attendee.ATT_ID'  => $attendee_ID,
305
+					'MSG_message_type' => $message_type,
306
+					'STS_ID'           => ['IN', $this->stati_indicating_sent()],
307
+				],
308
+			]
309
+		);
310
+	}
311
+
312
+
313
+	/**
314
+	 * Returns whether or not a message of that type was sent for a given registration
315
+	 *
316
+	 * @param EE_Registration|int $registration
317
+	 * @param string              $message_type the message type slug
318
+	 * @return boolean
319
+	 * @throws EE_Error
320
+	 * @throws EE_Error
321
+	 * @throws EE_Error
322
+	 */
323
+	public function message_sent_for_registration($registration, $message_type)
324
+	{
325
+		$registrationID = EEM_Registration::instance()->ensure_is_ID($registration);
326
+		return $this->exists(
327
+			[
328
+				[
329
+					'Registration.REG_ID' => $registrationID,
330
+					'MSG_message_type'    => $message_type,
331
+					'STS_ID'              => ['IN', $this->stati_indicating_sent()],
332
+				],
333
+			]
334
+		);
335
+	}
336
+
337
+
338
+	/**
339
+	 * This retrieves an EE_Message object from the db matching the given token string.
340
+	 *
341
+	 * @param string $token
342
+	 * @return EE_Message
343
+	 * @throws EE_Error
344
+	 */
345
+	public function get_one_by_token($token)
346
+	{
347
+		return $this->get_one(
348
+			[
349
+				[
350
+					'MSG_token' => $token,
351
+				],
352
+			]
353
+		);
354
+	}
355
+
356
+
357
+	/**
358
+	 * Returns stati that indicate the message HAS been sent
359
+	 *
360
+	 * @return array of strings for possible stati
361
+	 */
362
+	public function stati_indicating_sent()
363
+	{
364
+		return apply_filters('FHEE__EEM_Message__stati_indicating_sent', [self::status_sent]);
365
+	}
366
+
367
+
368
+	/**
369
+	 * Returns stati that indicate the message is waiting to be sent.
370
+	 *
371
+	 * @return array of strings for possible stati.
372
+	 */
373
+	public function stati_indicating_to_send()
374
+	{
375
+		return apply_filters(
376
+			'FHEE__EEM_Message__stati_indicating_to_send',
377
+			[self::status_idle, self::status_resend]
378
+		);
379
+	}
380
+
381
+
382
+	/**
383
+	 * Returns stati that indicate the message has failed sending
384
+	 *
385
+	 * @return array  array of strings for possible stati.
386
+	 */
387
+	public function stati_indicating_failed_sending()
388
+	{
389
+		$failed_stati = [
390
+			self::status_failed,
391
+			self::status_retry,
392
+			self::status_messenger_executing,
393
+		];
394
+		// if WP_DEBUG is set, then let's include debug_only fails
395
+		if (WP_DEBUG) {
396
+			$failed_stati[] = self::status_debug_only;
397
+		}
398
+		return apply_filters('FHEE__EEM_Message__stati_indicating_failed_sending', $failed_stati);
399
+	}
400
+
401
+
402
+	/**
403
+	 * Returns filterable array of all EEM_Message statuses.
404
+	 *
405
+	 * @return array
406
+	 */
407
+	public function all_statuses()
408
+	{
409
+		return apply_filters(
410
+			'FHEE__EEM_Message__all_statuses',
411
+			[
412
+				EEM_Message::status_sent,
413
+				EEM_Message::status_incomplete,
414
+				EEM_Message::status_idle,
415
+				EEM_Message::status_resend,
416
+				EEM_Message::status_retry,
417
+				EEM_Message::status_failed,
418
+				EEM_Message::status_messenger_executing,
419
+				EEM_Message::status_debug_only,
420
+			]
421
+		);
422
+	}
423
+
424
+
425
+	/**
426
+	 * Detects any specific query variables in the request and uses those to setup appropriate
427
+	 * filter for any queries.
428
+	 *
429
+	 * @return array
430
+	 */
431
+	public function filter_by_query_params()
432
+	{
433
+		/** @var RequestInterface $request */
434
+		$request = EEM_Base::$loader->getShared(RequestInterface::class);
435
+		// expected possible query_vars, the key in this array matches an expected key in the request,
436
+		// the value, matches the corresponding EEM_Base child reference.
437
+		$expected_vars   = $this->_expected_vars_for_query_inject();
438
+		$query_params[0] = [];
439
+		foreach ($expected_vars as $request_key => $model_name) {
440
+			$request_value = $request->getRequestParam($request_key);
441
+			if ($request_value) {
442
+				// special case
443
+				switch ($request_key) {
444
+					case '_REG_ID':
445
+						$query_params[0]['AND**filter_by']['OR**filter_by_REG_ID'] = [
446
+							'Transaction.Registration.REG_ID' => $request_value,
447
+						];
448
+						break;
449
+					case 'EVT_ID':
450
+						$query_params[0]['AND**filter_by']['OR**filter_by_EVT_ID'] = [
451
+							'Transaction.Registration.EVT_ID' => $request_value,
452
+						];
453
+						break;
454
+					default:
455
+						$query_params[0]['AND**filter_by'][ 'OR**filter_by_' . $request_key ][ $model_name . '.' . $request_key ] =
456
+							$request_value;
457
+						break;
458
+				}
459
+			}
460
+		}
461
+		return $query_params;
462
+	}
463
+
464
+
465
+	/**
466
+	 * @return string
467
+	 * @throws EE_Error
468
+	 * @throws ReflectionException
469
+	 */
470
+	public function get_pretty_label_for_results()
471
+	{
472
+		/** @var RequestInterface $request */
473
+		$request       = EEM_Base::$loader->getShared(RequestInterface::class);
474
+		$expected_vars = $this->_expected_vars_for_query_inject();
475
+		$pretty_label  = '';
476
+		$label_parts   = [];
477
+		foreach ($expected_vars as $request_key => $model_name) {
478
+			$model_name        = strpos($model_name, 'EEM_', true) === 0 ? $model_name : "EEM_{$model_name}";
479
+			$model             = EEM_Base::$loader->getShared($model_name);
480
+			$model_field_value = $request->getRequestParam($request_key);
481
+			if ($model instanceof EEM_Base && $model_field_value !== '') {
482
+				switch ($request_key) {
483
+					case '_REG_ID':
484
+						$label_parts[] = sprintf(
485
+							esc_html__('Registration with the ID: %s', 'event_espresso'),
486
+							$model_field_value
487
+						);
488
+						break;
489
+					case 'ATT_ID':
490
+						/** @var EE_Attendee $attendee */
491
+						$attendee      = $model->get_one_by_ID($model_field_value);
492
+						$label_parts[] = $attendee instanceof EE_Attendee
493
+							? sprintf(esc_html__('Attendee %s', 'event_espresso'), $attendee->full_name())
494
+							: sprintf(esc_html__('Attendee ID: %s', 'event_espresso'), $model_field_value);
495
+						break;
496
+					case 'ID':
497
+						/** @var EE_WP_User $wpUser */
498
+						$wpUser        = $model->get_one_by_ID($model_field_value);
499
+						$label_parts[] = $wpUser instanceof EE_WP_User
500
+							? sprintf(esc_html__('WP User: %s', 'event_espresso'), $wpUser->name())
501
+							: sprintf(esc_html__('WP User ID: %s', 'event_espresso'), $model_field_value);
502
+						break;
503
+					case 'TXN_ID':
504
+						$label_parts[] = sprintf(
505
+							esc_html__('Transaction with the ID: %s', 'event_espresso'),
506
+							$model_field_value
507
+						);
508
+						break;
509
+					case 'EVT_ID':
510
+						/** @var EE_Event $Event */
511
+						$Event         = $model->get_one_by_ID($model_field_value);
512
+						$label_parts[] = $Event instanceof EE_Event
513
+							? sprintf(esc_html__('for the Event: %s', 'event_espresso'), $Event->name())
514
+							: sprintf(esc_html__('for the Event with ID: %s', 'event_espresso'), $model_field_value);
515
+						break;
516
+				}
517
+			}
518
+		}
519
+
520
+		if ($label_parts) {
521
+			// prepend to the last element of $label_parts an "and".
522
+			if (count($label_parts) > 1) {
523
+				$label_parts_index_to_prepend                 = count($label_parts) - 1;
524
+				$label_parts[ $label_parts_index_to_prepend ] = 'and' . $label_parts[ $label_parts_index_to_prepend ];
525
+			}
526
+
527
+			$pretty_label .= sprintf(
528
+				esc_html_x(
529
+					'Showing messages for %s',
530
+					'A label for the messages returned in a query that are filtered by items in the query. This could be Transaction, Event, Attendee, Registration, or WP_User.',
531
+					'event_espresso'
532
+				),
533
+				implode(', ', $label_parts)
534
+			);
535
+		}
536
+		return $pretty_label;
537
+	}
538
+
539
+
540
+	/**
541
+	 * This returns the array of expected variables for the EEI_Query_Filter methods being implemented
542
+	 * The array is in the format:
543
+	 * array(
544
+	 *  {$field_name} => {$model_name}
545
+	 * );
546
+	 *
547
+	 * @return array
548
+	 * @since 4.9.0
549
+	 */
550
+	protected function _expected_vars_for_query_inject()
551
+	{
552
+		return [
553
+			'_REG_ID' => 'Registration',
554
+			'ATT_ID'  => 'Attendee',
555
+			'ID'      => 'WP_User',
556
+			'TXN_ID'  => 'Transaction',
557
+			'EVT_ID'  => 'Event',
558
+		];
559
+	}
560
+
561
+
562
+	/**
563
+	 * This returns whether EEM_Message is in debug mode or not.
564
+	 * Currently "debug mode" is used to control the handling of the EEM_Message::debug_only status when
565
+	 * generating/sending messages. Debug mode can be set by either:
566
+	 * 1. Sending in a value for the $set_debug argument
567
+	 * 2. Defining `EE_DEBUG_MESSAGES` constant in wp-config.php
568
+	 * 3. Overriding the above via the provided filter.
569
+	 *
570
+	 * @param bool|null $set_debug      If provided, then the debug mode will be set internally until reset via the
571
+	 *                                  provided boolean. When no argument is provided (default null) then the debug
572
+	 *                                  mode will be returned.
573
+	 * @return bool         true means Messages is in debug mode.  false means messages system is not in debug mode.
574
+	 */
575
+	public static function debug($set_debug = null)
576
+	{
577
+		static $is_debugging = null;
578
+
579
+		// initialize (use constant if set).
580
+		if (is_null($set_debug) && is_null($is_debugging)) {
581
+			$is_debugging = defined('EE_DEBUG_MESSAGES') && EE_DEBUG_MESSAGES;
582
+		}
583
+
584
+		if (! is_null($set_debug)) {
585
+			$is_debugging = filter_var($set_debug, FILTER_VALIDATE_BOOLEAN);
586
+		}
587
+
588
+		// return filtered value
589
+		return apply_filters('FHEE__EEM_Message__debug', $is_debugging);
590
+	}
591
+
592
+
593
+	/**
594
+	 * Deletes old messages meeting certain criteria for removal from the database.
595
+	 * By default, this will delete messages that:
596
+	 * - are older than the value of the delete_threshold in months.
597
+	 * - have a STS_ID other than EEM_Message::status_idle
598
+	 *
599
+	 * @param int $delete_threshold This integer will be used to set the boundary for what messages are deleted in
600
+	 *                              months.
601
+	 * @return bool|false|int Either the number of records affected or false if there was an error (you can call
602
+	 *                              $wpdb->last_error to find out what the error was.
603
+	 * @throws EE_Error
604
+	 * @throws EE_Error
605
+	 * @throws EE_Error
606
+	 */
607
+	public function delete_old_messages($delete_threshold = 6)
608
+	{
609
+		$number_deleted = 0;
610
+		/**
611
+		 * Allows code to change the boundary for what messages are kept.
612
+		 * Uses the value of the `delete_threshold` variable by default.
613
+		 *
614
+		 * @param int $seconds seconds that will be subtracted from the timestamp for now.
615
+		 * @return int
616
+		 */
617
+		$time_to_leave_alone = absint(
618
+			apply_filters(
619
+				'FHEE__EEM_Message__delete_old_messages__time_to_leave_alone',
620
+				((int) $delete_threshold) * MONTH_IN_SECONDS
621
+			)
622
+		);
623
+
624
+
625
+		/**
626
+		 * Allows code to change what message stati are ignored when deleting.
627
+		 * Defaults to only ignore EEM_Message::status_idle messages.
628
+		 *
629
+		 * @param string $message_stati_to_keep An array of message statuses that will be ignored when deleting.
630
+		 */
631
+		$message_stati_to_keep = (array) apply_filters(
632
+			'FHEE__EEM_Message__delete_old_messages__message_stati_to_keep',
633
+			[
634
+				EEM_Message::status_idle,
635
+			]
636
+		);
637
+
638
+		// first get all the ids of messages being deleted
639
+		$message_ids_to_delete = EEM_Message::instance()->get_col(
640
+			[
641
+				0       => [
642
+					'STS_ID'       => ['NOT_IN', $message_stati_to_keep],
643
+					'MSG_modified' => ['<', time() - $time_to_leave_alone],
644
+				],
645
+				'limit' => apply_filters(
646
+					'EEM_Message__delete_old_messages__limit',
647
+					2000,
648
+					$delete_threshold
649
+				),
650
+			]
651
+		);
652
+
653
+		if (! empty($message_ids_to_delete) && is_array($message_ids_to_delete)) {
654
+			global $wpdb;
655
+			$number_deleted = $wpdb->query(
656
+				'
657 657
                 DELETE
658 658
                 FROM ' . $this->table() . '
659 659
                 WHERE
660 660
                     MSG_ID IN (' . implode(",", $message_ids_to_delete) . ')
661 661
             '
662
-            );
663
-        }
664
-
665
-        /**
666
-         * This will get called if the number of records deleted 0 or greater.  So a successful deletion is one where
667
-         * there were no errors.  An unsuccessful deletion is where there were errors.  Keep that in mind for the actions
668
-         * below.
669
-         */
670
-        if ($number_deleted !== false) {
671
-            do_action(
672
-                'AHEE__EEM_Message__delete_old_messages__after_successful_deletion',
673
-                $message_ids_to_delete,
674
-                $number_deleted
675
-            );
676
-        } else {
677
-            do_action(
678
-                'AHEE__EEM_Message__delete_old_messages__after_deletion_fail',
679
-                $message_ids_to_delete,
680
-                $number_deleted
681
-            );
682
-        }
683
-        return $number_deleted;
684
-    }
662
+			);
663
+		}
664
+
665
+		/**
666
+		 * This will get called if the number of records deleted 0 or greater.  So a successful deletion is one where
667
+		 * there were no errors.  An unsuccessful deletion is where there were errors.  Keep that in mind for the actions
668
+		 * below.
669
+		 */
670
+		if ($number_deleted !== false) {
671
+			do_action(
672
+				'AHEE__EEM_Message__delete_old_messages__after_successful_deletion',
673
+				$message_ids_to_delete,
674
+				$number_deleted
675
+			);
676
+		} else {
677
+			do_action(
678
+				'AHEE__EEM_Message__delete_old_messages__after_deletion_fail',
679
+				$message_ids_to_delete,
680
+				$number_deleted
681
+			);
682
+		}
683
+		return $number_deleted;
684
+	}
685 685
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
             self::priority_low    => esc_html__('low', 'event_espresso'),
124 124
         ];
125 125
 
126
-        $this->_fields          = [
126
+        $this->_fields = [
127 127
             'Message' => [
128 128
                 'MSG_ID'             => new EE_Primary_Key_Int_Field(
129 129
                     'MSG_ID',
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
                         ];
453 453
                         break;
454 454
                     default:
455
-                        $query_params[0]['AND**filter_by'][ 'OR**filter_by_' . $request_key ][ $model_name . '.' . $request_key ] =
455
+                        $query_params[0]['AND**filter_by']['OR**filter_by_'.$request_key][$model_name.'.'.$request_key] =
456 456
                             $request_value;
457 457
                         break;
458 458
                 }
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
             // prepend to the last element of $label_parts an "and".
522 522
             if (count($label_parts) > 1) {
523 523
                 $label_parts_index_to_prepend                 = count($label_parts) - 1;
524
-                $label_parts[ $label_parts_index_to_prepend ] = 'and' . $label_parts[ $label_parts_index_to_prepend ];
524
+                $label_parts[$label_parts_index_to_prepend] = 'and'.$label_parts[$label_parts_index_to_prepend];
525 525
             }
526 526
 
527 527
             $pretty_label .= sprintf(
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
             $is_debugging = defined('EE_DEBUG_MESSAGES') && EE_DEBUG_MESSAGES;
582 582
         }
583 583
 
584
-        if (! is_null($set_debug)) {
584
+        if ( ! is_null($set_debug)) {
585 585
             $is_debugging = filter_var($set_debug, FILTER_VALIDATE_BOOLEAN);
586 586
         }
587 587
 
@@ -650,14 +650,14 @@  discard block
 block discarded – undo
650 650
             ]
651 651
         );
652 652
 
653
-        if (! empty($message_ids_to_delete) && is_array($message_ids_to_delete)) {
653
+        if ( ! empty($message_ids_to_delete) && is_array($message_ids_to_delete)) {
654 654
             global $wpdb;
655 655
             $number_deleted = $wpdb->query(
656 656
                 '
657 657
                 DELETE
658
-                FROM ' . $this->table() . '
658
+                FROM ' . $this->table().'
659 659
                 WHERE
660
-                    MSG_ID IN (' . implode(",", $message_ids_to_delete) . ')
660
+                    MSG_ID IN (' . implode(",", $message_ids_to_delete).')
661 661
             '
662 662
             );
663 663
         }
Please login to merge, or discard this patch.
core/db_models/helpers/EE_Secondary_Table.php 1 patch
Indentation   +153 added lines, -153 removed lines patch added patch discarded remove patch
@@ -8,157 +8,157 @@
 block discarded – undo
8 8
  */
9 9
 class EE_Secondary_Table extends EE_Table_Base
10 10
 {
11
-    protected ?string $_extra_join_conditions;
12
-
13
-    protected ?string $_fk_on_table;
14
-
15
-    protected ?EE_Table_Base $_table_to_join_with = null;
16
-
17
-
18
-    /**
19
-     * @param string      $table_name            with or without wpdb prefix
20
-     * @param string      $pk_column             name of primary key column on THIS table
21
-     * @param string|null $fk_column             the name of the COLUMN that is a foreign key to the primary table's
22
-     *                                           primary key
23
-     * @param string|null $extra_join_conditions string for additional SQL to add onto the join statement's ON condition
24
-     * @param boolean     $global                whether the table is "global" as in there is only 1 table on an entire
25
-     *                                           multisite install, or whether each site on a multisite installation ha
26
-     *                                           a copy of this table
27
-     * @global WPDB       $wpdb
28
-     */
29
-    public function __construct(
30
-        string $table_name,
31
-        string $pk_column,
32
-        ?string $fk_column = null,
33
-        ?string $extra_join_conditions = null,
34
-        bool $global = false
35
-    ) {
36
-        $this->_fk_on_table           = $fk_column;
37
-        $this->_extra_join_conditions = $extra_join_conditions;
38
-        parent::__construct($table_name, $pk_column, $global);
39
-    }
40
-
41
-
42
-    public function get_fk_on_table(): ?string
43
-    {
44
-        return $this->_fk_on_table;
45
-    }
46
-
47
-
48
-    public function _construct_finalize_set_table_to_join_with(EE_Table_Base $table)
49
-    {
50
-        $this->_table_to_join_with = $table;
51
-    }
52
-
53
-
54
-    /**
55
-     * @return string of sql like "Event.post_type = 'event'", which gets added to
56
-     * the end of the join statement with the primary table
57
-     */
58
-    public function get_extra_join_conditions(): ?string
59
-    {
60
-        return $this->_extra_join_conditions;
61
-    }
62
-
63
-
64
-    /**
65
-     * @return EE_Table_Base|null
66
-     */
67
-    public function get_table_to_join_with(): ?EE_Table_Base
68
-    {
69
-        return $this->_table_to_join_with;
70
-    }
71
-
72
-
73
-    /**
74
-     * creates join statement FROM primary table
75
-     * gets SQL like "LEFT JOIN table_name AS table_alias ON other_table_alias.pk = table_alias.fk
76
-     *
77
-     * @param string $primary_table_alias_with_model_chain_prefix allows us to set special conditions on the
78
-     *                                                            $table_name portion of the join query
79
-     *                                                            (i.e. doing a sub-query)
80
-     * @return string of SQL
81
-     * @throws EE_Error
82
-     */
83
-    public function get_join_sql($primary_table_alias_with_model_chain_prefix)
84
-    {
85
-        $table_name            = $this->get_table_name();
86
-        $secondary_table_alias =
87
-            EE_Model_Parser::get_prefix_from_table_alias_with_model_relation_chain_prefix(
88
-                $primary_table_alias_with_model_chain_prefix
89
-            ) . $this->get_table_alias();
90
-        $other_table_pk        = $this->get_table_to_join_with()->get_pk_column();
91
-        $fk                    = $this->get_fk_on_table();
92
-        $join_sql              =
93
-            " LEFT JOIN $table_name AS $secondary_table_alias ON $primary_table_alias_with_model_chain_prefix.$other_table_pk = $secondary_table_alias.$fk ";
94
-        if ($this->get_extra_join_conditions()) {
95
-            $join_sql .= "AND " . $this->get_extra_join_conditions();
96
-        }
97
-        return $join_sql;
98
-    }
99
-
100
-
101
-    /**
102
-     * Produces join SQL like get_join_sql, except instead of joining the primary table to the
103
-     * secondary table, does the inverse: joins the secondary table to the primary one. Eg, instead of
104
-     * " LEFT JOIN secondary_table_table AS Secondary ON ..." like get_join_sql, this function returns
105
-     * " LEFT JOIN primary_table AS Primary ON ...".
106
-     * This is useful if the secondary table is already included in the SQL, but the primary table is not yet.
107
-     *
108
-     * @return string
109
-     * @throws EE_Error
110
-     */
111
-    public function get_inverse_join_sql($secondary_table_alias_with_model_chain_prefix)
112
-    {
113
-        $primary_table_name  = $this->get_table_to_join_with()->get_table_name();
114
-        $primary_table_alias =
115
-            EE_Model_Parser::get_prefix_from_table_alias_with_model_relation_chain_prefix(
116
-                $secondary_table_alias_with_model_chain_prefix
117
-            ) . $this->get_table_to_join_with()->get_table_alias();
118
-        $primary_table_pk    = $this->get_table_to_join_with()->get_pk_column();// $this->get_pk_column();
119
-        $fk                  = $this->get_fk_on_table();
120
-        $join_sql            =
121
-            " LEFT JOIN $primary_table_name AS $primary_table_alias ON $primary_table_alias.$primary_table_pk = $secondary_table_alias_with_model_chain_prefix.$fk ";
122
-        if ($this->get_extra_join_conditions()) {
123
-            $join_sql .= "AND " . $this->get_extra_join_conditions();
124
-        }
125
-        return $join_sql;
126
-    }
127
-
128
-
129
-    /**
130
-     * This prepares the join on the other table using a select with a internal limit.
131
-     *
132
-     * @param array|string $limit limit
133
-     * @return string             SQL to return
134
-     * @throws EE_Error
135
-     */
136
-    public function get_select_join_limit_join($limit)
137
-    {
138
-        // first get the select
139
-        $select   = $this->get_select_join_limit($limit);
140
-        return $this->get_join_sql($select);
141
-    }
142
-
143
-
144
-    /**
145
-     * @throws EE_Error
146
-     */
147
-    public function get_fully_qualified_fk_column()
148
-    {
149
-        $table_alias = $this->get_table_alias();
150
-        $fk          = $this->get_fk_on_table();
151
-        return $table_alias . '.' . $fk;
152
-    }
153
-
154
-
155
-    /**
156
-     * @throws EE_Error
157
-     */
158
-    public function get_fully_qualified_pk_on_fk_table()
159
-    {
160
-        $table_alias = $this->get_table_to_join_with()->get_table_alias();
161
-        $pk          = $this->get_table_to_join_with()->get_pk_column();
162
-        return $table_alias . '.' . $pk;
163
-    }
11
+	protected ?string $_extra_join_conditions;
12
+
13
+	protected ?string $_fk_on_table;
14
+
15
+	protected ?EE_Table_Base $_table_to_join_with = null;
16
+
17
+
18
+	/**
19
+	 * @param string      $table_name            with or without wpdb prefix
20
+	 * @param string      $pk_column             name of primary key column on THIS table
21
+	 * @param string|null $fk_column             the name of the COLUMN that is a foreign key to the primary table's
22
+	 *                                           primary key
23
+	 * @param string|null $extra_join_conditions string for additional SQL to add onto the join statement's ON condition
24
+	 * @param boolean     $global                whether the table is "global" as in there is only 1 table on an entire
25
+	 *                                           multisite install, or whether each site on a multisite installation ha
26
+	 *                                           a copy of this table
27
+	 * @global WPDB       $wpdb
28
+	 */
29
+	public function __construct(
30
+		string $table_name,
31
+		string $pk_column,
32
+		?string $fk_column = null,
33
+		?string $extra_join_conditions = null,
34
+		bool $global = false
35
+	) {
36
+		$this->_fk_on_table           = $fk_column;
37
+		$this->_extra_join_conditions = $extra_join_conditions;
38
+		parent::__construct($table_name, $pk_column, $global);
39
+	}
40
+
41
+
42
+	public function get_fk_on_table(): ?string
43
+	{
44
+		return $this->_fk_on_table;
45
+	}
46
+
47
+
48
+	public function _construct_finalize_set_table_to_join_with(EE_Table_Base $table)
49
+	{
50
+		$this->_table_to_join_with = $table;
51
+	}
52
+
53
+
54
+	/**
55
+	 * @return string of sql like "Event.post_type = 'event'", which gets added to
56
+	 * the end of the join statement with the primary table
57
+	 */
58
+	public function get_extra_join_conditions(): ?string
59
+	{
60
+		return $this->_extra_join_conditions;
61
+	}
62
+
63
+
64
+	/**
65
+	 * @return EE_Table_Base|null
66
+	 */
67
+	public function get_table_to_join_with(): ?EE_Table_Base
68
+	{
69
+		return $this->_table_to_join_with;
70
+	}
71
+
72
+
73
+	/**
74
+	 * creates join statement FROM primary table
75
+	 * gets SQL like "LEFT JOIN table_name AS table_alias ON other_table_alias.pk = table_alias.fk
76
+	 *
77
+	 * @param string $primary_table_alias_with_model_chain_prefix allows us to set special conditions on the
78
+	 *                                                            $table_name portion of the join query
79
+	 *                                                            (i.e. doing a sub-query)
80
+	 * @return string of SQL
81
+	 * @throws EE_Error
82
+	 */
83
+	public function get_join_sql($primary_table_alias_with_model_chain_prefix)
84
+	{
85
+		$table_name            = $this->get_table_name();
86
+		$secondary_table_alias =
87
+			EE_Model_Parser::get_prefix_from_table_alias_with_model_relation_chain_prefix(
88
+				$primary_table_alias_with_model_chain_prefix
89
+			) . $this->get_table_alias();
90
+		$other_table_pk        = $this->get_table_to_join_with()->get_pk_column();
91
+		$fk                    = $this->get_fk_on_table();
92
+		$join_sql              =
93
+			" LEFT JOIN $table_name AS $secondary_table_alias ON $primary_table_alias_with_model_chain_prefix.$other_table_pk = $secondary_table_alias.$fk ";
94
+		if ($this->get_extra_join_conditions()) {
95
+			$join_sql .= "AND " . $this->get_extra_join_conditions();
96
+		}
97
+		return $join_sql;
98
+	}
99
+
100
+
101
+	/**
102
+	 * Produces join SQL like get_join_sql, except instead of joining the primary table to the
103
+	 * secondary table, does the inverse: joins the secondary table to the primary one. Eg, instead of
104
+	 * " LEFT JOIN secondary_table_table AS Secondary ON ..." like get_join_sql, this function returns
105
+	 * " LEFT JOIN primary_table AS Primary ON ...".
106
+	 * This is useful if the secondary table is already included in the SQL, but the primary table is not yet.
107
+	 *
108
+	 * @return string
109
+	 * @throws EE_Error
110
+	 */
111
+	public function get_inverse_join_sql($secondary_table_alias_with_model_chain_prefix)
112
+	{
113
+		$primary_table_name  = $this->get_table_to_join_with()->get_table_name();
114
+		$primary_table_alias =
115
+			EE_Model_Parser::get_prefix_from_table_alias_with_model_relation_chain_prefix(
116
+				$secondary_table_alias_with_model_chain_prefix
117
+			) . $this->get_table_to_join_with()->get_table_alias();
118
+		$primary_table_pk    = $this->get_table_to_join_with()->get_pk_column();// $this->get_pk_column();
119
+		$fk                  = $this->get_fk_on_table();
120
+		$join_sql            =
121
+			" LEFT JOIN $primary_table_name AS $primary_table_alias ON $primary_table_alias.$primary_table_pk = $secondary_table_alias_with_model_chain_prefix.$fk ";
122
+		if ($this->get_extra_join_conditions()) {
123
+			$join_sql .= "AND " . $this->get_extra_join_conditions();
124
+		}
125
+		return $join_sql;
126
+	}
127
+
128
+
129
+	/**
130
+	 * This prepares the join on the other table using a select with a internal limit.
131
+	 *
132
+	 * @param array|string $limit limit
133
+	 * @return string             SQL to return
134
+	 * @throws EE_Error
135
+	 */
136
+	public function get_select_join_limit_join($limit)
137
+	{
138
+		// first get the select
139
+		$select   = $this->get_select_join_limit($limit);
140
+		return $this->get_join_sql($select);
141
+	}
142
+
143
+
144
+	/**
145
+	 * @throws EE_Error
146
+	 */
147
+	public function get_fully_qualified_fk_column()
148
+	{
149
+		$table_alias = $this->get_table_alias();
150
+		$fk          = $this->get_fk_on_table();
151
+		return $table_alias . '.' . $fk;
152
+	}
153
+
154
+
155
+	/**
156
+	 * @throws EE_Error
157
+	 */
158
+	public function get_fully_qualified_pk_on_fk_table()
159
+	{
160
+		$table_alias = $this->get_table_to_join_with()->get_table_alias();
161
+		$pk          = $this->get_table_to_join_with()->get_pk_column();
162
+		return $table_alias . '.' . $pk;
163
+	}
164 164
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Ticket.model.php 2 patches
Indentation   +481 added lines, -481 removed lines patch added patch discarded remove patch
@@ -13,485 +13,485 @@
 block discarded – undo
13 13
  */
14 14
 class EEM_Ticket extends EEM_Soft_Delete_Base
15 15
 {
16
-    /**
17
-     * the following constants define where tickets can be viewed throughout the UI
18
-     *  TICKET_VISIBILITY_NONE          - will not be displayed anywhere
19
-     *  TICKET_VISIBILITY_PUBLIC        - basically displayed everywhere
20
-     *  TICKET_VISIBILITY_MEMBERS_ONLY  - displayed to any logged-in user
21
-     *  TICKET_VISIBILITY_ADMINS_ONLY   - displayed to any logged-in user that is an admin
22
-     *  TICKET_VISIBILITY_ADMIN_UI_ONLY - only displayed in the admin, never publicly
23
-     */
24
-    public const TICKET_VISIBILITY_NONE_KEY            = 'NONE';
25
-
26
-    public const TICKET_VISIBILITY_NONE_VALUE          = 0;
27
-
28
-    public const TICKET_VISIBILITY_PUBLIC_KEY          = 'PUBLIC';
29
-
30
-    public const TICKET_VISIBILITY_PUBLIC_VALUE        = 100;
31
-
32
-    public const TICKET_VISIBILITY_MEMBERS_ONLY_KEY    = 'MEMBERS_ONLY';
33
-
34
-    public const TICKET_VISIBILITY_MEMBERS_ONLY_VALUE  = 200;
35
-
36
-    public const TICKET_VISIBILITY_ADMINS_ONLY_KEY     = 'ADMINS_ONLY';
37
-
38
-    public const TICKET_VISIBILITY_ADMINS_ONLY_VALUE   = 300;
39
-
40
-    public const TICKET_VISIBILITY_ADMIN_UI_ONLY_KEY   = 'ADMIN_UI_ONLY';
41
-
42
-    public const TICKET_VISIBILITY_ADMIN_UI_ONLY_VALUE = 400;
43
-
44
-
45
-    /**
46
-     * defines where tickets can be viewed throughout the UI
47
-     *
48
-     * @var array
49
-     */
50
-    private $ticket_visibility;
51
-
52
-    protected static ?EEM_Ticket $_instance = null;
53
-
54
-
55
-    /**
56
-     * private constructor to prevent direct creation
57
-     *
58
-     * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings
59
-     *                              (and any incoming timezone data that gets saved).
60
-     *                              Note this just sends the timezone info to the date time model field objects.
61
-     *                              Default is NULL
62
-     *                              (and will be assumed using the set timezone in the 'timezone_string' wp option)
63
-     * @throws EE_Error
64
-     * @throws ReflectionException
65
-     */
66
-    protected function __construct(?string $timezone = '')
67
-    {
68
-        $this->singular_item = esc_html__('Ticket', 'event_espresso');
69
-        $this->plural_item   = esc_html__('Tickets', 'event_espresso');
70
-        $this->_tables       = [
71
-            'Ticket' => new EE_Primary_Table('esp_ticket', 'TKT_ID'),
72
-        ];
73
-        $this->parseTicketVisibilityOptions();
74
-        $this->_fields          = [
75
-            'Ticket' => [
76
-                'TKT_ID'                => new EE_Primary_Key_Int_Field(
77
-                    'TKT_ID',
78
-                    esc_html__('Ticket ID', 'event_espresso')
79
-                ),
80
-                'TTM_ID'                => new EE_Foreign_Key_Int_Field(
81
-                    'TTM_ID',
82
-                    esc_html__('Ticket Template ID', 'event_espresso'),
83
-                    false,
84
-                    0,
85
-                    'Ticket_Template'
86
-                ),
87
-                'TKT_name'              => new EE_Plain_Text_Field(
88
-                    'TKT_name',
89
-                    esc_html__('Ticket Name', 'event_espresso'),
90
-                    false,
91
-                    ''
92
-                ),
93
-                'TKT_description'       => new EE_Post_Content_Field(
94
-                    'TKT_description',
95
-                    esc_html__('Description of Ticket', 'event_espresso'),
96
-                    false,
97
-                    ''
98
-                ),
99
-                'TKT_start_date'        => new EE_Datetime_Field(
100
-                    'TKT_start_date',
101
-                    esc_html__('Start time/date of Ticket', 'event_espresso'),
102
-                    false,
103
-                    EE_Datetime_Field::now,
104
-                    $timezone
105
-                ),
106
-                'TKT_end_date'          => new EE_Datetime_Field(
107
-                    'TKT_end_date',
108
-                    esc_html__('End time/date of Ticket', 'event_espresso'),
109
-                    false,
110
-                    EE_Datetime_Field::now,
111
-                    $timezone
112
-                ),
113
-                'TKT_min'               => new EE_Integer_Field(
114
-                    'TKT_min',
115
-                    esc_html__('Minimum quantity of this ticket that must be purchased', 'event_espresso'),
116
-                    false,
117
-                    0
118
-                ),
119
-                'TKT_max'               => new EE_Infinite_Integer_Field(
120
-                    'TKT_max',
121
-                    esc_html__(
122
-                        'Maximum quantity of this ticket that can be purchased in one transaction',
123
-                        'event_espresso'
124
-                    ),
125
-                    false,
126
-                    EE_INF
127
-                ),
128
-                'TKT_price'             => new EE_Money_Field(
129
-                    'TKT_price',
130
-                    esc_html__('Final calculated price for ticket', 'event_espresso'),
131
-                    false,
132
-                    0
133
-                ),
134
-                'TKT_sold'              => new EE_Integer_Field(
135
-                    'TKT_sold',
136
-                    esc_html__('Number of this ticket sold', 'event_espresso'),
137
-                    false,
138
-                    0
139
-                ),
140
-                'TKT_qty'               => new EE_Infinite_Integer_Field(
141
-                    'TKT_qty',
142
-                    esc_html__('Quantity of this ticket that is available', 'event_espresso'),
143
-                    false,
144
-                    EE_INF
145
-                ),
146
-                'TKT_reserved'          => new EE_Integer_Field(
147
-                    'TKT_reserved',
148
-                    esc_html__(
149
-                        'Quantity of this ticket that is reserved, but not yet fully purchased',
150
-                        'event_espresso'
151
-                    ),
152
-                    false,
153
-                    0
154
-                ),
155
-                'TKT_uses'              => new EE_Infinite_Integer_Field(
156
-                    'TKT_uses',
157
-                    esc_html__('Number of datetimes this ticket can be used at', 'event_espresso'),
158
-                    false,
159
-                    EE_INF
160
-                ),
161
-                'TKT_required'          => new EE_Boolean_Field(
162
-                    'TKT_required',
163
-                    esc_html__(
164
-                        'Flag indicating whether this ticket must be purchased with a transaction',
165
-                        'event_espresso'
166
-                    ),
167
-                    false,
168
-                    false
169
-                ),
170
-                'TKT_taxable'           => new EE_Boolean_Field(
171
-                    'TKT_taxable',
172
-                    esc_html__(
173
-                        'Flag indicating whether there is tax applied on this ticket',
174
-                        'event_espresso'
175
-                    ),
176
-                    false,
177
-                    false
178
-                ),
179
-                'TKT_is_default'        => new EE_Boolean_Field(
180
-                    'TKT_is_default',
181
-                    esc_html__('Flag indicating that this ticket is a default ticket', 'event_espresso'),
182
-                    false,
183
-                    false
184
-                ),
185
-                'TKT_order'             => new EE_Integer_Field(
186
-                    'TKT_order',
187
-                    esc_html__(
188
-                        'The order in which the Ticket is displayed in the editor (used for autosaves when the form doesn\'t have the ticket ID yet)',
189
-                        'event_espresso'
190
-                    ),
191
-                    false,
192
-                    0
193
-                ),
194
-                'TKT_row'               => new EE_Integer_Field(
195
-                    'TKT_row',
196
-                    esc_html__('How tickets are displayed in the ui', 'event_espresso'),
197
-                    false,
198
-                    0
199
-                ),
200
-                'TKT_deleted'           => new EE_Trashed_Flag_Field(
201
-                    'TKT_deleted',
202
-                    esc_html__('Flag indicating if this has been archived or not', 'event_espresso'),
203
-                    false,
204
-                    false
205
-                ),
206
-                'TKT_wp_user'           => new EE_WP_User_Field(
207
-                    'TKT_wp_user',
208
-                    esc_html__('Ticket Creator ID', 'event_espresso'),
209
-                    false
210
-                ),
211
-                'TKT_parent'            => new EE_Integer_Field(
212
-                    'TKT_parent',
213
-                    esc_html__(
214
-                        'Indicates what TKT_ID is the parent of this TKT_ID (used in autosaves/revisions)',
215
-                        'event_espresso'
216
-                    ),
217
-                    true,
218
-                    0
219
-                ),
220
-                'TKT_reverse_calculate' => new EE_Boolean_Field(
221
-                    'TKT_reverse_calculate',
222
-                    esc_html__(
223
-                        'Flag indicating whether ticket calculations should run in reverse and calculate the base ticket price from the provided ticket total.',
224
-                        'event_espresso'
225
-                    ),
226
-                    false,
227
-                    false
228
-                ),
229
-                'TKT_visibility'        => new EE_Enum_Integer_Field(
230
-                    'TKT_visibility',
231
-                    esc_html__('Defines where the ticket can be viewed throughout the UI.', 'event_espresso'),
232
-                    false,
233
-                    EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE,
234
-                    $this->getTicketVisibilityEnumOptions()
235
-                ),
236
-            ],
237
-        ];
238
-        $this->_model_relations = [
239
-            'Datetime'        => new EE_HABTM_Relation('Datetime_Ticket'),
240
-            'Datetime_Ticket' => new EE_Has_Many_Relation(),
241
-            'Price'           => new EE_HABTM_Relation('Ticket_Price'),
242
-            'Ticket_Template' => new EE_Belongs_To_Relation(),
243
-            'Registration'    => new EE_Has_Many_Relation(),
244
-            'WP_User'         => new EE_Belongs_To_Relation(),
245
-        ];
246
-        // this model is generally available for reading
247
-        $path_to_event                                            = 'Datetime.Event';
248
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public(
249
-            'TKT_is_default',
250
-            $path_to_event
251
-        );
252
-
253
-        // account for default tickets in the caps
254
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ]
255
-                                                                    = new EE_Restriction_Generator_Default_Protected(
256
-                                                                        'TKT_is_default',
257
-                                                                        $path_to_event
258
-                                                                    );
259
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]   = new EE_Restriction_Generator_Default_Protected(
260
-            'TKT_is_default',
261
-            $path_to_event
262
-        );
263
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Default_Protected(
264
-            'TKT_is_default',
265
-            $path_to_event
266
-        );
267
-        $this->model_chain_to_password                              = $path_to_event;
268
-        parent::__construct($timezone);
269
-    }
270
-
271
-
272
-    /**
273
-     * This returns all tickets that are defaults from the db
274
-     *
275
-     * @return EE_Ticket[]
276
-     * @throws EE_Error
277
-     * @throws ReflectionException
278
-     */
279
-    public function get_all_default_tickets(): array
280
-    {
281
-        $tickets = $this->get_all(
282
-            [
283
-                [
284
-                    'TKT_is_default' => 1,
285
-                    'TKT_visibility' => ['>', EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE],
286
-                ],
287
-                'order_by' => ['TKT_ID' => 'ASC'],
288
-            ]
289
-        );
290
-        // we need to set the start date and end date to today's date and the start of the default dtt
291
-        return $this->_set_default_dates($tickets);
292
-    }
293
-
294
-
295
-    /**
296
-     * sets up relevant start and end date for EE_Ticket (s)
297
-     *
298
-     * @param EE_Ticket[] $tickets
299
-     * @return EE_Ticket[]
300
-     * @throws EE_Error
301
-     * @throws ReflectionException
302
-     */
303
-    private function _set_default_dates(array $tickets): array
304
-    {
305
-        foreach ($tickets as $ticket) {
306
-            $ticket->set(
307
-                'TKT_start_date',
308
-                (int) $this->current_time_for_query('TKT_start_date', true)
309
-            );
310
-            $ticket->set(
311
-                'TKT_end_date',
312
-                (int) $this->current_time_for_query('TKT_end_date', true) + MONTH_IN_SECONDS
313
-            );
314
-            $ticket->set_end_time(
315
-                $this->convert_datetime_for_query(
316
-                    'TKT_end_date',
317
-                    '11:59 pm',
318
-                    'g:i a',
319
-                    $this->_timezone
320
-                )
321
-            );
322
-        }
323
-        return $tickets;
324
-    }
325
-
326
-
327
-    /**
328
-     * Gets the total number of tickets available at a particular datetime (does
329
-     * NOT take int account the datetime's spaces available)
330
-     *
331
-     * @param int   $DTT_ID
332
-     * @param array $query_params
333
-     * @return int
334
-     * @throws EE_Error
335
-     * @throws ReflectionException
336
-     */
337
-    public function sum_tickets_currently_available_at_datetime(int $DTT_ID, array $query_params = []): int
338
-    {
339
-        $query_params += [['TKT_visibility' => ['>', EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE]]];
340
-        return EEM_Datetime::instance()->sum_tickets_currently_available_at_datetime($DTT_ID, $query_params);
341
-    }
342
-
343
-
344
-    /**
345
-     * Updates the TKT_sold quantity on all the tickets matching $query_params
346
-     *
347
-     * @param EE_Ticket[] $tickets
348
-     * @return void
349
-     * @throws EE_Error
350
-     * @throws ReflectionException
351
-     */
352
-    public function update_tickets_sold(array $tickets)
353
-    {
354
-        foreach ($tickets as $ticket) {
355
-            $ticket->update_tickets_sold();
356
-        }
357
-    }
358
-
359
-
360
-    /**
361
-     * returns an array of EE_Ticket objects with a non-zero value for TKT_reserved
362
-     *
363
-     * @return EE_Base_Class[]|EE_Ticket[]|null
364
-     * @throws EE_Error
365
-     * @throws ReflectionException
366
-     */
367
-    public function get_tickets_with_reservations(): ?array
368
-    {
369
-        return $this->get_all(
370
-            [
371
-                [
372
-                    'TKT_reserved'   => ['>', 0],
373
-                    'TKT_visibility' => ['>', EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE],
374
-                ],
375
-            ]
376
-        );
377
-    }
378
-
379
-
380
-    /**
381
-     * returns an array of EE_Ticket objects matching the supplied list of IDs
382
-     *
383
-     * @param array $ticket_IDs
384
-     * @return EE_Base_Class[]|EE_Ticket[]|null
385
-     * @throws EE_Error
386
-     * @throws ReflectionException
387
-     */
388
-    public function get_tickets_with_IDs(array $ticket_IDs): ?array
389
-    {
390
-        return $this->get_all(
391
-            [
392
-                [
393
-                    'TKT_ID' => ['IN', $ticket_IDs],
394
-                ],
395
-            ]
396
-        );
397
-    }
398
-
399
-
400
-    /**
401
-     * @return void
402
-     */
403
-    private function parseTicketVisibilityOptions()
404
-    {
405
-        $this->ticket_visibility = (array) apply_filters(
406
-            'FHEE__EEM_Ticket__construct__ticket_visibility',
407
-            [
408
-                EEM_Ticket::TICKET_VISIBILITY_PUBLIC_KEY        => [
409
-                    'desc'  => esc_html__('ticket displayed to everyone everywhere', 'event_espresso'),
410
-                    'label' => esc_html__('Public', 'event_espresso'),
411
-                    'value' => EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE,
412
-                ],
413
-                EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_KEY  => [
414
-                    'desc'  => esc_html__('ticket only displayed to logged-in users', 'event_espresso'),
415
-                    'label' => esc_html__('Members only', 'event_espresso'),
416
-                    'value' => EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE,
417
-                ],
418
-                EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_KEY   => [
419
-                    'desc'  => esc_html__('ticket only displayed to logged-in admins', 'event_espresso'),
420
-                    'label' => esc_html__('Admins only', 'event_espresso'),
421
-                    'value' => EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE,
422
-                ],
423
-                EEM_Ticket::TICKET_VISIBILITY_ADMIN_UI_ONLY_KEY => [
424
-                    'desc'  => esc_html__(
425
-                        'ticket only displayed in the admin UI and not on the frontend',
426
-                        'event_espresso'
427
-                    ),
428
-                    'label' => esc_html__('Admin UI only', 'event_espresso'),
429
-                    'value' => EEM_Ticket::TICKET_VISIBILITY_ADMIN_UI_ONLY_VALUE,
430
-                ],
431
-                EEM_Ticket::TICKET_VISIBILITY_NONE_KEY          => [
432
-                    'desc'  => esc_html__('will hide the ticket everywhere', 'event_espresso'),
433
-                    'label' => esc_html__('None', 'event_espresso'),
434
-                    'value' => EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE,
435
-                ],
436
-            ]
437
-        );
438
-    }
439
-
440
-
441
-    /**
442
-     * @return array
443
-     */
444
-    public function getTicketVisibilityEnumOptions(): array
445
-    {
446
-        $ticket_visibility = [];
447
-        foreach ($this->ticket_visibility as $visibility) {
448
-            if (isset($visibility['value'], $visibility['label'])) {
449
-                $ticket_visibility[ $visibility['value'] ] = $visibility['label'];
450
-            }
451
-        }
452
-        return $ticket_visibility;
453
-    }
454
-
455
-
456
-    /**
457
-     * @return array
458
-     */
459
-    public function getTicketVisibilityValues(): array
460
-    {
461
-        // copy ticket_visibility array
462
-        $ticket_visibility_options = $this->ticket_visibility;
463
-        foreach ($ticket_visibility_options as $ticket_visibility_option) {
464
-            // remove labels because we only want the values
465
-            unset($ticket_visibility_option['label']);
466
-        }
467
-        return $ticket_visibility_options;
468
-    }
469
-
470
-
471
-    /**
472
-     * @return array
473
-     */
474
-    public function getTicketVisibilityLabels(): array
475
-    {
476
-        $ticket_visibility_options = [];
477
-        foreach ($this->ticket_visibility as $key => $ticket_visibility_option) {
478
-            if (isset($ticket_visibility_option['label'])) {
479
-                // change because we only want the labels tied to the keys
480
-                $ticket_visibility_options[] = [
481
-                    'value' => $key,
482
-                    'label' => $ticket_visibility_option['label'],
483
-                ];
484
-            }
485
-        }
486
-        return $ticket_visibility_options;
487
-    }
488
-
489
-
490
-    /**
491
-     * @return array
492
-     */
493
-    public function ticketVisibilityOptions(): array
494
-    {
495
-        return $this->ticket_visibility;
496
-    }
16
+	/**
17
+	 * the following constants define where tickets can be viewed throughout the UI
18
+	 *  TICKET_VISIBILITY_NONE          - will not be displayed anywhere
19
+	 *  TICKET_VISIBILITY_PUBLIC        - basically displayed everywhere
20
+	 *  TICKET_VISIBILITY_MEMBERS_ONLY  - displayed to any logged-in user
21
+	 *  TICKET_VISIBILITY_ADMINS_ONLY   - displayed to any logged-in user that is an admin
22
+	 *  TICKET_VISIBILITY_ADMIN_UI_ONLY - only displayed in the admin, never publicly
23
+	 */
24
+	public const TICKET_VISIBILITY_NONE_KEY            = 'NONE';
25
+
26
+	public const TICKET_VISIBILITY_NONE_VALUE          = 0;
27
+
28
+	public const TICKET_VISIBILITY_PUBLIC_KEY          = 'PUBLIC';
29
+
30
+	public const TICKET_VISIBILITY_PUBLIC_VALUE        = 100;
31
+
32
+	public const TICKET_VISIBILITY_MEMBERS_ONLY_KEY    = 'MEMBERS_ONLY';
33
+
34
+	public const TICKET_VISIBILITY_MEMBERS_ONLY_VALUE  = 200;
35
+
36
+	public const TICKET_VISIBILITY_ADMINS_ONLY_KEY     = 'ADMINS_ONLY';
37
+
38
+	public const TICKET_VISIBILITY_ADMINS_ONLY_VALUE   = 300;
39
+
40
+	public const TICKET_VISIBILITY_ADMIN_UI_ONLY_KEY   = 'ADMIN_UI_ONLY';
41
+
42
+	public const TICKET_VISIBILITY_ADMIN_UI_ONLY_VALUE = 400;
43
+
44
+
45
+	/**
46
+	 * defines where tickets can be viewed throughout the UI
47
+	 *
48
+	 * @var array
49
+	 */
50
+	private $ticket_visibility;
51
+
52
+	protected static ?EEM_Ticket $_instance = null;
53
+
54
+
55
+	/**
56
+	 * private constructor to prevent direct creation
57
+	 *
58
+	 * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings
59
+	 *                              (and any incoming timezone data that gets saved).
60
+	 *                              Note this just sends the timezone info to the date time model field objects.
61
+	 *                              Default is NULL
62
+	 *                              (and will be assumed using the set timezone in the 'timezone_string' wp option)
63
+	 * @throws EE_Error
64
+	 * @throws ReflectionException
65
+	 */
66
+	protected function __construct(?string $timezone = '')
67
+	{
68
+		$this->singular_item = esc_html__('Ticket', 'event_espresso');
69
+		$this->plural_item   = esc_html__('Tickets', 'event_espresso');
70
+		$this->_tables       = [
71
+			'Ticket' => new EE_Primary_Table('esp_ticket', 'TKT_ID'),
72
+		];
73
+		$this->parseTicketVisibilityOptions();
74
+		$this->_fields          = [
75
+			'Ticket' => [
76
+				'TKT_ID'                => new EE_Primary_Key_Int_Field(
77
+					'TKT_ID',
78
+					esc_html__('Ticket ID', 'event_espresso')
79
+				),
80
+				'TTM_ID'                => new EE_Foreign_Key_Int_Field(
81
+					'TTM_ID',
82
+					esc_html__('Ticket Template ID', 'event_espresso'),
83
+					false,
84
+					0,
85
+					'Ticket_Template'
86
+				),
87
+				'TKT_name'              => new EE_Plain_Text_Field(
88
+					'TKT_name',
89
+					esc_html__('Ticket Name', 'event_espresso'),
90
+					false,
91
+					''
92
+				),
93
+				'TKT_description'       => new EE_Post_Content_Field(
94
+					'TKT_description',
95
+					esc_html__('Description of Ticket', 'event_espresso'),
96
+					false,
97
+					''
98
+				),
99
+				'TKT_start_date'        => new EE_Datetime_Field(
100
+					'TKT_start_date',
101
+					esc_html__('Start time/date of Ticket', 'event_espresso'),
102
+					false,
103
+					EE_Datetime_Field::now,
104
+					$timezone
105
+				),
106
+				'TKT_end_date'          => new EE_Datetime_Field(
107
+					'TKT_end_date',
108
+					esc_html__('End time/date of Ticket', 'event_espresso'),
109
+					false,
110
+					EE_Datetime_Field::now,
111
+					$timezone
112
+				),
113
+				'TKT_min'               => new EE_Integer_Field(
114
+					'TKT_min',
115
+					esc_html__('Minimum quantity of this ticket that must be purchased', 'event_espresso'),
116
+					false,
117
+					0
118
+				),
119
+				'TKT_max'               => new EE_Infinite_Integer_Field(
120
+					'TKT_max',
121
+					esc_html__(
122
+						'Maximum quantity of this ticket that can be purchased in one transaction',
123
+						'event_espresso'
124
+					),
125
+					false,
126
+					EE_INF
127
+				),
128
+				'TKT_price'             => new EE_Money_Field(
129
+					'TKT_price',
130
+					esc_html__('Final calculated price for ticket', 'event_espresso'),
131
+					false,
132
+					0
133
+				),
134
+				'TKT_sold'              => new EE_Integer_Field(
135
+					'TKT_sold',
136
+					esc_html__('Number of this ticket sold', 'event_espresso'),
137
+					false,
138
+					0
139
+				),
140
+				'TKT_qty'               => new EE_Infinite_Integer_Field(
141
+					'TKT_qty',
142
+					esc_html__('Quantity of this ticket that is available', 'event_espresso'),
143
+					false,
144
+					EE_INF
145
+				),
146
+				'TKT_reserved'          => new EE_Integer_Field(
147
+					'TKT_reserved',
148
+					esc_html__(
149
+						'Quantity of this ticket that is reserved, but not yet fully purchased',
150
+						'event_espresso'
151
+					),
152
+					false,
153
+					0
154
+				),
155
+				'TKT_uses'              => new EE_Infinite_Integer_Field(
156
+					'TKT_uses',
157
+					esc_html__('Number of datetimes this ticket can be used at', 'event_espresso'),
158
+					false,
159
+					EE_INF
160
+				),
161
+				'TKT_required'          => new EE_Boolean_Field(
162
+					'TKT_required',
163
+					esc_html__(
164
+						'Flag indicating whether this ticket must be purchased with a transaction',
165
+						'event_espresso'
166
+					),
167
+					false,
168
+					false
169
+				),
170
+				'TKT_taxable'           => new EE_Boolean_Field(
171
+					'TKT_taxable',
172
+					esc_html__(
173
+						'Flag indicating whether there is tax applied on this ticket',
174
+						'event_espresso'
175
+					),
176
+					false,
177
+					false
178
+				),
179
+				'TKT_is_default'        => new EE_Boolean_Field(
180
+					'TKT_is_default',
181
+					esc_html__('Flag indicating that this ticket is a default ticket', 'event_espresso'),
182
+					false,
183
+					false
184
+				),
185
+				'TKT_order'             => new EE_Integer_Field(
186
+					'TKT_order',
187
+					esc_html__(
188
+						'The order in which the Ticket is displayed in the editor (used for autosaves when the form doesn\'t have the ticket ID yet)',
189
+						'event_espresso'
190
+					),
191
+					false,
192
+					0
193
+				),
194
+				'TKT_row'               => new EE_Integer_Field(
195
+					'TKT_row',
196
+					esc_html__('How tickets are displayed in the ui', 'event_espresso'),
197
+					false,
198
+					0
199
+				),
200
+				'TKT_deleted'           => new EE_Trashed_Flag_Field(
201
+					'TKT_deleted',
202
+					esc_html__('Flag indicating if this has been archived or not', 'event_espresso'),
203
+					false,
204
+					false
205
+				),
206
+				'TKT_wp_user'           => new EE_WP_User_Field(
207
+					'TKT_wp_user',
208
+					esc_html__('Ticket Creator ID', 'event_espresso'),
209
+					false
210
+				),
211
+				'TKT_parent'            => new EE_Integer_Field(
212
+					'TKT_parent',
213
+					esc_html__(
214
+						'Indicates what TKT_ID is the parent of this TKT_ID (used in autosaves/revisions)',
215
+						'event_espresso'
216
+					),
217
+					true,
218
+					0
219
+				),
220
+				'TKT_reverse_calculate' => new EE_Boolean_Field(
221
+					'TKT_reverse_calculate',
222
+					esc_html__(
223
+						'Flag indicating whether ticket calculations should run in reverse and calculate the base ticket price from the provided ticket total.',
224
+						'event_espresso'
225
+					),
226
+					false,
227
+					false
228
+				),
229
+				'TKT_visibility'        => new EE_Enum_Integer_Field(
230
+					'TKT_visibility',
231
+					esc_html__('Defines where the ticket can be viewed throughout the UI.', 'event_espresso'),
232
+					false,
233
+					EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE,
234
+					$this->getTicketVisibilityEnumOptions()
235
+				),
236
+			],
237
+		];
238
+		$this->_model_relations = [
239
+			'Datetime'        => new EE_HABTM_Relation('Datetime_Ticket'),
240
+			'Datetime_Ticket' => new EE_Has_Many_Relation(),
241
+			'Price'           => new EE_HABTM_Relation('Ticket_Price'),
242
+			'Ticket_Template' => new EE_Belongs_To_Relation(),
243
+			'Registration'    => new EE_Has_Many_Relation(),
244
+			'WP_User'         => new EE_Belongs_To_Relation(),
245
+		];
246
+		// this model is generally available for reading
247
+		$path_to_event                                            = 'Datetime.Event';
248
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public(
249
+			'TKT_is_default',
250
+			$path_to_event
251
+		);
252
+
253
+		// account for default tickets in the caps
254
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ]
255
+																	= new EE_Restriction_Generator_Default_Protected(
256
+																		'TKT_is_default',
257
+																		$path_to_event
258
+																	);
259
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ]   = new EE_Restriction_Generator_Default_Protected(
260
+			'TKT_is_default',
261
+			$path_to_event
262
+		);
263
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Default_Protected(
264
+			'TKT_is_default',
265
+			$path_to_event
266
+		);
267
+		$this->model_chain_to_password                              = $path_to_event;
268
+		parent::__construct($timezone);
269
+	}
270
+
271
+
272
+	/**
273
+	 * This returns all tickets that are defaults from the db
274
+	 *
275
+	 * @return EE_Ticket[]
276
+	 * @throws EE_Error
277
+	 * @throws ReflectionException
278
+	 */
279
+	public function get_all_default_tickets(): array
280
+	{
281
+		$tickets = $this->get_all(
282
+			[
283
+				[
284
+					'TKT_is_default' => 1,
285
+					'TKT_visibility' => ['>', EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE],
286
+				],
287
+				'order_by' => ['TKT_ID' => 'ASC'],
288
+			]
289
+		);
290
+		// we need to set the start date and end date to today's date and the start of the default dtt
291
+		return $this->_set_default_dates($tickets);
292
+	}
293
+
294
+
295
+	/**
296
+	 * sets up relevant start and end date for EE_Ticket (s)
297
+	 *
298
+	 * @param EE_Ticket[] $tickets
299
+	 * @return EE_Ticket[]
300
+	 * @throws EE_Error
301
+	 * @throws ReflectionException
302
+	 */
303
+	private function _set_default_dates(array $tickets): array
304
+	{
305
+		foreach ($tickets as $ticket) {
306
+			$ticket->set(
307
+				'TKT_start_date',
308
+				(int) $this->current_time_for_query('TKT_start_date', true)
309
+			);
310
+			$ticket->set(
311
+				'TKT_end_date',
312
+				(int) $this->current_time_for_query('TKT_end_date', true) + MONTH_IN_SECONDS
313
+			);
314
+			$ticket->set_end_time(
315
+				$this->convert_datetime_for_query(
316
+					'TKT_end_date',
317
+					'11:59 pm',
318
+					'g:i a',
319
+					$this->_timezone
320
+				)
321
+			);
322
+		}
323
+		return $tickets;
324
+	}
325
+
326
+
327
+	/**
328
+	 * Gets the total number of tickets available at a particular datetime (does
329
+	 * NOT take int account the datetime's spaces available)
330
+	 *
331
+	 * @param int   $DTT_ID
332
+	 * @param array $query_params
333
+	 * @return int
334
+	 * @throws EE_Error
335
+	 * @throws ReflectionException
336
+	 */
337
+	public function sum_tickets_currently_available_at_datetime(int $DTT_ID, array $query_params = []): int
338
+	{
339
+		$query_params += [['TKT_visibility' => ['>', EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE]]];
340
+		return EEM_Datetime::instance()->sum_tickets_currently_available_at_datetime($DTT_ID, $query_params);
341
+	}
342
+
343
+
344
+	/**
345
+	 * Updates the TKT_sold quantity on all the tickets matching $query_params
346
+	 *
347
+	 * @param EE_Ticket[] $tickets
348
+	 * @return void
349
+	 * @throws EE_Error
350
+	 * @throws ReflectionException
351
+	 */
352
+	public function update_tickets_sold(array $tickets)
353
+	{
354
+		foreach ($tickets as $ticket) {
355
+			$ticket->update_tickets_sold();
356
+		}
357
+	}
358
+
359
+
360
+	/**
361
+	 * returns an array of EE_Ticket objects with a non-zero value for TKT_reserved
362
+	 *
363
+	 * @return EE_Base_Class[]|EE_Ticket[]|null
364
+	 * @throws EE_Error
365
+	 * @throws ReflectionException
366
+	 */
367
+	public function get_tickets_with_reservations(): ?array
368
+	{
369
+		return $this->get_all(
370
+			[
371
+				[
372
+					'TKT_reserved'   => ['>', 0],
373
+					'TKT_visibility' => ['>', EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE],
374
+				],
375
+			]
376
+		);
377
+	}
378
+
379
+
380
+	/**
381
+	 * returns an array of EE_Ticket objects matching the supplied list of IDs
382
+	 *
383
+	 * @param array $ticket_IDs
384
+	 * @return EE_Base_Class[]|EE_Ticket[]|null
385
+	 * @throws EE_Error
386
+	 * @throws ReflectionException
387
+	 */
388
+	public function get_tickets_with_IDs(array $ticket_IDs): ?array
389
+	{
390
+		return $this->get_all(
391
+			[
392
+				[
393
+					'TKT_ID' => ['IN', $ticket_IDs],
394
+				],
395
+			]
396
+		);
397
+	}
398
+
399
+
400
+	/**
401
+	 * @return void
402
+	 */
403
+	private function parseTicketVisibilityOptions()
404
+	{
405
+		$this->ticket_visibility = (array) apply_filters(
406
+			'FHEE__EEM_Ticket__construct__ticket_visibility',
407
+			[
408
+				EEM_Ticket::TICKET_VISIBILITY_PUBLIC_KEY        => [
409
+					'desc'  => esc_html__('ticket displayed to everyone everywhere', 'event_espresso'),
410
+					'label' => esc_html__('Public', 'event_espresso'),
411
+					'value' => EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE,
412
+				],
413
+				EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_KEY  => [
414
+					'desc'  => esc_html__('ticket only displayed to logged-in users', 'event_espresso'),
415
+					'label' => esc_html__('Members only', 'event_espresso'),
416
+					'value' => EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE,
417
+				],
418
+				EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_KEY   => [
419
+					'desc'  => esc_html__('ticket only displayed to logged-in admins', 'event_espresso'),
420
+					'label' => esc_html__('Admins only', 'event_espresso'),
421
+					'value' => EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE,
422
+				],
423
+				EEM_Ticket::TICKET_VISIBILITY_ADMIN_UI_ONLY_KEY => [
424
+					'desc'  => esc_html__(
425
+						'ticket only displayed in the admin UI and not on the frontend',
426
+						'event_espresso'
427
+					),
428
+					'label' => esc_html__('Admin UI only', 'event_espresso'),
429
+					'value' => EEM_Ticket::TICKET_VISIBILITY_ADMIN_UI_ONLY_VALUE,
430
+				],
431
+				EEM_Ticket::TICKET_VISIBILITY_NONE_KEY          => [
432
+					'desc'  => esc_html__('will hide the ticket everywhere', 'event_espresso'),
433
+					'label' => esc_html__('None', 'event_espresso'),
434
+					'value' => EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE,
435
+				],
436
+			]
437
+		);
438
+	}
439
+
440
+
441
+	/**
442
+	 * @return array
443
+	 */
444
+	public function getTicketVisibilityEnumOptions(): array
445
+	{
446
+		$ticket_visibility = [];
447
+		foreach ($this->ticket_visibility as $visibility) {
448
+			if (isset($visibility['value'], $visibility['label'])) {
449
+				$ticket_visibility[ $visibility['value'] ] = $visibility['label'];
450
+			}
451
+		}
452
+		return $ticket_visibility;
453
+	}
454
+
455
+
456
+	/**
457
+	 * @return array
458
+	 */
459
+	public function getTicketVisibilityValues(): array
460
+	{
461
+		// copy ticket_visibility array
462
+		$ticket_visibility_options = $this->ticket_visibility;
463
+		foreach ($ticket_visibility_options as $ticket_visibility_option) {
464
+			// remove labels because we only want the values
465
+			unset($ticket_visibility_option['label']);
466
+		}
467
+		return $ticket_visibility_options;
468
+	}
469
+
470
+
471
+	/**
472
+	 * @return array
473
+	 */
474
+	public function getTicketVisibilityLabels(): array
475
+	{
476
+		$ticket_visibility_options = [];
477
+		foreach ($this->ticket_visibility as $key => $ticket_visibility_option) {
478
+			if (isset($ticket_visibility_option['label'])) {
479
+				// change because we only want the labels tied to the keys
480
+				$ticket_visibility_options[] = [
481
+					'value' => $key,
482
+					'label' => $ticket_visibility_option['label'],
483
+				];
484
+			}
485
+		}
486
+		return $ticket_visibility_options;
487
+	}
488
+
489
+
490
+	/**
491
+	 * @return array
492
+	 */
493
+	public function ticketVisibilityOptions(): array
494
+	{
495
+		return $this->ticket_visibility;
496
+	}
497 497
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
             'Ticket' => new EE_Primary_Table('esp_ticket', 'TKT_ID'),
72 72
         ];
73 73
         $this->parseTicketVisibilityOptions();
74
-        $this->_fields          = [
74
+        $this->_fields = [
75 75
             'Ticket' => [
76 76
                 'TKT_ID'                => new EE_Primary_Key_Int_Field(
77 77
                     'TKT_ID',
@@ -245,26 +245,26 @@  discard block
 block discarded – undo
245 245
         ];
246 246
         // this model is generally available for reading
247 247
         $path_to_event                                            = 'Datetime.Event';
248
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public(
248
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Default_Public(
249 249
             'TKT_is_default',
250 250
             $path_to_event
251 251
         );
252 252
 
253 253
         // account for default tickets in the caps
254
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ]
254
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin]
255 255
                                                                     = new EE_Restriction_Generator_Default_Protected(
256 256
                                                                         'TKT_is_default',
257 257
                                                                         $path_to_event
258 258
                                                                     );
259
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]   = new EE_Restriction_Generator_Default_Protected(
259
+        $this->_cap_restriction_generators[EEM_Base::caps_edit] = new EE_Restriction_Generator_Default_Protected(
260 260
             'TKT_is_default',
261 261
             $path_to_event
262 262
         );
263
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Default_Protected(
263
+        $this->_cap_restriction_generators[EEM_Base::caps_delete] = new EE_Restriction_Generator_Default_Protected(
264 264
             'TKT_is_default',
265 265
             $path_to_event
266 266
         );
267
-        $this->model_chain_to_password                              = $path_to_event;
267
+        $this->model_chain_to_password = $path_to_event;
268 268
         parent::__construct($timezone);
269 269
     }
270 270
 
@@ -446,7 +446,7 @@  discard block
 block discarded – undo
446 446
         $ticket_visibility = [];
447 447
         foreach ($this->ticket_visibility as $visibility) {
448 448
             if (isset($visibility['value'], $visibility['label'])) {
449
-                $ticket_visibility[ $visibility['value'] ] = $visibility['label'];
449
+                $ticket_visibility[$visibility['value']] = $visibility['label'];
450 450
             }
451 451
         }
452 452
         return $ticket_visibility;
Please login to merge, or discard this patch.
core/db_models/EEM_Ticket_Template.model.php 1 patch
Indentation   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -9,71 +9,71 @@
 block discarded – undo
9 9
  */
10 10
 class EEM_Ticket_Template extends EEM_Base
11 11
 {
12
-    protected static ?EEM_Ticket_Template $_instance = null;
12
+	protected static ?EEM_Ticket_Template $_instance = null;
13 13
 
14 14
 
15
-    /**
16
-     * private constructor to prevent direct creation
17
-     *
18
-     * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings (and
19
-     *                              any incoming timezone data that gets saved).  Note this just sends the timezone
20
-     *                              info to the date time model field objects.  Default is NULL (and will be assumed
21
-     *                              using the set timezone in the 'timezone_string' wp option)
22
-     * @throws EE_Error
23
-     */
24
-    protected function __construct(?string $timezone = '')
25
-    {
26
-        $this->singular_item = esc_html__('Ticket Template', 'event_espresso');
27
-        $this->plural_item   = esc_html__('Ticket Templates', 'event_espresso');
15
+	/**
16
+	 * private constructor to prevent direct creation
17
+	 *
18
+	 * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings (and
19
+	 *                              any incoming timezone data that gets saved).  Note this just sends the timezone
20
+	 *                              info to the date time model field objects.  Default is NULL (and will be assumed
21
+	 *                              using the set timezone in the 'timezone_string' wp option)
22
+	 * @throws EE_Error
23
+	 */
24
+	protected function __construct(?string $timezone = '')
25
+	{
26
+		$this->singular_item = esc_html__('Ticket Template', 'event_espresso');
27
+		$this->plural_item   = esc_html__('Ticket Templates', 'event_espresso');
28 28
 
29
-        $this->_tables                                            = [
30
-            'Ticket_Template' => new EE_Primary_Table('esp_ticket_template', 'TTM_ID'),
31
-        ];
32
-        $this->_fields                                            = [
33
-            'Ticket_Template' => [
34
-                'TTM_ID'          => new EE_Primary_Key_Int_Field(
35
-                    'TTM_ID',
36
-                    esc_html__('Ticket Template ID', 'event_espresso')
37
-                ),
38
-                'TTM_name'        => new EE_Plain_Text_Field(
39
-                    'TTM_name',
40
-                    esc_html__('The name of the ticket template', 'event_espresso'),
41
-                    false,
42
-                    ''
43
-                ),
44
-                'TTM_description' => new EE_Plain_Text_Field(
45
-                    'TTM_description',
46
-                    esc_html__(
47
-                        'The description for the ticket template',
48
-                        'event_espresso'
49
-                    ),
50
-                    true,
51
-                    ''
52
-                ),
53
-                'TTM_file'        => new EE_Plain_Text_Field(
54
-                    'TTM_file',
55
-                    esc_html__(
56
-                        'The file name for the actual template file saved on disk',
57
-                        'event_espresso'
58
-                    ),
59
-                    true,
60
-                    ''
61
-                ),
62
-            ],
63
-        ];
64
-        $this->_model_relations                                   = [
65
-            'Ticket' => new EE_Has_Many_Relation(),
66
-        ];
67
-        $this->_model_chain_to_wp_user                            = 'Ticket';
68
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] =
69
-            new EE_Restriction_Generator_Default_Public('Ticket.TKT_is_default', 'Ticket.Datetime.Event');
70
-        // account for default tickets in the caps
71
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
72
-            new EE_Restriction_Generator_Default_Protected('Ticket.TKT_is_default', 'Ticket.Datetime.Event');
73
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
74
-            new EE_Restriction_Generator_Default_Protected('Ticket.TKT_is_default', 'Ticket.Datetime.Event');
75
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
76
-            new EE_Restriction_Generator_Default_Protected('Ticket.TKT_is_default', 'Ticket.Datetime.Event');
77
-        parent::__construct($timezone);
78
-    }
29
+		$this->_tables                                            = [
30
+			'Ticket_Template' => new EE_Primary_Table('esp_ticket_template', 'TTM_ID'),
31
+		];
32
+		$this->_fields                                            = [
33
+			'Ticket_Template' => [
34
+				'TTM_ID'          => new EE_Primary_Key_Int_Field(
35
+					'TTM_ID',
36
+					esc_html__('Ticket Template ID', 'event_espresso')
37
+				),
38
+				'TTM_name'        => new EE_Plain_Text_Field(
39
+					'TTM_name',
40
+					esc_html__('The name of the ticket template', 'event_espresso'),
41
+					false,
42
+					''
43
+				),
44
+				'TTM_description' => new EE_Plain_Text_Field(
45
+					'TTM_description',
46
+					esc_html__(
47
+						'The description for the ticket template',
48
+						'event_espresso'
49
+					),
50
+					true,
51
+					''
52
+				),
53
+				'TTM_file'        => new EE_Plain_Text_Field(
54
+					'TTM_file',
55
+					esc_html__(
56
+						'The file name for the actual template file saved on disk',
57
+						'event_espresso'
58
+					),
59
+					true,
60
+					''
61
+				),
62
+			],
63
+		];
64
+		$this->_model_relations                                   = [
65
+			'Ticket' => new EE_Has_Many_Relation(),
66
+		];
67
+		$this->_model_chain_to_wp_user                            = 'Ticket';
68
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] =
69
+			new EE_Restriction_Generator_Default_Public('Ticket.TKT_is_default', 'Ticket.Datetime.Event');
70
+		// account for default tickets in the caps
71
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
72
+			new EE_Restriction_Generator_Default_Protected('Ticket.TKT_is_default', 'Ticket.Datetime.Event');
73
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
74
+			new EE_Restriction_Generator_Default_Protected('Ticket.TKT_is_default', 'Ticket.Datetime.Event');
75
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
76
+			new EE_Restriction_Generator_Default_Protected('Ticket.TKT_is_default', 'Ticket.Datetime.Event');
77
+		parent::__construct($timezone);
78
+	}
79 79
 }
Please login to merge, or discard this patch.
core/db_models/fields/EE_Datetime_Field.php 1 patch
Indentation   +761 added lines, -761 removed lines patch added patch discarded remove patch
@@ -19,765 +19,765 @@
 block discarded – undo
19 19
  */
20 20
 class EE_Datetime_Field extends EE_Model_Field_Base
21 21
 {
22
-    /**
23
-     * The pattern we're looking for is if only the characters 0-9 are found and there are only
24
-     * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
25
-     *
26
-     * @type string unix_timestamp_regex
27
-     */
28
-    const unix_timestamp_regex = '/[0-9]{10,}/';
29
-
30
-    /**
31
-     * @type string mysql_timestamp_format
32
-     */
33
-    const mysql_timestamp_format = 'Y-m-d H:i:s';
34
-
35
-    /**
36
-     * @type string mysql_date_format
37
-     */
38
-    const mysql_date_format = 'Y-m-d';
39
-
40
-    /**
41
-     * @type string mysql_time_format
42
-     */
43
-    const mysql_time_format = 'H:i:s';
44
-
45
-    /**
46
-     * Const for using in the default value. If the field's default is set to this,
47
-     * then we will return the time of calling `get_default_value()`, not
48
-     * just the current time at construction
49
-     */
50
-    const now = 'now';
51
-
52
-    /**
53
-     * The following properties hold the default formats for date and time.
54
-     * Defaults are set via the constructor and can be overridden on class instantiation.
55
-     * However they can also be overridden later by the set_format() method
56
-     * (and corresponding set_date_format, set_time_format methods);
57
-     */
58
-
59
-    protected string $_date_format        = '';
60
-
61
-    protected string $_time_format        = '';
62
-
63
-    protected string $_pretty_date_format = '';
64
-
65
-    protected string $_pretty_time_format = '';
66
-
67
-    protected ?DateTimeZone $_DateTimeZone       = null;
68
-
69
-    protected ?DateTimeZone $_UTC_DateTimeZone   = null;
70
-
71
-    protected ?DateTimeZone $_blog_DateTimeZone  = null;
72
-
73
-
74
-    /**
75
-     * This property holds how we want the output returned when getting a datetime string.  It is set for the
76
-     * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
77
-     * and time returned via getters.
78
-     *
79
-     * @var mixed (null|string)
80
-     */
81
-    protected $_date_time_output;
82
-
83
-
84
-    /**
85
-     * timezone string
86
-     * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
87
-     * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
88
-     * coming out of the object to be in.  Default timezone is the current WP timezone option setting
89
-     */
90
-    protected ?string $_timezone_string = null;
91
-
92
-
93
-    /**
94
-     * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
95
-     * offsets for comparison purposes).
96
-     *
97
-     * @var int
98
-     */
99
-    protected int $_blog_offset = 0;
100
-
101
-
102
-    /**
103
-     * @param string      $table_column
104
-     * @param string      $nice_name
105
-     * @param bool        $nullable
106
-     * @param string|null $default_value
107
-     * @param string|null $timezone_string
108
-     * @param string|null $date_format
109
-     * @param string|null $time_format
110
-     * @param string|null $pretty_date_format
111
-     * @param string|null $pretty_time_format
112
-     * @throws InvalidArgumentException
113
-     * @throws Exception
114
-     */
115
-    public function __construct(
116
-        string $table_column,
117
-        string $nice_name,
118
-        bool $nullable,
119
-        ?string $default_value,
120
-        ?string $timezone_string = '',
121
-        ?string $date_format = '',
122
-        ?string $time_format = '',
123
-        ?string $pretty_date_format = '',
124
-        ?string $pretty_time_format = ''
125
-    ) {
126
-        $this->set_date_format($date_format);
127
-        $this->set_time_format($time_format);
128
-        $this->set_date_format($pretty_date_format, true);
129
-        $this->set_time_format($pretty_time_format, true);
130
-
131
-        parent::__construct($table_column, $nice_name, $nullable, $default_value);
132
-        $this->set_timezone($timezone_string);
133
-        $this->setSchemaType(SchemaType::STRING);
134
-        $this->setSchemaFormat(SchemaFormat::DATETIME);
135
-    }
136
-
137
-
138
-    /**
139
-     * @return DateTimeZone
140
-     * @throws Exception
141
-     */
142
-    public function get_UTC_DateTimeZone(): DateTimeZone
143
-    {
144
-        return $this->_UTC_DateTimeZone instanceof DateTimeZone
145
-            ? $this->_UTC_DateTimeZone
146
-            : $this->_create_timezone_object_from_timezone_string('UTC');
147
-    }
148
-
149
-
150
-    /**
151
-     * @return DateTimeZone
152
-     * @throws Exception
153
-     */
154
-    public function get_blog_DateTimeZone(): DateTimeZone
155
-    {
156
-        return $this->_blog_DateTimeZone instanceof DateTimeZone
157
-            ? $this->_blog_DateTimeZone
158
-            : $this->_create_timezone_object_from_timezone_string();
159
-    }
160
-
161
-
162
-    /**
163
-     * this prepares any incoming date data and make sure its converted to a utc unix timestamp
164
-     *
165
-     * @param string|int $value_inputted_for_field_on_model_object  could be a string formatted date time or int unix
166
-     *                                                              timestamp
167
-     * @return DateTime
168
-     * @throws Exception
169
-     */
170
-    public function prepare_for_set($value_inputted_for_field_on_model_object)
171
-    {
172
-        return $this->_get_date_object($value_inputted_for_field_on_model_object);
173
-    }
174
-
175
-
176
-    /**
177
-     * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
178
-     * getters need to know whether we're just returning the date or the time or both.  By default we return both.
179
-     *
180
-     * @param bool $pretty If we're returning the pretty formats or standard format string.
181
-     * @return string    The final assembled format string.
182
-     */
183
-    protected function _get_date_time_output(bool $pretty = false): string
184
-    {
185
-        switch ($this->_date_time_output) {
186
-            case 'time':
187
-                return $pretty
188
-                    ? $this->_pretty_time_format
189
-                    : $this->_time_format;
190
-
191
-            case 'date':
192
-                return $pretty
193
-                    ? $this->_pretty_date_format
194
-                    : $this->_date_format;
195
-
196
-            default:
197
-                return $pretty
198
-                    ? trim($this->_pretty_date_format . ' ' . $this->_pretty_time_format)
199
-                    : trim($this->_date_format . ' ' . $this->_time_format);
200
-        }
201
-    }
202
-
203
-
204
-    /**
205
-     * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
206
-     * returned (using the format properties)
207
-     *
208
-     * @param string|null $what acceptable values are 'time' or 'date'.
209
-     *                          Any other value will be set but will always result
210
-     *                          in both 'date' and 'time' being returned.
211
-     * @return void
212
-     */
213
-    public function set_date_time_output(?string $what = null)
214
-    {
215
-        $this->_date_time_output = $what;
216
-    }
217
-
218
-
219
-    /**
220
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
221
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
222
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
223
-     * We also set some other properties in this method.
224
-     *
225
-     * @param string|null $timezone_string A valid timezone string as described by @link
226
-     *                                     http://www.php.net/manual/en/timezones.php
227
-     * @return void
228
-     * @throws InvalidArgumentException
229
-     * @throws InvalidDataTypeException
230
-     * @throws InvalidInterfaceException
231
-     * @throws Exception
232
-     */
233
-    public function set_timezone(?string $timezone_string = '')
234
-    {
235
-        if (empty($timezone_string) && $this->_timezone_string !== null) {
236
-            // leave the timezone AS-IS if we already have one and
237
-            // the function arg didn't provide one
238
-            return;
239
-        }
240
-        $timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
241
-        $this->_timezone_string = ! empty($timezone_string)
242
-            ? $timezone_string
243
-            : 'UTC';
244
-        $this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
245
-    }
246
-
247
-
248
-    /**
249
-     * _create_timezone_object_from_timezone_name
250
-     *
251
-     * @access protected
252
-     * @param string|null $timezone_string
253
-     * @return DateTimeZone
254
-     * @throws InvalidArgumentException
255
-     * @throws InvalidDataTypeException
256
-     * @throws InvalidInterfaceException
257
-     * @throws Exception
258
-     */
259
-    protected function _create_timezone_object_from_timezone_string(?string $timezone_string = ''): DateTimeZone
260
-    {
261
-        return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
262
-    }
263
-
264
-
265
-    /**
266
-     * This just returns whatever is set for the current timezone.
267
-     *
268
-     * @access public
269
-     * @return string timezone string
270
-     */
271
-    public function get_timezone(): ?string
272
-    {
273
-        return $this->_timezone_string;
274
-    }
275
-
276
-
277
-    /**
278
-     * set the $_date_format property
279
-     *
280
-     * @access public
281
-     * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
282
-     * @param bool   $pretty Whether to set pretty format or not.
283
-     * @return void
284
-     */
285
-    public function set_date_format(string $format, bool $pretty = false)
286
-    {
287
-        if ($pretty) {
288
-            $this->_pretty_date_format = new DateFormat($format);
289
-        } else {
290
-            $this->_date_format = new DateFormat($format);
291
-        }
292
-    }
293
-
294
-
295
-    /**
296
-     * return the $_date_format property value.
297
-     *
298
-     * @param bool $pretty Whether to get pretty format or not.
299
-     * @return string
300
-     */
301
-    public function get_date_format(bool $pretty = false): string
302
-    {
303
-        return $pretty
304
-            ? $this->_pretty_date_format
305
-            : $this->_date_format;
306
-    }
307
-
308
-
309
-    /**
310
-     * set the $_time_format property
311
-     *
312
-     * @access public
313
-     * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
314
-     * @param bool   $pretty Whether to set pretty format or not.
315
-     * @return void
316
-     */
317
-    public function set_time_format(string $format, bool $pretty = false)
318
-    {
319
-        if ($pretty) {
320
-            $this->_pretty_time_format = new TimeFormat($format);
321
-        } else {
322
-            $this->_time_format = new TimeFormat($format);
323
-        }
324
-    }
325
-
326
-
327
-    /**
328
-     * return the $_time_format property value.
329
-     *
330
-     * @param bool $pretty Whether to get pretty format or not.
331
-     * @return string
332
-     */
333
-    public function get_time_format(bool $pretty = false): string
334
-    {
335
-        return $pretty
336
-            ? $this->_pretty_time_format
337
-            : $this->_time_format;
338
-    }
339
-
340
-
341
-    /**
342
-     * set the $_pretty_date_format property
343
-     *
344
-     * @access public
345
-     * @param string|null $format a new pretty date format (corresponding to formats accepted by PHP date() function)
346
-     * @return void
347
-     */
348
-    public function set_pretty_date_format(?string $format)
349
-    {
350
-        $this->set_date_format($format, true);
351
-    }
352
-
353
-
354
-    /**
355
-     * set the $_pretty_time_format property
356
-     *
357
-     * @access public
358
-     * @param string|null $format a new pretty time format (corresponding to formats accepted by PHP date() function)
359
-     * @return void
360
-     */
361
-    public function set_pretty_time_format(?string $format)
362
-    {
363
-        $this->set_time_format($format, true);
364
-    }
365
-
366
-
367
-    /**
368
-     * Only sets the time portion of the datetime.
369
-     *
370
-     * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
371
-     * @param DateTime        $current            current DateTime object for the datetime field
372
-     * @return DateTime
373
-     */
374
-    public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current): DateTime
375
-    {
376
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
377
-        // Otherwise parse the string.
378
-        if ($time_to_set_string instanceof DateTime) {
379
-            $parsed = [
380
-                'hour'   => $time_to_set_string->format('H'),
381
-                'minute' => $time_to_set_string->format('i'),
382
-                'second' => $time_to_set_string->format('s'),
383
-            ];
384
-        } else {
385
-            // parse incoming string
386
-            $parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
387
-        }
388
-        EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
389
-        return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
390
-    }
391
-
392
-
393
-    /**
394
-     * Only sets the date portion of the datetime.
395
-     *
396
-     * @param string|DateTime $date_to_set_string like Friday, January 8th or a DateTime object.
397
-     * @param DateTime        $current            current DateTime object for the datetime field
398
-     * @return DateTime
399
-     */
400
-    public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current): DateTime
401
-    {
402
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
403
-        // Otherwise parse the string.
404
-        if ($date_to_set_string instanceof DateTime) {
405
-            $parsed = [
406
-                'year'  => $date_to_set_string->format('Y'),
407
-                'month' => $date_to_set_string->format('m'),
408
-                'day'   => $date_to_set_string->format('d'),
409
-            ];
410
-        } else {
411
-            // parse incoming string
412
-            $parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
413
-        }
414
-        EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
415
-        return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
416
-    }
417
-
418
-
419
-    /**
420
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).  When the
421
-     * datetime gets to this stage it should ALREADY be in UTC time
422
-     *
423
-     * @param DateTime $DateTime
424
-     * @return string formatted date time for given timezone
425
-     * @throws EE_Error
426
-     */
427
-    public function prepare_for_get($DateTime): string
428
-    {
429
-        return $this->_prepare_for_display($DateTime);
430
-    }
431
-
432
-
433
-    /**
434
-     * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
435
-     * from the set wp timezone.  If so, then it returns the datetime string formatted via
436
-     * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
437
-     * abbreviation to the date_string.
438
-     *
439
-     * @param mixed       $DateTime
440
-     * @param string|null $schema
441
-     * @return string
442
-     * @throws EE_Error
443
-     */
444
-    public function prepare_for_pretty_echoing($DateTime, ?string $schema = null): string
445
-    {
446
-        $schema = $schema ?: true;
447
-        return $this->_prepare_for_display($DateTime, $schema);
448
-    }
449
-
450
-
451
-    /**
452
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
453
-     * timezone).
454
-     *
455
-     * @param DateTime|null $DateTime
456
-     * @param bool|string   $schema
457
-     * @return string
458
-     * @throws EE_Error
459
-     * @throws Exception
460
-     */
461
-    protected function _prepare_for_display(?DateTime $DateTime, $schema = false): string
462
-    {
463
-        if (! $DateTime instanceof DateTime) {
464
-            if ($this->_nullable) {
465
-                return '';
466
-            }
467
-            if (WP_DEBUG) {
468
-                throw new EE_Error(
469
-                    sprintf(
470
-                        esc_html__(
471
-                            'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.',
472
-                            'event_espresso'
473
-                        ),
474
-                        $this->_nicename
475
-                    )
476
-                );
477
-            }
478
-            $DateTime = new DbSafeDateTime(EE_Datetime_Field::now);
479
-            EE_Error::add_error(
480
-                sprintf(
481
-                    esc_html__(
482
-                        'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.  When WP_DEBUG is false, the value is set to "now" instead of throwing an exception.',
483
-                        'event_espresso'
484
-                    ),
485
-                    $this->_nicename
486
-                ),
487
-                __FILE__,
488
-                __FUNCTION__,
489
-                __LINE__
490
-            );
491
-        }
492
-        $format_string = $this->_get_date_time_output($schema);
493
-        EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
494
-        if ($schema) {
495
-            $timezone_string = '';
496
-            if ($this->_display_timezone()) {
497
-                // must be explicit because schema could equal true.
498
-                if ($schema === 'no_html') {
499
-                    $timezone_string = ' (' . $DateTime->format('T') . ')';
500
-                } else {
501
-                    $timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
502
-                }
503
-            }
504
-
505
-            return $DateTime->format($format_string) . $timezone_string;
506
-        }
507
-        return $DateTime->format($format_string);
508
-    }
509
-
510
-
511
-    /**
512
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
513
-     * timezone).
514
-     *
515
-     * @param mixed $datetime_value u
516
-     * @return string mysql timestamp in UTC
517
-     * @throws EE_Error
518
-     * @throws Exception
519
-     */
520
-    public function prepare_for_use_in_db($datetime_value): ?string
521
-    {
522
-        // we allow an empty value or DateTime object, but nothing else.
523
-        if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
524
-            $datetime_value = $this->_get_date_object($datetime_value);
525
-            if (! $datetime_value instanceof DateTime) {
526
-                throw new EE_Error(
527
-                    sprintf(
528
-                        esc_html__(
529
-                            'The incoming value being prepared for setting in the database for the %1$s field must either be empty or a php DateTime object, instead of: %2$s %3$s',
530
-                            'event_espresso'
531
-                        ),
532
-                        $this->get_name(),
533
-                        '<br />',
534
-                        print_r($datetime_value, true)
535
-                    )
536
-                );
537
-            }
538
-        }
539
-
540
-        if ($datetime_value instanceof DateTime) {
541
-            if (! $datetime_value instanceof DbSafeDateTime) {
542
-                $datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
543
-            }
544
-            EEH_DTT_Helper::setTimezone($datetime_value, $this->get_UTC_DateTimeZone());
545
-            return $datetime_value->format(
546
-                EE_Datetime_Field::mysql_timestamp_format
547
-            );
548
-        }
549
-
550
-        // if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
551
-        return ! $this->_nullable
552
-            ? current_time('mysql', true)
553
-            : null;
554
-    }
555
-
556
-
557
-    /**
558
-     * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
559
-     * allowed)
560
-     *
561
-     * @param string $datetime_string mysql timestamp in UTC
562
-     * @return  bool|DbSafeDateTime|null
563
-     * @throws EE_Error
564
-     * @throws Exception
565
-     */
566
-    public function prepare_for_set_from_db($datetime_string)
567
-    {
568
-        // if $datetime_value is empty, and ! $this->_nullable, just use time()
569
-        if (empty($datetime_string) && $this->_nullable) {
570
-            return null;
571
-        }
572
-        // datetime strings from the db should ALWAYS be in UTC+0, so use UTC_DateTimeZone when creating
573
-        $DateTime = empty($datetime_string)
574
-            ? new DbSafeDateTime(EE_Datetime_Field::now, $this->get_UTC_DateTimeZone())
575
-            : DbSafeDateTime::createFromFormat(
576
-                EE_Datetime_Field::mysql_timestamp_format,
577
-                $datetime_string,
578
-                $this->get_UTC_DateTimeZone()
579
-            );
580
-
581
-        if (! $DateTime instanceof DbSafeDateTime) {
582
-            // if still no datetime object, then let's just use now
583
-            $DateTime = new DbSafeDateTime(EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
584
-        }
585
-        // THEN apply the field's set DateTimeZone
586
-        EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
587
-        return $DateTime;
588
-    }
589
-
590
-
591
-    /**
592
-     * All this method does is determine if we're going to display the timezone string or not on any output.
593
-     * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
594
-     * If so, then true.
595
-     *
596
-     * @return bool true for yes false for no
597
-     * @throws Exception
598
-     */
599
-    protected function _display_timezone(): bool
600
-    {
601
-        // first let's do a comparison of timezone strings.
602
-        // If they match then we can get out without any further calculations
603
-        $blog_string = get_option('timezone_string');
604
-        if ($blog_string === $this->_timezone_string) {
605
-            return false;
606
-        }
607
-        // now we need to calc the offset for the timezone string so we can compare with the blog offset.
608
-        $this_offset = $this->get_timezone_offset($this->_DateTimeZone);
609
-        $blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
610
-        // now compare
611
-        return $blog_offset !== $this_offset;
612
-    }
613
-
614
-
615
-    /**
616
-     * This method returns a php DateTime object for setting on the EE_Base_Class model.
617
-     * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
618
-     * with.
619
-     *
620
-     * @param int|string|DateTime $date_string            This should be the incoming date string.  It's assumed to be
621
-     *                                                    in the format that is set on the date_field (or DateTime
622
-     *                                                    object)!
623
-     * @return DateTime
624
-     * @throws Exception
625
-     * @throws Exception
626
-     */
627
-    protected function _get_date_object($date_string)
628
-    {
629
-        // first if this is an empty date_string and nullable is allowed, just return null.
630
-        if ($this->_nullable && empty($date_string)) {
631
-            return null;
632
-        }
633
-
634
-        // if incoming date
635
-        if ($date_string instanceof DateTime) {
636
-            EEH_DTT_Helper::setTimezone($date_string, $this->_DateTimeZone);
637
-            return $date_string;
638
-        }
639
-        // if empty date_string and made it here.
640
-        // Return a datetime object for now in the given timezone.
641
-        if (empty($date_string)) {
642
-            return new DbSafeDateTime(EE_Datetime_Field::now, $this->_DateTimeZone);
643
-        }
644
-        // if $date_string is matches something that looks like a Unix timestamp let's just use it.
645
-        if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
646
-            try {
647
-                // This is operating under the assumption that the incoming Unix timestamp
648
-                // is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
649
-                $DateTime = new DbSafeDateTime(EE_Datetime_Field::now, $this->_DateTimeZone);
650
-                $DateTime->setTimestamp($date_string);
651
-
652
-                return $DateTime;
653
-            } catch (Exception $e) {
654
-                // should be rare, but if things got fooled then let's just continue
655
-            }
656
-        }
657
-        // not a unix timestamp.  So we will use the set format on this object and set timezone to
658
-        // create the DateTime object.
659
-        $format = $this->_date_format . ' ' . $this->_time_format;
660
-        try {
661
-            $DateTime = DbSafeDateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
662
-            if (! $DateTime instanceof DbSafeDateTime) {
663
-                throw new EE_Error(
664
-                    sprintf(
665
-                        esc_html__(
666
-                            '"%1$s" does not represent a valid Date Time in the format "%2$s".',
667
-                            'event_espresso'
668
-                        ),
669
-                        $date_string,
670
-                        $format
671
-                    )
672
-                );
673
-            }
674
-        } catch (Exception $e) {
675
-            // if we made it here then likely then something went really wrong.
676
-            // Instead of throwing an exception, let's just return a DateTime object for now, in the set timezone.
677
-            $DateTime = new DbSafeDateTime(EE_Datetime_Field::now, $this->_DateTimeZone);
678
-        }
679
-
680
-        return $DateTime;
681
-    }
682
-
683
-
684
-    /**
685
-     * get_timezone_transitions
686
-     *
687
-     * @param DateTimeZone $DateTimeZone
688
-     * @param int|null     $time
689
-     * @param bool|null    $first_only
690
-     * @return array
691
-     */
692
-    public function get_timezone_transitions(
693
-        DateTimeZone $DateTimeZone,
694
-        ?int $time = null,
695
-        bool $first_only = true
696
-    ): array {
697
-        return EEH_DTT_Helper::get_timezone_transitions($DateTimeZone, $time, $first_only);
698
-    }
699
-
700
-
701
-    /**
702
-     * get_timezone_offset
703
-     *
704
-     * @param DateTimeZone    $DateTimeZone
705
-     * @param int|string|null $time
706
-     * @return mixed
707
-     * @throws DomainException
708
-     */
709
-    public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
710
-    {
711
-        return EEH_DTT_Helper::get_timezone_offset($DateTimeZone, $time);
712
-    }
713
-
714
-
715
-    /**
716
-     * This will take an incoming timezone string and return the abbreviation for that timezone
717
-     *
718
-     * @param string|null $timezone_string
719
-     * @return string           abbreviation
720
-     * @throws Exception
721
-     */
722
-    public function get_timezone_abbrev(?string $timezone_string = ''): string
723
-    {
724
-        $timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
725
-        $dateTime        = new DateTime(EE_Datetime_Field::now, new DateTimeZone($timezone_string));
726
-        return $dateTime->format('T');
727
-    }
728
-
729
-
730
-    /**
731
-     * Overrides the parent to allow for having a dynamic "now" value
732
-     *
733
-     * @return mixed
734
-     */
735
-    public function get_default_value()
736
-    {
737
-        if ($this->_default_value === EE_Datetime_Field::now) {
738
-            return time();
739
-        }
740
-        return parent::get_default_value();
741
-    }
742
-
743
-
744
-    /**
745
-     * Gets the default datetime object from the field's default time
746
-     *
747
-     * @return DbSafeDateTime|DateTime|null
748
-     * @throws InvalidArgumentException
749
-     * @throws InvalidDataTypeException
750
-     * @throws InvalidInterfaceException
751
-     * @throws Exception
752
-     * @since 4.9.66.p
753
-     */
754
-    public function getDefaultDateTimeObj()
755
-    {
756
-        $default_raw = $this->get_default_value();
757
-        if ($default_raw instanceof DateTime) {
758
-            return $default_raw;
759
-        }
760
-        if (is_null($default_raw)) {
761
-            return null;
762
-        }
763
-        $timezone_string = EEH_DTT_Helper::get_valid_timezone_string($this->get_timezone());
764
-        $timezone        = new DateTimeZone($timezone_string);
765
-
766
-        // can't pass unix timestamps directly to Datetime constructor
767
-        if (is_numeric($default_raw)) {
768
-            $datetime = new DbSafeDateTime();
769
-            $datetime->setTimestamp($default_raw);
770
-            return $datetime;
771
-        }
772
-        return new DbSafeDateTime($default_raw, $timezone);
773
-    }
774
-
775
-
776
-    public function getSchemaDescription(): string
777
-    {
778
-        return sprintf(
779
-            esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
780
-            $this->get_nicename()
781
-        );
782
-    }
22
+	/**
23
+	 * The pattern we're looking for is if only the characters 0-9 are found and there are only
24
+	 * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
25
+	 *
26
+	 * @type string unix_timestamp_regex
27
+	 */
28
+	const unix_timestamp_regex = '/[0-9]{10,}/';
29
+
30
+	/**
31
+	 * @type string mysql_timestamp_format
32
+	 */
33
+	const mysql_timestamp_format = 'Y-m-d H:i:s';
34
+
35
+	/**
36
+	 * @type string mysql_date_format
37
+	 */
38
+	const mysql_date_format = 'Y-m-d';
39
+
40
+	/**
41
+	 * @type string mysql_time_format
42
+	 */
43
+	const mysql_time_format = 'H:i:s';
44
+
45
+	/**
46
+	 * Const for using in the default value. If the field's default is set to this,
47
+	 * then we will return the time of calling `get_default_value()`, not
48
+	 * just the current time at construction
49
+	 */
50
+	const now = 'now';
51
+
52
+	/**
53
+	 * The following properties hold the default formats for date and time.
54
+	 * Defaults are set via the constructor and can be overridden on class instantiation.
55
+	 * However they can also be overridden later by the set_format() method
56
+	 * (and corresponding set_date_format, set_time_format methods);
57
+	 */
58
+
59
+	protected string $_date_format        = '';
60
+
61
+	protected string $_time_format        = '';
62
+
63
+	protected string $_pretty_date_format = '';
64
+
65
+	protected string $_pretty_time_format = '';
66
+
67
+	protected ?DateTimeZone $_DateTimeZone       = null;
68
+
69
+	protected ?DateTimeZone $_UTC_DateTimeZone   = null;
70
+
71
+	protected ?DateTimeZone $_blog_DateTimeZone  = null;
72
+
73
+
74
+	/**
75
+	 * This property holds how we want the output returned when getting a datetime string.  It is set for the
76
+	 * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
77
+	 * and time returned via getters.
78
+	 *
79
+	 * @var mixed (null|string)
80
+	 */
81
+	protected $_date_time_output;
82
+
83
+
84
+	/**
85
+	 * timezone string
86
+	 * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
87
+	 * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
88
+	 * coming out of the object to be in.  Default timezone is the current WP timezone option setting
89
+	 */
90
+	protected ?string $_timezone_string = null;
91
+
92
+
93
+	/**
94
+	 * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
95
+	 * offsets for comparison purposes).
96
+	 *
97
+	 * @var int
98
+	 */
99
+	protected int $_blog_offset = 0;
100
+
101
+
102
+	/**
103
+	 * @param string      $table_column
104
+	 * @param string      $nice_name
105
+	 * @param bool        $nullable
106
+	 * @param string|null $default_value
107
+	 * @param string|null $timezone_string
108
+	 * @param string|null $date_format
109
+	 * @param string|null $time_format
110
+	 * @param string|null $pretty_date_format
111
+	 * @param string|null $pretty_time_format
112
+	 * @throws InvalidArgumentException
113
+	 * @throws Exception
114
+	 */
115
+	public function __construct(
116
+		string $table_column,
117
+		string $nice_name,
118
+		bool $nullable,
119
+		?string $default_value,
120
+		?string $timezone_string = '',
121
+		?string $date_format = '',
122
+		?string $time_format = '',
123
+		?string $pretty_date_format = '',
124
+		?string $pretty_time_format = ''
125
+	) {
126
+		$this->set_date_format($date_format);
127
+		$this->set_time_format($time_format);
128
+		$this->set_date_format($pretty_date_format, true);
129
+		$this->set_time_format($pretty_time_format, true);
130
+
131
+		parent::__construct($table_column, $nice_name, $nullable, $default_value);
132
+		$this->set_timezone($timezone_string);
133
+		$this->setSchemaType(SchemaType::STRING);
134
+		$this->setSchemaFormat(SchemaFormat::DATETIME);
135
+	}
136
+
137
+
138
+	/**
139
+	 * @return DateTimeZone
140
+	 * @throws Exception
141
+	 */
142
+	public function get_UTC_DateTimeZone(): DateTimeZone
143
+	{
144
+		return $this->_UTC_DateTimeZone instanceof DateTimeZone
145
+			? $this->_UTC_DateTimeZone
146
+			: $this->_create_timezone_object_from_timezone_string('UTC');
147
+	}
148
+
149
+
150
+	/**
151
+	 * @return DateTimeZone
152
+	 * @throws Exception
153
+	 */
154
+	public function get_blog_DateTimeZone(): DateTimeZone
155
+	{
156
+		return $this->_blog_DateTimeZone instanceof DateTimeZone
157
+			? $this->_blog_DateTimeZone
158
+			: $this->_create_timezone_object_from_timezone_string();
159
+	}
160
+
161
+
162
+	/**
163
+	 * this prepares any incoming date data and make sure its converted to a utc unix timestamp
164
+	 *
165
+	 * @param string|int $value_inputted_for_field_on_model_object  could be a string formatted date time or int unix
166
+	 *                                                              timestamp
167
+	 * @return DateTime
168
+	 * @throws Exception
169
+	 */
170
+	public function prepare_for_set($value_inputted_for_field_on_model_object)
171
+	{
172
+		return $this->_get_date_object($value_inputted_for_field_on_model_object);
173
+	}
174
+
175
+
176
+	/**
177
+	 * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
178
+	 * getters need to know whether we're just returning the date or the time or both.  By default we return both.
179
+	 *
180
+	 * @param bool $pretty If we're returning the pretty formats or standard format string.
181
+	 * @return string    The final assembled format string.
182
+	 */
183
+	protected function _get_date_time_output(bool $pretty = false): string
184
+	{
185
+		switch ($this->_date_time_output) {
186
+			case 'time':
187
+				return $pretty
188
+					? $this->_pretty_time_format
189
+					: $this->_time_format;
190
+
191
+			case 'date':
192
+				return $pretty
193
+					? $this->_pretty_date_format
194
+					: $this->_date_format;
195
+
196
+			default:
197
+				return $pretty
198
+					? trim($this->_pretty_date_format . ' ' . $this->_pretty_time_format)
199
+					: trim($this->_date_format . ' ' . $this->_time_format);
200
+		}
201
+	}
202
+
203
+
204
+	/**
205
+	 * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
206
+	 * returned (using the format properties)
207
+	 *
208
+	 * @param string|null $what acceptable values are 'time' or 'date'.
209
+	 *                          Any other value will be set but will always result
210
+	 *                          in both 'date' and 'time' being returned.
211
+	 * @return void
212
+	 */
213
+	public function set_date_time_output(?string $what = null)
214
+	{
215
+		$this->_date_time_output = $what;
216
+	}
217
+
218
+
219
+	/**
220
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
221
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
222
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
223
+	 * We also set some other properties in this method.
224
+	 *
225
+	 * @param string|null $timezone_string A valid timezone string as described by @link
226
+	 *                                     http://www.php.net/manual/en/timezones.php
227
+	 * @return void
228
+	 * @throws InvalidArgumentException
229
+	 * @throws InvalidDataTypeException
230
+	 * @throws InvalidInterfaceException
231
+	 * @throws Exception
232
+	 */
233
+	public function set_timezone(?string $timezone_string = '')
234
+	{
235
+		if (empty($timezone_string) && $this->_timezone_string !== null) {
236
+			// leave the timezone AS-IS if we already have one and
237
+			// the function arg didn't provide one
238
+			return;
239
+		}
240
+		$timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
241
+		$this->_timezone_string = ! empty($timezone_string)
242
+			? $timezone_string
243
+			: 'UTC';
244
+		$this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
245
+	}
246
+
247
+
248
+	/**
249
+	 * _create_timezone_object_from_timezone_name
250
+	 *
251
+	 * @access protected
252
+	 * @param string|null $timezone_string
253
+	 * @return DateTimeZone
254
+	 * @throws InvalidArgumentException
255
+	 * @throws InvalidDataTypeException
256
+	 * @throws InvalidInterfaceException
257
+	 * @throws Exception
258
+	 */
259
+	protected function _create_timezone_object_from_timezone_string(?string $timezone_string = ''): DateTimeZone
260
+	{
261
+		return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
262
+	}
263
+
264
+
265
+	/**
266
+	 * This just returns whatever is set for the current timezone.
267
+	 *
268
+	 * @access public
269
+	 * @return string timezone string
270
+	 */
271
+	public function get_timezone(): ?string
272
+	{
273
+		return $this->_timezone_string;
274
+	}
275
+
276
+
277
+	/**
278
+	 * set the $_date_format property
279
+	 *
280
+	 * @access public
281
+	 * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
282
+	 * @param bool   $pretty Whether to set pretty format or not.
283
+	 * @return void
284
+	 */
285
+	public function set_date_format(string $format, bool $pretty = false)
286
+	{
287
+		if ($pretty) {
288
+			$this->_pretty_date_format = new DateFormat($format);
289
+		} else {
290
+			$this->_date_format = new DateFormat($format);
291
+		}
292
+	}
293
+
294
+
295
+	/**
296
+	 * return the $_date_format property value.
297
+	 *
298
+	 * @param bool $pretty Whether to get pretty format or not.
299
+	 * @return string
300
+	 */
301
+	public function get_date_format(bool $pretty = false): string
302
+	{
303
+		return $pretty
304
+			? $this->_pretty_date_format
305
+			: $this->_date_format;
306
+	}
307
+
308
+
309
+	/**
310
+	 * set the $_time_format property
311
+	 *
312
+	 * @access public
313
+	 * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
314
+	 * @param bool   $pretty Whether to set pretty format or not.
315
+	 * @return void
316
+	 */
317
+	public function set_time_format(string $format, bool $pretty = false)
318
+	{
319
+		if ($pretty) {
320
+			$this->_pretty_time_format = new TimeFormat($format);
321
+		} else {
322
+			$this->_time_format = new TimeFormat($format);
323
+		}
324
+	}
325
+
326
+
327
+	/**
328
+	 * return the $_time_format property value.
329
+	 *
330
+	 * @param bool $pretty Whether to get pretty format or not.
331
+	 * @return string
332
+	 */
333
+	public function get_time_format(bool $pretty = false): string
334
+	{
335
+		return $pretty
336
+			? $this->_pretty_time_format
337
+			: $this->_time_format;
338
+	}
339
+
340
+
341
+	/**
342
+	 * set the $_pretty_date_format property
343
+	 *
344
+	 * @access public
345
+	 * @param string|null $format a new pretty date format (corresponding to formats accepted by PHP date() function)
346
+	 * @return void
347
+	 */
348
+	public function set_pretty_date_format(?string $format)
349
+	{
350
+		$this->set_date_format($format, true);
351
+	}
352
+
353
+
354
+	/**
355
+	 * set the $_pretty_time_format property
356
+	 *
357
+	 * @access public
358
+	 * @param string|null $format a new pretty time format (corresponding to formats accepted by PHP date() function)
359
+	 * @return void
360
+	 */
361
+	public function set_pretty_time_format(?string $format)
362
+	{
363
+		$this->set_time_format($format, true);
364
+	}
365
+
366
+
367
+	/**
368
+	 * Only sets the time portion of the datetime.
369
+	 *
370
+	 * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
371
+	 * @param DateTime        $current            current DateTime object for the datetime field
372
+	 * @return DateTime
373
+	 */
374
+	public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current): DateTime
375
+	{
376
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
377
+		// Otherwise parse the string.
378
+		if ($time_to_set_string instanceof DateTime) {
379
+			$parsed = [
380
+				'hour'   => $time_to_set_string->format('H'),
381
+				'minute' => $time_to_set_string->format('i'),
382
+				'second' => $time_to_set_string->format('s'),
383
+			];
384
+		} else {
385
+			// parse incoming string
386
+			$parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
387
+		}
388
+		EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
389
+		return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
390
+	}
391
+
392
+
393
+	/**
394
+	 * Only sets the date portion of the datetime.
395
+	 *
396
+	 * @param string|DateTime $date_to_set_string like Friday, January 8th or a DateTime object.
397
+	 * @param DateTime        $current            current DateTime object for the datetime field
398
+	 * @return DateTime
399
+	 */
400
+	public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current): DateTime
401
+	{
402
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
403
+		// Otherwise parse the string.
404
+		if ($date_to_set_string instanceof DateTime) {
405
+			$parsed = [
406
+				'year'  => $date_to_set_string->format('Y'),
407
+				'month' => $date_to_set_string->format('m'),
408
+				'day'   => $date_to_set_string->format('d'),
409
+			];
410
+		} else {
411
+			// parse incoming string
412
+			$parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
413
+		}
414
+		EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
415
+		return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
416
+	}
417
+
418
+
419
+	/**
420
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).  When the
421
+	 * datetime gets to this stage it should ALREADY be in UTC time
422
+	 *
423
+	 * @param DateTime $DateTime
424
+	 * @return string formatted date time for given timezone
425
+	 * @throws EE_Error
426
+	 */
427
+	public function prepare_for_get($DateTime): string
428
+	{
429
+		return $this->_prepare_for_display($DateTime);
430
+	}
431
+
432
+
433
+	/**
434
+	 * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
435
+	 * from the set wp timezone.  If so, then it returns the datetime string formatted via
436
+	 * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
437
+	 * abbreviation to the date_string.
438
+	 *
439
+	 * @param mixed       $DateTime
440
+	 * @param string|null $schema
441
+	 * @return string
442
+	 * @throws EE_Error
443
+	 */
444
+	public function prepare_for_pretty_echoing($DateTime, ?string $schema = null): string
445
+	{
446
+		$schema = $schema ?: true;
447
+		return $this->_prepare_for_display($DateTime, $schema);
448
+	}
449
+
450
+
451
+	/**
452
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
453
+	 * timezone).
454
+	 *
455
+	 * @param DateTime|null $DateTime
456
+	 * @param bool|string   $schema
457
+	 * @return string
458
+	 * @throws EE_Error
459
+	 * @throws Exception
460
+	 */
461
+	protected function _prepare_for_display(?DateTime $DateTime, $schema = false): string
462
+	{
463
+		if (! $DateTime instanceof DateTime) {
464
+			if ($this->_nullable) {
465
+				return '';
466
+			}
467
+			if (WP_DEBUG) {
468
+				throw new EE_Error(
469
+					sprintf(
470
+						esc_html__(
471
+							'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.',
472
+							'event_espresso'
473
+						),
474
+						$this->_nicename
475
+					)
476
+				);
477
+			}
478
+			$DateTime = new DbSafeDateTime(EE_Datetime_Field::now);
479
+			EE_Error::add_error(
480
+				sprintf(
481
+					esc_html__(
482
+						'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.  When WP_DEBUG is false, the value is set to "now" instead of throwing an exception.',
483
+						'event_espresso'
484
+					),
485
+					$this->_nicename
486
+				),
487
+				__FILE__,
488
+				__FUNCTION__,
489
+				__LINE__
490
+			);
491
+		}
492
+		$format_string = $this->_get_date_time_output($schema);
493
+		EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
494
+		if ($schema) {
495
+			$timezone_string = '';
496
+			if ($this->_display_timezone()) {
497
+				// must be explicit because schema could equal true.
498
+				if ($schema === 'no_html') {
499
+					$timezone_string = ' (' . $DateTime->format('T') . ')';
500
+				} else {
501
+					$timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
502
+				}
503
+			}
504
+
505
+			return $DateTime->format($format_string) . $timezone_string;
506
+		}
507
+		return $DateTime->format($format_string);
508
+	}
509
+
510
+
511
+	/**
512
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
513
+	 * timezone).
514
+	 *
515
+	 * @param mixed $datetime_value u
516
+	 * @return string mysql timestamp in UTC
517
+	 * @throws EE_Error
518
+	 * @throws Exception
519
+	 */
520
+	public function prepare_for_use_in_db($datetime_value): ?string
521
+	{
522
+		// we allow an empty value or DateTime object, but nothing else.
523
+		if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
524
+			$datetime_value = $this->_get_date_object($datetime_value);
525
+			if (! $datetime_value instanceof DateTime) {
526
+				throw new EE_Error(
527
+					sprintf(
528
+						esc_html__(
529
+							'The incoming value being prepared for setting in the database for the %1$s field must either be empty or a php DateTime object, instead of: %2$s %3$s',
530
+							'event_espresso'
531
+						),
532
+						$this->get_name(),
533
+						'<br />',
534
+						print_r($datetime_value, true)
535
+					)
536
+				);
537
+			}
538
+		}
539
+
540
+		if ($datetime_value instanceof DateTime) {
541
+			if (! $datetime_value instanceof DbSafeDateTime) {
542
+				$datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
543
+			}
544
+			EEH_DTT_Helper::setTimezone($datetime_value, $this->get_UTC_DateTimeZone());
545
+			return $datetime_value->format(
546
+				EE_Datetime_Field::mysql_timestamp_format
547
+			);
548
+		}
549
+
550
+		// if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
551
+		return ! $this->_nullable
552
+			? current_time('mysql', true)
553
+			: null;
554
+	}
555
+
556
+
557
+	/**
558
+	 * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
559
+	 * allowed)
560
+	 *
561
+	 * @param string $datetime_string mysql timestamp in UTC
562
+	 * @return  bool|DbSafeDateTime|null
563
+	 * @throws EE_Error
564
+	 * @throws Exception
565
+	 */
566
+	public function prepare_for_set_from_db($datetime_string)
567
+	{
568
+		// if $datetime_value is empty, and ! $this->_nullable, just use time()
569
+		if (empty($datetime_string) && $this->_nullable) {
570
+			return null;
571
+		}
572
+		// datetime strings from the db should ALWAYS be in UTC+0, so use UTC_DateTimeZone when creating
573
+		$DateTime = empty($datetime_string)
574
+			? new DbSafeDateTime(EE_Datetime_Field::now, $this->get_UTC_DateTimeZone())
575
+			: DbSafeDateTime::createFromFormat(
576
+				EE_Datetime_Field::mysql_timestamp_format,
577
+				$datetime_string,
578
+				$this->get_UTC_DateTimeZone()
579
+			);
580
+
581
+		if (! $DateTime instanceof DbSafeDateTime) {
582
+			// if still no datetime object, then let's just use now
583
+			$DateTime = new DbSafeDateTime(EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
584
+		}
585
+		// THEN apply the field's set DateTimeZone
586
+		EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
587
+		return $DateTime;
588
+	}
589
+
590
+
591
+	/**
592
+	 * All this method does is determine if we're going to display the timezone string or not on any output.
593
+	 * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
594
+	 * If so, then true.
595
+	 *
596
+	 * @return bool true for yes false for no
597
+	 * @throws Exception
598
+	 */
599
+	protected function _display_timezone(): bool
600
+	{
601
+		// first let's do a comparison of timezone strings.
602
+		// If they match then we can get out without any further calculations
603
+		$blog_string = get_option('timezone_string');
604
+		if ($blog_string === $this->_timezone_string) {
605
+			return false;
606
+		}
607
+		// now we need to calc the offset for the timezone string so we can compare with the blog offset.
608
+		$this_offset = $this->get_timezone_offset($this->_DateTimeZone);
609
+		$blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
610
+		// now compare
611
+		return $blog_offset !== $this_offset;
612
+	}
613
+
614
+
615
+	/**
616
+	 * This method returns a php DateTime object for setting on the EE_Base_Class model.
617
+	 * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
618
+	 * with.
619
+	 *
620
+	 * @param int|string|DateTime $date_string            This should be the incoming date string.  It's assumed to be
621
+	 *                                                    in the format that is set on the date_field (or DateTime
622
+	 *                                                    object)!
623
+	 * @return DateTime
624
+	 * @throws Exception
625
+	 * @throws Exception
626
+	 */
627
+	protected function _get_date_object($date_string)
628
+	{
629
+		// first if this is an empty date_string and nullable is allowed, just return null.
630
+		if ($this->_nullable && empty($date_string)) {
631
+			return null;
632
+		}
633
+
634
+		// if incoming date
635
+		if ($date_string instanceof DateTime) {
636
+			EEH_DTT_Helper::setTimezone($date_string, $this->_DateTimeZone);
637
+			return $date_string;
638
+		}
639
+		// if empty date_string and made it here.
640
+		// Return a datetime object for now in the given timezone.
641
+		if (empty($date_string)) {
642
+			return new DbSafeDateTime(EE_Datetime_Field::now, $this->_DateTimeZone);
643
+		}
644
+		// if $date_string is matches something that looks like a Unix timestamp let's just use it.
645
+		if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
646
+			try {
647
+				// This is operating under the assumption that the incoming Unix timestamp
648
+				// is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
649
+				$DateTime = new DbSafeDateTime(EE_Datetime_Field::now, $this->_DateTimeZone);
650
+				$DateTime->setTimestamp($date_string);
651
+
652
+				return $DateTime;
653
+			} catch (Exception $e) {
654
+				// should be rare, but if things got fooled then let's just continue
655
+			}
656
+		}
657
+		// not a unix timestamp.  So we will use the set format on this object and set timezone to
658
+		// create the DateTime object.
659
+		$format = $this->_date_format . ' ' . $this->_time_format;
660
+		try {
661
+			$DateTime = DbSafeDateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
662
+			if (! $DateTime instanceof DbSafeDateTime) {
663
+				throw new EE_Error(
664
+					sprintf(
665
+						esc_html__(
666
+							'"%1$s" does not represent a valid Date Time in the format "%2$s".',
667
+							'event_espresso'
668
+						),
669
+						$date_string,
670
+						$format
671
+					)
672
+				);
673
+			}
674
+		} catch (Exception $e) {
675
+			// if we made it here then likely then something went really wrong.
676
+			// Instead of throwing an exception, let's just return a DateTime object for now, in the set timezone.
677
+			$DateTime = new DbSafeDateTime(EE_Datetime_Field::now, $this->_DateTimeZone);
678
+		}
679
+
680
+		return $DateTime;
681
+	}
682
+
683
+
684
+	/**
685
+	 * get_timezone_transitions
686
+	 *
687
+	 * @param DateTimeZone $DateTimeZone
688
+	 * @param int|null     $time
689
+	 * @param bool|null    $first_only
690
+	 * @return array
691
+	 */
692
+	public function get_timezone_transitions(
693
+		DateTimeZone $DateTimeZone,
694
+		?int $time = null,
695
+		bool $first_only = true
696
+	): array {
697
+		return EEH_DTT_Helper::get_timezone_transitions($DateTimeZone, $time, $first_only);
698
+	}
699
+
700
+
701
+	/**
702
+	 * get_timezone_offset
703
+	 *
704
+	 * @param DateTimeZone    $DateTimeZone
705
+	 * @param int|string|null $time
706
+	 * @return mixed
707
+	 * @throws DomainException
708
+	 */
709
+	public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
710
+	{
711
+		return EEH_DTT_Helper::get_timezone_offset($DateTimeZone, $time);
712
+	}
713
+
714
+
715
+	/**
716
+	 * This will take an incoming timezone string and return the abbreviation for that timezone
717
+	 *
718
+	 * @param string|null $timezone_string
719
+	 * @return string           abbreviation
720
+	 * @throws Exception
721
+	 */
722
+	public function get_timezone_abbrev(?string $timezone_string = ''): string
723
+	{
724
+		$timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
725
+		$dateTime        = new DateTime(EE_Datetime_Field::now, new DateTimeZone($timezone_string));
726
+		return $dateTime->format('T');
727
+	}
728
+
729
+
730
+	/**
731
+	 * Overrides the parent to allow for having a dynamic "now" value
732
+	 *
733
+	 * @return mixed
734
+	 */
735
+	public function get_default_value()
736
+	{
737
+		if ($this->_default_value === EE_Datetime_Field::now) {
738
+			return time();
739
+		}
740
+		return parent::get_default_value();
741
+	}
742
+
743
+
744
+	/**
745
+	 * Gets the default datetime object from the field's default time
746
+	 *
747
+	 * @return DbSafeDateTime|DateTime|null
748
+	 * @throws InvalidArgumentException
749
+	 * @throws InvalidDataTypeException
750
+	 * @throws InvalidInterfaceException
751
+	 * @throws Exception
752
+	 * @since 4.9.66.p
753
+	 */
754
+	public function getDefaultDateTimeObj()
755
+	{
756
+		$default_raw = $this->get_default_value();
757
+		if ($default_raw instanceof DateTime) {
758
+			return $default_raw;
759
+		}
760
+		if (is_null($default_raw)) {
761
+			return null;
762
+		}
763
+		$timezone_string = EEH_DTT_Helper::get_valid_timezone_string($this->get_timezone());
764
+		$timezone        = new DateTimeZone($timezone_string);
765
+
766
+		// can't pass unix timestamps directly to Datetime constructor
767
+		if (is_numeric($default_raw)) {
768
+			$datetime = new DbSafeDateTime();
769
+			$datetime->setTimestamp($default_raw);
770
+			return $datetime;
771
+		}
772
+		return new DbSafeDateTime($default_raw, $timezone);
773
+	}
774
+
775
+
776
+	public function getSchemaDescription(): string
777
+	{
778
+		return sprintf(
779
+			esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
780
+			$this->get_nicename()
781
+		);
782
+	}
783 783
 }
Please login to merge, or discard this patch.
core/db_models/fields/EE_Email_Field.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -15,40 +15,40 @@
 block discarded – undo
15 15
  */
16 16
 class EE_Email_Field extends EE_Text_Field_Base
17 17
 {
18
-    /**
19
-     * @param string $table_column
20
-     * @param string $nice_name
21
-     * @param bool   $nullable
22
-     * @param null   $default_value
23
-     * @throws InvalidArgumentException
24
-     */
25
-    public function __construct($table_column, $nice_name, $nullable, $default_value = null)
26
-    {
27
-        parent::__construct($table_column, $nice_name, $nullable, $default_value);
28
-        $this->setSchemaFormat(SchemaFormat::EMAIL);
29
-    }
18
+	/**
19
+	 * @param string $table_column
20
+	 * @param string $nice_name
21
+	 * @param bool   $nullable
22
+	 * @param null   $default_value
23
+	 * @throws InvalidArgumentException
24
+	 */
25
+	public function __construct($table_column, $nice_name, $nullable, $default_value = null)
26
+	{
27
+		parent::__construct($table_column, $nice_name, $nullable, $default_value);
28
+		$this->setSchemaFormat(SchemaFormat::EMAIL);
29
+	}
30 30
 
31 31
 
32
-    /**
33
-     * In form inputs, we should have called htmlentities and addslashes() on form inputs,
34
-     * so we need to undo that on setting of these fields
35
-     *
36
-     * @param string $email_address
37
-     * @return string
38
-     * @throws InvalidArgumentException
39
-     * @throws InvalidInterfaceException
40
-     * @throws InvalidDataTypeException
41
-     */
42
-    public function prepare_for_set($email_address)
43
-    {
44
-        if (empty($email_address)) {
45
-            return '';
46
-        }
47
-        try {
48
-            $email_address_obj = EmailAddressFactory::create($email_address);
49
-            return $email_address_obj instanceof EmailAddress ? $email_address_obj->get() : '';
50
-        } catch (EmailValidationException $e) {
51
-            return '';
52
-        }
53
-    }
32
+	/**
33
+	 * In form inputs, we should have called htmlentities and addslashes() on form inputs,
34
+	 * so we need to undo that on setting of these fields
35
+	 *
36
+	 * @param string $email_address
37
+	 * @return string
38
+	 * @throws InvalidArgumentException
39
+	 * @throws InvalidInterfaceException
40
+	 * @throws InvalidDataTypeException
41
+	 */
42
+	public function prepare_for_set($email_address)
43
+	{
44
+		if (empty($email_address)) {
45
+			return '';
46
+		}
47
+		try {
48
+			$email_address_obj = EmailAddressFactory::create($email_address);
49
+			return $email_address_obj instanceof EmailAddress ? $email_address_obj->get() : '';
50
+		} catch (EmailValidationException $e) {
51
+			return '';
52
+		}
53
+	}
54 54
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 1 patch
Indentation   +6677 added lines, -6677 removed lines patch added patch discarded remove patch
@@ -39,6686 +39,6686 @@
 block discarded – undo
39 39
  */
40 40
 abstract class EEM_Base extends EE_Base implements ResettableInterface
41 41
 {
42
-    /**
43
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
44
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
45
-     * They almost always WILL NOT, but it's not necessarily a requirement.
46
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
47
-     *
48
-     * @var boolean
49
-     */
50
-    private $_values_already_prepared_by_model_object = 0;
51
-
52
-    /**
53
-     * when $_values_already_prepared_by_model_object equals this, we assume
54
-     * the data is just like form input that needs to have the model fields'
55
-     * prepare_for_set and prepare_for_use_in_db called on it
56
-     */
57
-    const not_prepared_by_model_object = 0;
58
-
59
-    /**
60
-     * when $_values_already_prepared_by_model_object equals this, we
61
-     * assume this value is coming from a model object and doesn't need to have
62
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
63
-     */
64
-    const prepared_by_model_object = 1;
65
-
66
-    /**
67
-     * when $_values_already_prepared_by_model_object equals this, we assume
68
-     * the values are already to be used in the database (ie no processing is done
69
-     * on them by the model's fields)
70
-     */
71
-    const prepared_for_use_in_db = 2;
72
-
73
-
74
-    protected $singular_item = 'Item';
75
-
76
-    protected $plural_item   = 'Items';
77
-
78
-    /**
79
-     * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
80
-     */
81
-    protected $_tables;
82
-
83
-    /**
84
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
85
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
86
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
87
-     *
88
-     * @var EE_Model_Field_Base[][] $_fields
89
-     */
90
-    protected $_fields;
91
-
92
-    /**
93
-     * array of different kinds of relations
94
-     *
95
-     * @var EE_Model_Relation_Base[] $_model_relations
96
-     */
97
-    protected $_model_relations = [];
98
-
99
-    /**
100
-     * @var EE_Index[] $_indexes
101
-     */
102
-    protected $_indexes = [];
103
-
104
-    /**
105
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
106
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
107
-     * by setting the same columns as used in these queries in the query yourself.
108
-     *
109
-     * @var EE_Default_Where_Conditions
110
-     */
111
-    protected $_default_where_conditions_strategy;
112
-
113
-    /**
114
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
115
-     * This is particularly useful when you want something between 'none' and 'default'
116
-     *
117
-     * @var EE_Default_Where_Conditions
118
-     */
119
-    protected $_minimum_where_conditions_strategy;
120
-
121
-    /**
122
-     * String describing how to find the "owner" of this model's objects.
123
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
124
-     * But when there isn't, this indicates which related model, or transiently-related model,
125
-     * has the foreign key to the wp_users table.
126
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
127
-     * related to events, and events have a foreign key to wp_users.
128
-     * On EEM_Transaction, this would be 'Transaction.Event'
129
-     *
130
-     * @var string
131
-     */
132
-    protected $_model_chain_to_wp_user = '';
133
-
134
-    /**
135
-     * String describing how to find the model with a password controlling access to this model. This property has the
136
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
137
-     * This value is the path of models to follow to arrive at the model with the password field.
138
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
139
-     * model with a password that should affect reading this on the front-end.
140
-     * Eg this is an empty string for the Event model because it has a password.
141
-     * This is null for the Registration model, because its event's password has no bearing on whether
142
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
143
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
144
-     * should hide tickets for datetimes for events that have a password set.
145
-     *
146
-     * @var string |null
147
-     */
148
-    protected $model_chain_to_password = null;
149
-
150
-    /**
151
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
-     * don't need it (particularly CPT models)
153
-     *
154
-     * @var bool
155
-     */
156
-    protected $_ignore_where_strategy = false;
157
-
158
-    /**
159
-     * String used in caps relating to this model. Eg, if the caps relating to this
160
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
-     *
162
-     * @var string. If null it hasn't been initialized yet. If false then we
163
-     * have indicated capabilities don't apply to this
164
-     */
165
-    protected $_caps_slug = null;
166
-
167
-    /**
168
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
-     * and next-level keys are capability names, and each's value is a
170
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
-     * they specify which context to use (ie, frontend, backend, edit or delete)
172
-     * and then each capability in the corresponding sub-array that they're missing
173
-     * adds the where conditions onto the query.
174
-     *
175
-     * @var array
176
-     */
177
-    protected $_cap_restrictions = [
178
-        self::caps_read       => [],
179
-        self::caps_read_admin => [],
180
-        self::caps_edit       => [],
181
-        self::caps_delete     => [],
182
-    ];
183
-
184
-    /**
185
-     * Array defining which cap restriction generators to use to create default
186
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
187
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
-     * automatically set this to false (not just null).
190
-     *
191
-     * @var EE_Restriction_Generator_Base[]
192
-     */
193
-    protected $_cap_restriction_generators = [];
194
-
195
-    /**
196
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
-     */
198
-    const caps_read       = 'read';
199
-
200
-    const caps_read_admin = 'read_admin';
201
-
202
-    const caps_edit       = 'edit';
203
-
204
-    const caps_delete     = 'delete';
205
-
206
-    /**
207
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
-     * maps to 'read' because when looking for relevant permissions we're going to use
210
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
211
-     *
212
-     * @var array
213
-     */
214
-    protected $_cap_contexts_to_cap_action_map = [
215
-        self::caps_read       => 'read',
216
-        self::caps_read_admin => 'read',
217
-        self::caps_edit       => 'edit',
218
-        self::caps_delete     => 'delete',
219
-    ];
220
-
221
-    /**
222
-     * Timezone
223
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
-     * EE_Datetime_Field data type will have access to it.
227
-     *
228
-     * @var string
229
-     */
230
-    protected $_timezone;
231
-
232
-
233
-    /**
234
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
-     * multisite.
236
-     *
237
-     * @var int
238
-     */
239
-    protected static $_model_query_blog_id;
240
-
241
-    /**
242
-     * A copy of _fields, except the array keys are the model names pointed to by
243
-     * the field
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cache_foreign_key_to_fields = [];
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, indexed by their name
251
-     *
252
-     * @var EE_Model_Field_Base[]
253
-     */
254
-    private $_cached_fields = null;
255
-
256
-    /**
257
-     * Cached list of all the fields on the model, except those that are
258
-     * marked as only pertinent to the database
259
-     *
260
-     * @var EE_Model_Field_Base[]
261
-     */
262
-    private $_cached_fields_non_db_only = null;
263
-
264
-    /**
265
-     * A cached reference to the primary key for quick lookup
266
-     *
267
-     * @var EE_Model_Field_Base
268
-     */
269
-    private $_primary_key_field = null;
270
-
271
-    /**
272
-     * Flag indicating whether this model has a primary key or not
273
-     *
274
-     * @var boolean
275
-     */
276
-    protected $_has_primary_key_field = null;
277
-
278
-    /**
279
-     * array in the format:  [ FK alias => full PK ]
280
-     * where keys are local column name aliases for foreign keys
281
-     * and values are the fully qualified column name for the primary key they represent
282
-     *  ex:
283
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
-     *
285
-     * @var array $foreign_key_aliases
286
-     */
287
-    protected $foreign_key_aliases = [];
288
-
289
-    /**
290
-     * Whether or not this model is based off a table in WP core only (CPTs should set
291
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
-     * This should be true for models that deal with data that should exist independent of EE.
293
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
295
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
297
-     *
298
-     * @var boolean
299
-     */
300
-    protected $_wp_core_model = false;
301
-
302
-    /**
303
-     * @var bool stores whether this model has a password field or not.
304
-     * null until initialized by hasPasswordField()
305
-     */
306
-    protected $has_password_field;
307
-
308
-    /**
309
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
310
-     */
311
-    protected $password_field;
312
-
313
-    /**
314
-     *    List of valid operators that can be used for querying.
315
-     * The keys are all operators we'll accept, the values are the real SQL
316
-     * operators used
317
-     *
318
-     * @var array
319
-     */
320
-    protected $_valid_operators = [
321
-        '='           => '=',
322
-        '<='          => '<=',
323
-        '<'           => '<',
324
-        '>='          => '>=',
325
-        '>'           => '>',
326
-        '!='          => '!=',
327
-        'LIKE'        => 'LIKE',
328
-        'like'        => 'LIKE',
329
-        'NOT_LIKE'    => 'NOT LIKE',
330
-        'not_like'    => 'NOT LIKE',
331
-        'NOT LIKE'    => 'NOT LIKE',
332
-        'not like'    => 'NOT LIKE',
333
-        'IN'          => 'IN',
334
-        'in'          => 'IN',
335
-        'NOT_IN'      => 'NOT IN',
336
-        'not_in'      => 'NOT IN',
337
-        'NOT IN'      => 'NOT IN',
338
-        'not in'      => 'NOT IN',
339
-        'between'     => 'BETWEEN',
340
-        'BETWEEN'     => 'BETWEEN',
341
-        'IS_NOT_NULL' => 'IS NOT NULL',
342
-        'is_not_null' => 'IS NOT NULL',
343
-        'IS NOT NULL' => 'IS NOT NULL',
344
-        'is not null' => 'IS NOT NULL',
345
-        'IS_NULL'     => 'IS NULL',
346
-        'is_null'     => 'IS NULL',
347
-        'IS NULL'     => 'IS NULL',
348
-        'is null'     => 'IS NULL',
349
-        'REGEXP'      => 'REGEXP',
350
-        'regexp'      => 'REGEXP',
351
-        'NOT_REGEXP'  => 'NOT REGEXP',
352
-        'not_regexp'  => 'NOT REGEXP',
353
-        'NOT REGEXP'  => 'NOT REGEXP',
354
-        'not regexp'  => 'NOT REGEXP',
355
-    ];
356
-
357
-    /**
358
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
359
-     *
360
-     * @var array
361
-     */
362
-    protected $_in_style_operators = ['IN', 'NOT IN'];
363
-
364
-    /**
365
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
366
-     * '12-31-2012'"
367
-     *
368
-     * @var array
369
-     */
370
-    protected $_between_style_operators = ['BETWEEN'];
371
-
372
-    /**
373
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
374
-     *
375
-     * @var array
376
-     */
377
-    protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
378
-
379
-    /**
380
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
381
-     * on a join table.
382
-     *
383
-     * @var array
384
-     */
385
-    protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
386
-
387
-    /**
388
-     * Allowed values for $query_params['order'] for ordering in queries
389
-     *
390
-     * @var array
391
-     */
392
-    protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
393
-
394
-    /**
395
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
396
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
397
-     *
398
-     * @var array
399
-     */
400
-    private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
401
-
402
-    /**
403
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
404
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
405
-     *
406
-     * @var array
407
-     */
408
-    private $_allowed_query_params = [
409
-        0,
410
-        'limit',
411
-        'order_by',
412
-        'group_by',
413
-        'having',
414
-        'force_join',
415
-        'order',
416
-        'on_join_limit',
417
-        'default_where_conditions',
418
-        'caps',
419
-        'extra_selects',
420
-        'exclude_protected',
421
-    ];
422
-
423
-    /**
424
-     * All the data types that can be used in $wpdb->prepare statements.
425
-     *
426
-     * @var array
427
-     */
428
-    private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
429
-
430
-    /**
431
-     * @var EE_Registry $EE
432
-     */
433
-    protected $EE = null;
434
-
435
-
436
-    /**
437
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
438
-     *
439
-     * @var int
440
-     */
441
-    protected $_show_next_x_db_queries = 0;
442
-
443
-    /**
444
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
445
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
446
-     * WHERE, GROUP_BY, etc.
447
-     *
448
-     * @var CustomSelects
449
-     */
450
-    protected $_custom_selections = [];
451
-
452
-    /**
453
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
454
-     * caches every model object we've fetched from the DB on this request
455
-     *
456
-     * @var array
457
-     */
458
-    protected $_entity_map;
459
-
460
-    /**
461
-     * @var LoaderInterface
462
-     */
463
-    protected static $loader;
464
-
465
-    /**
466
-     * @var Mirror
467
-     */
468
-    private static $mirror;
469
-
470
-
471
-    /**
472
-     * constant used to show EEM_Base has not yet verified the db on this http request
473
-     */
474
-    const db_verified_none = 0;
475
-
476
-    /**
477
-     * constant used to show EEM_Base has verified the EE core db on this http request,
478
-     * but not the addons' dbs
479
-     */
480
-    const db_verified_core = 1;
481
-
482
-    /**
483
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
484
-     * the EE core db too)
485
-     */
486
-    const db_verified_addons = 2;
487
-
488
-    /**
489
-     * indicates whether an EEM_Base child has already re-verified the DB
490
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
491
-     * looking like EEM_Base::db_verified_*
492
-     *
493
-     * @var int - 0 = none, 1 = core, 2 = addons
494
-     */
495
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
496
-
497
-    /**
498
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
499
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
500
-     *        registrations for non-trashed tickets for non-trashed datetimes)
501
-     */
502
-    const default_where_conditions_all = 'all';
503
-
504
-    /**
505
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
506
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
507
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
508
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
509
-     *        models which share tables with other models, this can return data for the wrong model.
510
-     */
511
-    const default_where_conditions_this_only = 'this_model_only';
512
-
513
-    /**
514
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
515
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
516
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
517
-     */
518
-    const default_where_conditions_others_only = 'other_models_only';
519
-
520
-    /**
521
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
522
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
523
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
524
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
525
-     *        (regardless of whether those events and venues are trashed)
526
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
527
-     *        events.
528
-     */
529
-    const default_where_conditions_minimum_all = 'minimum';
530
-
531
-    /**
532
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
533
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
534
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
535
-     *        not)
536
-     */
537
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
538
-
539
-    /**
540
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
541
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
542
-     *        it's possible it will return table entries for other models. You should use
543
-     *        EEM_Base::default_where_conditions_minimum_all instead.
544
-     */
545
-    const default_where_conditions_none = 'none';
546
-
547
-
548
-    /**
549
-     * About all child constructors:
550
-     * they should define the _tables, _fields and _model_relations arrays.
551
-     * Should ALWAYS be called after child constructor.
552
-     * In order to make the child constructors to be as simple as possible, this parent constructor
553
-     * finalizes constructing all the object's attributes.
554
-     * Generally, rather than requiring a child to code
555
-     * $this->_tables = array(
556
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
557
-     *        ...);
558
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
559
-     * each EE_Table has a function to set the table's alias after the constructor, using
560
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
561
-     * do something similar.
562
-     *
563
-     * @param string|null $timezone
564
-     * @throws EE_Error
565
-     * @throws Exception
566
-     */
567
-    protected function __construct($timezone = '')
568
-    {
569
-        // check that the model has not been loaded too soon
570
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
-            throw new EE_Error(
572
-                sprintf(
573
-                    esc_html__(
574
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
575
-                        'event_espresso'
576
-                    ),
577
-                    get_class($this)
578
-                )
579
-            );
580
-        }
581
-        /**
582
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
-         */
584
-        if (empty(EEM_Base::$_model_query_blog_id)) {
585
-            EEM_Base::set_model_query_blog_id();
586
-        }
587
-        /**
588
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
-         * just use EE_Register_Model_Extension
590
-         *
591
-         * @var EE_Table_Base[] $_tables
592
-         */
593
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
-        foreach ($this->_tables as $table_alias => $table_obj) {
595
-            /** @var $table_obj EE_Table_Base */
596
-            $table_obj->_construct_finalize_with_alias($table_alias);
597
-            if ($table_obj instanceof EE_Secondary_Table) {
598
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
599
-            }
600
-        }
601
-        /**
602
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
603
-         * EE_Register_Model_Extension
604
-         *
605
-         * @param EE_Model_Field_Base[] $_fields
606
-         */
607
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
608
-        $this->_invalidate_field_caches();
609
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
610
-            if (! array_key_exists($table_alias, $this->_tables)) {
611
-                throw new EE_Error(
612
-                    sprintf(
613
-                        esc_html__(
614
-                            "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
615
-                            'event_espresso'
616
-                        ),
617
-                        $table_alias,
618
-                        implode(",", $this->_fields)
619
-                    )
620
-                );
621
-            }
622
-            foreach ($fields_for_table as $field_name => $field_obj) {
623
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
624
-                // primary key field base has a slightly different _construct_finalize
625
-                /** @var $field_obj EE_Model_Field_Base */
626
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
627
-            }
628
-        }
629
-        // everything is related to Extra_Meta
630
-        if (get_class($this) !== 'EEM_Extra_Meta') {
631
-            // make extra meta related to everything, but don't block deleting things just
632
-            // because they have related extra meta info. For now just orphan those extra meta
633
-            // in the future we should automatically delete them
634
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
635
-        }
636
-        // and change logs
637
-        if (get_class($this) !== 'EEM_Change_Log') {
638
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
639
-        }
640
-        /**
641
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
642
-         * EE_Register_Model_Extension
643
-         *
644
-         * @param EE_Model_Relation_Base[] $_model_relations
645
-         */
646
-        $this->_model_relations = (array) apply_filters(
647
-            'FHEE__' . get_class($this) . '__construct__model_relations',
648
-            $this->_model_relations
649
-        );
650
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
651
-            /** @var $relation_obj EE_Model_Relation_Base */
652
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
653
-        }
654
-        foreach ($this->_indexes as $index_name => $index_obj) {
655
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
656
-        }
657
-        $this->set_timezone($timezone);
658
-        // finalize default where condition strategy, or set default
659
-        if (! $this->_default_where_conditions_strategy) {
660
-            // nothing was set during child constructor, so set default
661
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
662
-        }
663
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
664
-        if (! $this->_minimum_where_conditions_strategy) {
665
-            // nothing was set during child constructor, so set default
666
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
667
-        }
668
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
669
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
670
-        // to indicate to NOT set it, set it to the logical default
671
-        if ($this->_caps_slug === null) {
672
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
673
-        }
674
-        // initialize the standard cap restriction generators if none were specified by the child constructor
675
-        if (is_array($this->_cap_restriction_generators)) {
676
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
677
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
678
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
679
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
680
-                        new EE_Restriction_Generator_Protected(),
681
-                        $cap_context,
682
-                        $this
683
-                    );
684
-                }
685
-            }
686
-        }
687
-        // if there are cap restriction generators, use them to make the default cap restrictions
688
-        if (is_array($this->_cap_restriction_generators)) {
689
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
690
-                if (! $generator_object) {
691
-                    continue;
692
-                }
693
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
694
-                    throw new EE_Error(
695
-                        sprintf(
696
-                            esc_html__(
697
-                                'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
698
-                                'event_espresso'
699
-                            ),
700
-                            $context,
701
-                            $this->get_this_model_name()
702
-                        )
703
-                    );
704
-                }
705
-                $action = $this->cap_action_for_context($context);
706
-                if (! $generator_object->construction_finalized()) {
707
-                    $generator_object->_construct_finalize($this, $action);
708
-                }
709
-            }
710
-        }
711
-        do_action('AHEE__' . get_class($this) . '__construct__end');
712
-    }
713
-
714
-
715
-    /**
716
-     * @return LoaderInterface
717
-     * @throws InvalidArgumentException
718
-     * @throws InvalidDataTypeException
719
-     * @throws InvalidInterfaceException
720
-     */
721
-    protected static function getLoader(): LoaderInterface
722
-    {
723
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
724
-            EEM_Base::$loader = LoaderFactory::getLoader();
725
-        }
726
-        return EEM_Base::$loader;
727
-    }
728
-
729
-
730
-    /**
731
-     * @return Mirror
732
-     * @since   5.0.0.p
733
-     */
734
-    private static function getMirror(): Mirror
735
-    {
736
-        if (! EEM_Base::$mirror instanceof Mirror) {
737
-            EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
738
-        }
739
-        return EEM_Base::$mirror;
740
-    }
741
-
742
-
743
-    /**
744
-     * @param string $model_class_Name
745
-     * @param string $timezone
746
-     * @return array
747
-     * @throws ReflectionException
748
-     * @since   5.0.0.p
749
-     */
750
-    private static function getModelArguments(string $model_class_Name, string $timezone): array
751
-    {
752
-        $arguments = [$timezone];
753
-        $params    = EEM_Base::getMirror()->getParameters($model_class_Name);
754
-        if (count($params) > 1) {
755
-            if ($params[1]->getName() === 'model_field_factory') {
756
-                $arguments = [
757
-                    $timezone,
758
-                    EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
759
-                ];
760
-            } elseif ($model_class_Name === 'EEM_Form_Section') {
761
-                $arguments = [
762
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
763
-                    $timezone,
764
-                ];
765
-            } elseif ($model_class_Name === 'EEM_Form_Element') {
766
-                $arguments = [
767
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
768
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
769
-                    $timezone,
770
-                ];
771
-            }
772
-        }
773
-        return $arguments;
774
-    }
775
-
776
-
777
-    /**
778
-     * This function is a singleton method used to instantiate the Espresso_model object
779
-     *
780
-     * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
781
-     *                                (and any incoming timezone data that gets saved).
782
-     *                                Note this just sends the timezone info to the date time model field objects.
783
-     *                                Default is NULL
784
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
785
-     * @return static (as in the concrete child class)
786
-     * @throws EE_Error
787
-     * @throws ReflectionException
788
-     */
789
-    public static function instance($timezone = '')
790
-    {
791
-        // check if instance of Espresso_model already exists
792
-        if (! static::$_instance instanceof static) {
793
-            $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
794
-            $model     = new static(...$arguments);
795
-            EEM_Base::getLoader()->share(static::class, $model, $arguments);
796
-            static::$_instance = $model;
797
-        }
798
-        // we might have a timezone set, let set_timezone decide what to do with it
799
-        if ($timezone) {
800
-            static::$_instance->set_timezone($timezone);
801
-        }
802
-        // Espresso_model object
803
-        return static::$_instance;
804
-    }
805
-
806
-
807
-    /**
808
-     * resets the model and returns it
809
-     *
810
-     * @param string|null $timezone
811
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
812
-     * all its properties reset; if it wasn't instantiated, returns null)
813
-     * @throws EE_Error
814
-     * @throws ReflectionException
815
-     * @throws InvalidArgumentException
816
-     * @throws InvalidDataTypeException
817
-     * @throws InvalidInterfaceException
818
-     */
819
-    public static function reset($timezone = '')
820
-    {
821
-        if (! static::$_instance instanceof EEM_Base) {
822
-            return null;
823
-        }
824
-        // Let's NOT swap out the current instance for a new one
825
-        // because if someone has a reference to it, we can't remove their reference.
826
-        // It's best to keep using the same reference but change the original object instead,
827
-        // so reset all its properties to their original values as defined in the class.
828
-        $static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
829
-        foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
830
-            // don't set instance to null like it was originally,
831
-            // but it's static anyways, and we're ignoring static properties (for now at least)
832
-            if (! isset($static_properties[ $property ])) {
833
-                static::$_instance->{$property} = $value;
834
-            }
835
-        }
836
-        // and then directly call its constructor again, like we would if we were creating a new one
837
-        $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
838
-        static::$_instance->__construct(...$arguments);
839
-        return self::instance();
840
-    }
841
-
842
-
843
-    /**
844
-     * Used to set the $_model_query_blog_id static property.
845
-     *
846
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
847
-     *                      value for get_current_blog_id() will be used.
848
-     */
849
-    public static function set_model_query_blog_id($blog_id = 0)
850
-    {
851
-        EEM_Base::$_model_query_blog_id = $blog_id > 0
852
-            ? (int) $blog_id
853
-            : get_current_blog_id();
854
-    }
855
-
856
-
857
-    /**
858
-     * Returns whatever is set as the internal $model_query_blog_id.
859
-     *
860
-     * @return int
861
-     */
862
-    public static function get_model_query_blog_id()
863
-    {
864
-        return EEM_Base::$_model_query_blog_id;
865
-    }
866
-
867
-
868
-    /**
869
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
870
-     *
871
-     * @param boolean $translated return localized strings or JUST the array.
872
-     * @return array
873
-     * @throws EE_Error
874
-     * @throws InvalidArgumentException
875
-     * @throws InvalidDataTypeException
876
-     * @throws InvalidInterfaceException
877
-     * @throws ReflectionException
878
-     */
879
-    public function status_array($translated = false)
880
-    {
881
-        if (! array_key_exists('Status', $this->_model_relations)) {
882
-            return [];
883
-        }
884
-        $model_name   = $this->get_this_model_name();
885
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
886
-        $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
887
-        $status_array = [];
888
-        foreach ($stati as $status) {
889
-            $status_array[ $status->ID() ] = $status->get('STS_code');
890
-        }
891
-        return $translated
892
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
893
-            : $status_array;
894
-    }
895
-
896
-
897
-    /**
898
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
899
-     *
900
-     * @param array $query_params             @see
901
-     *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
-     *                                        or if you have the development copy of EE you can view this at the path:
903
-     *                                        /docs/G--Model-System/model-query-params.md
904
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
905
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
906
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
907
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
908
-     *                                        EEM_Transaction::instance()->get_all( array( array(
909
-     *                                        'OR'=>array(
910
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
911
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
912
-     *                                        )
913
-     *                                        ),
914
-     *                                        'limit'=>10,
915
-     *                                        'group_by'=>'TXN_ID'
916
-     *                                        ));
917
-     *                                        get all the answers to the question titled "shirt size" for event with id
918
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
919
-     *                                        'Question.QST_display_text'=>'shirt size',
920
-     *                                        'Registration.Event.EVT_ID'=>12
921
-     *                                        ),
922
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
923
-     *                                        ));
924
-     * @throws EE_Error
925
-     * @throws ReflectionException
926
-     */
927
-    public function get_all($query_params = [])
928
-    {
929
-        if (
930
-            isset($query_params['limit'])
931
-            && ! isset($query_params['group_by'])
932
-        ) {
933
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
-        }
935
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
936
-    }
937
-
938
-
939
-    /**
940
-     * Modifies the query parameters so we only get back model objects
941
-     * that "belong" to the current user
942
-     *
943
-     * @param array $query_params @see
944
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
945
-     * @return array @see
946
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
947
-     * @throws ReflectionException
948
-     * @throws ReflectionException
949
-     */
950
-    public function alter_query_params_to_only_include_mine($query_params = [])
951
-    {
952
-        $wp_user_field_name = $this->wp_user_field_name();
953
-        if ($wp_user_field_name) {
954
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
955
-        }
956
-        return $query_params;
957
-    }
958
-
959
-
960
-    /**
961
-     * Returns the name of the field's name that points to the WP_User table
962
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
963
-     * foreign key to the WP_User table)
964
-     *
965
-     * @return string|boolean string on success, boolean false when there is no
966
-     * foreign key to the WP_User table
967
-     * @throws ReflectionException
968
-     * @throws ReflectionException
969
-     */
970
-    public function wp_user_field_name()
971
-    {
972
-        try {
973
-            if (! empty($this->_model_chain_to_wp_user)) {
974
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
975
-                $last_model_name              = end($models_to_follow_to_wp_users);
976
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
977
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
978
-            } else {
979
-                $model_with_fk_to_wp_users = $this;
980
-                $model_chain_to_wp_user    = '';
981
-            }
982
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
983
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
984
-        } catch (EE_Error $e) {
985
-            return false;
986
-        }
987
-    }
988
-
989
-
990
-    /**
991
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
992
-     * (or transiently-related model) has a foreign key to the wp_users table;
993
-     * useful for finding if model objects of this type are 'owned' by the current user.
994
-     * This is an empty string when the foreign key is on this model and when it isn't,
995
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
996
-     * (or transiently-related model)
997
-     *
998
-     * @return string
999
-     */
1000
-    public function model_chain_to_wp_user()
1001
-    {
1002
-        return $this->_model_chain_to_wp_user;
1003
-    }
1004
-
1005
-
1006
-    /**
1007
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1008
-     * like how registrations don't have a foreign key to wp_users, but the
1009
-     * events they are for are), or is unrelated to wp users.
1010
-     * generally available
1011
-     *
1012
-     * @return boolean
1013
-     */
1014
-    public function is_owned()
1015
-    {
1016
-        if ($this->model_chain_to_wp_user()) {
1017
-            return true;
1018
-        }
1019
-        try {
1020
-            $this->get_foreign_key_to('WP_User');
1021
-            return true;
1022
-        } catch (EE_Error $e) {
1023
-            return false;
1024
-        }
1025
-    }
1026
-
1027
-
1028
-    /**
1029
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
-     * the model)
1032
-     *
1033
-     * @param array  $query_params      @see
1034
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1035
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
-     * @param mixed  $columns_to_select What columns to select. By default, we select all columns specified by the
1037
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1038
-     *                                  override this and set the select to "*", or a specific column name, like
1039
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
-     *                                  the aliases used to refer to this selection, and values are to be
1042
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
-     * @throws EE_Error
1046
-     * @throws InvalidArgumentException
1047
-     * @throws ReflectionException
1048
-     */
1049
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1050
-    {
1051
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1052
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1053
-        $select_expressions       = $columns_to_select === null
1054
-            ? $this->_construct_default_select_sql($model_query_info)
1055
-            : '';
1056
-        if ($this->_custom_selections instanceof CustomSelects) {
1057
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1058
-            $select_expressions .= $select_expressions
1059
-                ? ', ' . $custom_expressions
1060
-                : $custom_expressions;
1061
-        }
1062
-
1063
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1064
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1065
-    }
1066
-
1067
-
1068
-    /**
1069
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1070
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1071
-     * method of including extra select information.
1072
-     *
1073
-     * @param array             $query_params
1074
-     * @param null|array|string $columns_to_select
1075
-     * @return null|CustomSelects
1076
-     * @throws InvalidArgumentException
1077
-     */
1078
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1079
-    {
1080
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1081
-            return null;
1082
-        }
1083
-        $selects = $query_params['extra_selects'] ?? $columns_to_select;
1084
-        $selects = is_string($selects)
1085
-            ? explode(',', $selects)
1086
-            : $selects;
1087
-        return new CustomSelects($selects);
1088
-    }
1089
-
1090
-
1091
-    /**
1092
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1093
-     * but you can use the model query params to more easily
1094
-     * take care of joins, field preparation etc.
1095
-     *
1096
-     * @param array  $query_params      @see
1097
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1098
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1099
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1100
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1101
-     *                                  override this and set the select to "*", or a specific column name, like
1102
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1103
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1104
-     *                                  the aliases used to refer to this selection, and values are to be
1105
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1106
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1107
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1108
-     * @throws EE_Error
1109
-     * @throws ReflectionException
1110
-     */
1111
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1112
-    {
1113
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1114
-    }
1115
-
1116
-
1117
-    /**
1118
-     * For creating a custom select statement
1119
-     *
1120
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1121
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1122
-     *                                 SQL, and 1=>is the datatype
1123
-     * @return string
1124
-     * @throws EE_Error
1125
-     */
1126
-    private function _construct_select_from_input($columns_to_select)
1127
-    {
1128
-        if (is_array($columns_to_select)) {
1129
-            $select_sql_array = [];
1130
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1131
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1132
-                    throw new EE_Error(
1133
-                        sprintf(
1134
-                            esc_html__(
1135
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1136
-                                'event_espresso'
1137
-                            ),
1138
-                            $selection_and_datatype,
1139
-                            $alias
1140
-                        )
1141
-                    );
1142
-                }
1143
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1144
-                    throw new EE_Error(
1145
-                        sprintf(
1146
-                            esc_html__(
1147
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1148
-                                'event_espresso'
1149
-                            ),
1150
-                            $selection_and_datatype[1],
1151
-                            $selection_and_datatype[0],
1152
-                            $alias,
1153
-                            implode(', ', $this->_valid_wpdb_data_types)
1154
-                        )
1155
-                    );
1156
-                }
1157
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1158
-            }
1159
-            $columns_to_select_string = implode(', ', $select_sql_array);
1160
-        } else {
1161
-            $columns_to_select_string = $columns_to_select;
1162
-        }
1163
-        return $columns_to_select_string;
1164
-    }
1165
-
1166
-
1167
-    /**
1168
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1169
-     *
1170
-     * @return string
1171
-     * @throws EE_Error
1172
-     */
1173
-    public function primary_key_name()
1174
-    {
1175
-        return $this->get_primary_key_field()->get_name();
1176
-    }
1177
-
1178
-
1179
-    /**
1180
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1181
-     * If there is no primary key on this model, $id is treated as primary key string
1182
-     *
1183
-     * @param mixed $id int or string, depending on the type of the model's primary key
1184
-     * @return EE_Base_Class|mixed|null
1185
-     * @throws EE_Error
1186
-     * @throws ReflectionException
1187
-     */
1188
-    public function get_one_by_ID($id)
1189
-    {
1190
-        // since entities with no ID can still have properties, we need to check the cache for them
1191
-        $cached_value = $this->get_from_entity_map($id);
1192
-        if ($cached_value) {
1193
-            return $cached_value;
1194
-        }
1195
-        // but if no cahced property AND no id is passed, just return null
1196
-        if (empty($id)) {
1197
-            return null;
1198
-        }
1199
-        $model_object = $this->get_one(
1200
-            $this->alter_query_params_to_restrict_by_ID(
1201
-                $id,
1202
-                ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1203
-            )
1204
-        );
1205
-        $className    = $this->_get_class_name();
1206
-        if ($model_object instanceof $className) {
1207
-            // make sure valid objects get added to the entity map
1208
-            // so that the next call to this method doesn't trigger another trip to the db
1209
-            $this->add_to_entity_map($model_object);
1210
-        }
1211
-        return $model_object;
1212
-    }
1213
-
1214
-
1215
-    /**
1216
-     * Alters query parameters to only get items with this ID are returned.
1217
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1218
-     * or could just be a simple primary key ID
1219
-     *
1220
-     * @param int   $id
1221
-     * @param array $query_params
1222
-     * @return array of normal query params, @see
1223
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1224
-     * @throws EE_Error
1225
-     */
1226
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1227
-    {
1228
-        if (! isset($query_params[0])) {
1229
-            $query_params[0] = [];
1230
-        }
1231
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1232
-        if ($conditions_from_id === null) {
1233
-            $query_params[0][ $this->primary_key_name() ] = $id;
1234
-        } else {
1235
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1236
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1237
-        }
1238
-        return $query_params;
1239
-    }
1240
-
1241
-
1242
-    /**
1243
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1244
-     * array. If no item is found, null is returned.
1245
-     *
1246
-     * @param array $query_params like EEM_Base's $query_params variable.
1247
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1248
-     * @throws EE_Error
1249
-     * @throws ReflectionException
1250
-     */
1251
-    public function get_one($query_params = [])
1252
-    {
1253
-        if (! is_array($query_params)) {
1254
-            EE_Error::doing_it_wrong(
1255
-                'EEM_Base::get_one',
1256
-                sprintf(
1257
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1258
-                    gettype($query_params)
1259
-                ),
1260
-                '4.6.0'
1261
-            );
1262
-            $query_params = [];
1263
-        }
1264
-        $query_params['limit'] = 1;
1265
-        $items                 = $this->get_all($query_params);
1266
-        if (empty($items)) {
1267
-            return null;
1268
-        }
1269
-        return array_shift($items);
1270
-    }
1271
-
1272
-
1273
-    /**
1274
-     * Returns the next x number of items in sequence from the given value as
1275
-     * found in the database matching the given query conditions.
1276
-     *
1277
-     * @param mixed $current_field_value    Value used for the reference point.
1278
-     * @param null  $field_to_order_by      What field is used for the
1279
-     *                                      reference point.
1280
-     * @param int   $limit                  How many to return.
1281
-     * @param array $query_params           Extra conditions on the query.
1282
-     * @param null  $columns_to_select      If left null, then an array of
1283
-     *                                      EE_Base_Class objects is returned,
1284
-     *                                      otherwise you can indicate just the
1285
-     *                                      columns you want returned.
1286
-     * @return EE_Base_Class[]|array
1287
-     * @throws EE_Error
1288
-     * @throws ReflectionException
1289
-     */
1290
-    public function next_x(
1291
-        $current_field_value,
1292
-        $field_to_order_by = null,
1293
-        $limit = 1,
1294
-        $query_params = [],
1295
-        $columns_to_select = null
1296
-    ) {
1297
-        return $this->_get_consecutive(
1298
-            $current_field_value,
1299
-            '>',
1300
-            $field_to_order_by,
1301
-            $limit,
1302
-            $query_params,
1303
-            $columns_to_select
1304
-        );
1305
-    }
1306
-
1307
-
1308
-    /**
1309
-     * Returns the previous x number of items in sequence from the given value
1310
-     * as found in the database matching the given query conditions.
1311
-     *
1312
-     * @param mixed $current_field_value    Value used for the reference point.
1313
-     * @param null  $field_to_order_by      What field is used for the
1314
-     *                                      reference point.
1315
-     * @param int   $limit                  How many to return.
1316
-     * @param array $query_params           Extra conditions on the query.
1317
-     * @param null  $columns_to_select      If left null, then an array of
1318
-     *                                      EE_Base_Class objects is returned,
1319
-     *                                      otherwise you can indicate just the
1320
-     *                                      columns you want returned.
1321
-     * @return EE_Base_Class[]|array
1322
-     * @throws EE_Error
1323
-     * @throws ReflectionException
1324
-     */
1325
-    public function previous_x(
1326
-        $current_field_value,
1327
-        $field_to_order_by = null,
1328
-        $limit = 1,
1329
-        $query_params = [],
1330
-        $columns_to_select = null
1331
-    ) {
1332
-        return $this->_get_consecutive(
1333
-            $current_field_value,
1334
-            '<',
1335
-            $field_to_order_by,
1336
-            $limit,
1337
-            $query_params,
1338
-            $columns_to_select
1339
-        );
1340
-    }
1341
-
1342
-
1343
-    /**
1344
-     * Returns the next item in sequence from the given value as found in the
1345
-     * database matching the given query conditions.
1346
-     *
1347
-     * @param mixed $current_field_value    Value used for the reference point.
1348
-     * @param null  $field_to_order_by      What field is used for the
1349
-     *                                      reference point.
1350
-     * @param array $query_params           Extra conditions on the query.
1351
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1352
-     *                                      object is returned, otherwise you
1353
-     *                                      can indicate just the columns you
1354
-     *                                      want and a single array indexed by
1355
-     *                                      the columns will be returned.
1356
-     * @return EE_Base_Class|null|array()
1357
-     * @throws EE_Error
1358
-     * @throws ReflectionException
1359
-     */
1360
-    public function next(
1361
-        $current_field_value,
1362
-        $field_to_order_by = null,
1363
-        $query_params = [],
1364
-        $columns_to_select = null
1365
-    ) {
1366
-        $results = $this->_get_consecutive(
1367
-            $current_field_value,
1368
-            '>',
1369
-            $field_to_order_by,
1370
-            1,
1371
-            $query_params,
1372
-            $columns_to_select
1373
-        );
1374
-        return empty($results)
1375
-            ? null
1376
-            : reset($results);
1377
-    }
1378
-
1379
-
1380
-    /**
1381
-     * Returns the previous item in sequence from the given value as found in
1382
-     * the database matching the given query conditions.
1383
-     *
1384
-     * @param mixed $current_field_value    Value used for the reference point.
1385
-     * @param null  $field_to_order_by      What field is used for the
1386
-     *                                      reference point.
1387
-     * @param array $query_params           Extra conditions on the query.
1388
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1389
-     *                                      object is returned, otherwise you
1390
-     *                                      can indicate just the columns you
1391
-     *                                      want and a single array indexed by
1392
-     *                                      the columns will be returned.
1393
-     * @return EE_Base_Class|null|array()
1394
-     * @throws EE_Error
1395
-     * @throws ReflectionException
1396
-     */
1397
-    public function previous(
1398
-        $current_field_value,
1399
-        $field_to_order_by = null,
1400
-        $query_params = [],
1401
-        $columns_to_select = null
1402
-    ) {
1403
-        $results = $this->_get_consecutive(
1404
-            $current_field_value,
1405
-            '<',
1406
-            $field_to_order_by,
1407
-            1,
1408
-            $query_params,
1409
-            $columns_to_select
1410
-        );
1411
-        return empty($results)
1412
-            ? null
1413
-            : reset($results);
1414
-    }
1415
-
1416
-
1417
-    /**
1418
-     * Returns the a consecutive number of items in sequence from the given
1419
-     * value as found in the database matching the given query conditions.
1420
-     *
1421
-     * @param mixed  $current_field_value   Value used for the reference point.
1422
-     * @param string $operand               What operand is used for the sequence.
1423
-     * @param string $field_to_order_by     What field is used for the reference point.
1424
-     * @param int    $limit                 How many to return.
1425
-     * @param array  $query_params          Extra conditions on the query.
1426
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1427
-     *                                      otherwise you can indicate just the columns you want returned.
1428
-     * @return EE_Base_Class[]|array
1429
-     * @throws EE_Error
1430
-     * @throws ReflectionException
1431
-     */
1432
-    protected function _get_consecutive(
1433
-        $current_field_value,
1434
-        $operand = '>',
1435
-        $field_to_order_by = null,
1436
-        $limit = 1,
1437
-        $query_params = [],
1438
-        $columns_to_select = null
1439
-    ) {
1440
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1441
-        if (empty($field_to_order_by)) {
1442
-            if ($this->has_primary_key_field()) {
1443
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1444
-            } else {
1445
-                if (WP_DEBUG) {
1446
-                    throw new EE_Error(
1447
-                        esc_html__(
1448
-                            'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1449
-                            'event_espresso'
1450
-                        )
1451
-                    );
1452
-                }
1453
-                EE_Error::add_error(
1454
-                    esc_html__('There was an error with the query.', 'event_espresso'),
1455
-                    __FILE__,
1456
-                    __FUNCTION__,
1457
-                    __LINE__
1458
-                );
1459
-                return [];
1460
-            }
1461
-        }
1462
-        if (! is_array($query_params)) {
1463
-            EE_Error::doing_it_wrong(
1464
-                'EEM_Base::_get_consecutive',
1465
-                sprintf(
1466
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1467
-                    gettype($query_params)
1468
-                ),
1469
-                '4.6.0'
1470
-            );
1471
-            $query_params = [];
1472
-        }
1473
-        // let's add the where query param for consecutive look up.
1474
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1475
-        $query_params['limit']                 = $limit;
1476
-        // set direction
1477
-        $incoming_orderby         = isset($query_params['order_by'])
1478
-            ? (array) $query_params['order_by']
1479
-            : [];
1480
-        $query_params['order_by'] = $operand === '>'
1481
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1482
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1483
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1484
-        if (empty($columns_to_select)) {
1485
-            return $this->get_all($query_params);
1486
-        }
1487
-        // getting just the fields
1488
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1489
-    }
1490
-
1491
-
1492
-    /**
1493
-     * This sets the _timezone property after model object has been instantiated.
1494
-     *
1495
-     * @param string|null $timezone valid PHP DateTimeZone timezone string
1496
-     * @throws Exception
1497
-     */
1498
-    public function set_timezone(?string $timezone = '')
1499
-    {
1500
-        if (! $timezone) {
1501
-            return;
1502
-        }
1503
-        $this->_timezone = $timezone;
1504
-        // note we need to loop through relations and set the timezone on those objects as well.
1505
-        foreach ($this->_model_relations as $relation) {
1506
-            $relation->set_timezone($timezone);
1507
-        }
1508
-        // and finally we do the same for any datetime fields
1509
-        foreach ($this->_fields as $field) {
1510
-            if ($field instanceof EE_Datetime_Field) {
1511
-                $field->set_timezone($timezone);
1512
-            }
1513
-        }
1514
-    }
1515
-
1516
-
1517
-    /**
1518
-     * This just returns whatever is set for the current timezone.
1519
-     *
1520
-     * @access public
1521
-     * @return string
1522
-     * @throws Exception
1523
-     */
1524
-    public function get_timezone()
1525
-    {
1526
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1527
-        if (empty($this->_timezone)) {
1528
-            foreach ($this->_fields as $field) {
1529
-                if ($field instanceof EE_Datetime_Field) {
1530
-                    $this->set_timezone($field->get_timezone());
1531
-                    break;
1532
-                }
1533
-            }
1534
-        }
1535
-        // if timezone STILL empty then return the default timezone for the site.
1536
-        if (empty($this->_timezone)) {
1537
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1538
-        }
1539
-        return $this->_timezone;
1540
-    }
1541
-
1542
-
1543
-    /**
1544
-     * This returns the date formats set for the given field name and also ensures that
1545
-     * $this->_timezone property is set correctly.
1546
-     *
1547
-     * @param string $field_name The name of the field the formats are being retrieved for.
1548
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1549
-     * @return array formats in an array with the date format first, and the time format last.
1550
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1551
-     * @since 4.6.x
1552
-     */
1553
-    public function get_formats_for($field_name, $pretty = false)
1554
-    {
1555
-        $field_settings = $this->field_settings_for($field_name);
1556
-        // if not a valid EE_Datetime_Field then throw error
1557
-        if (! $field_settings instanceof EE_Datetime_Field) {
1558
-            throw new EE_Error(
1559
-                sprintf(
1560
-                    esc_html__(
1561
-                        'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1562
-                        'event_espresso'
1563
-                    ),
1564
-                    $field_name
1565
-                )
1566
-            );
1567
-        }
1568
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1569
-        // the field.
1570
-        $this->_timezone = $field_settings->get_timezone();
1571
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1572
-    }
1573
-
1574
-
1575
-    /**
1576
-     * This returns the current time in a format setup for a query on this model.
1577
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1578
-     * it will return:
1579
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1580
-     *  NOW
1581
-     *  - or a unix timestamp (equivalent to time())
1582
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1583
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1584
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1585
-     *
1586
-     * @param string $field_name       The field the current time is needed for.
1587
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1588
-     *                                 formatted string matching the set format for the field in the set timezone will
1589
-     *                                 be returned.
1590
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1591
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1592
-     *                                 exception is triggered.
1593
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1594
-     * @throws Exception
1595
-     * @since 4.6.x
1596
-     */
1597
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1598
-    {
1599
-        $formats  = $this->get_formats_for($field_name);
1600
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1601
-        if ($timestamp) {
1602
-            return $DateTime->format('U');
1603
-        }
1604
-        // not returning timestamp, so return formatted string in timezone.
1605
-        switch ($what) {
1606
-            case 'time':
1607
-                return $DateTime->format($formats[1]);
1608
-            case 'date':
1609
-                return $DateTime->format($formats[0]);
1610
-            default:
1611
-                return $DateTime->format(implode(' ', $formats));
1612
-        }
1613
-    }
1614
-
1615
-
1616
-    /**
1617
-     * This receives a time string for a given field and ensures
1618
-     * that it is set up to match what the internal settings for the model are.
1619
-     * Returns a DateTime object.
1620
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1621
-     * (functionally the equivalent of UTC+0).
1622
-     * So when you send it in, whatever timezone string you include is ignored.
1623
-     *
1624
-     * @param string      $field_name      The field being setup.
1625
-     * @param string      $timestring      The date time string being used.
1626
-     * @param string      $incoming_format The format for the time string.
1627
-     * @param string|null $timezone_string By default, it is assumed the incoming time string is in timezone for
1628
-     *                                     the blog.  If this is not the case, then it can be specified here.  If
1629
-     *                                     incoming format is
1630
-     *                                     'U', this is ignored.
1631
-     * @return DbSafeDateTime
1632
-     * @throws EE_Error
1633
-     * @throws Exception
1634
-     */
1635
-    public function convert_datetime_for_query(
1636
-        string $field_name,
1637
-        string $timestring,
1638
-        string $incoming_format,
1639
-        ?string $timezone_string = ''
1640
-    ): DbSafeDateTime {
1641
-        // just using this to ensure the timezone is set correctly internally
1642
-        $this->get_formats_for($field_name);
1643
-        // load EEH_DTT_Helper
1644
-        $timezone_string     = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1645
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($timezone_string));
1646
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1647
-        return DbSafeDateTime::createFromDateTime($incomingDateTime);
1648
-    }
1649
-
1650
-
1651
-    /**
1652
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1653
-     *
1654
-     * @return EE_Table_Base[]
1655
-     */
1656
-    public function get_tables()
1657
-    {
1658
-        return $this->_tables;
1659
-    }
1660
-
1661
-
1662
-    /**
1663
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1664
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1665
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1666
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1667
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1668
-     * model object with EVT_ID = 1
1669
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1670
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1671
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1672
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1673
-     * are not specified)
1674
-     *
1675
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1676
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1677
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1678
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1679
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1680
-     *                                         ID=34, we'd use this method as follows:
1681
-     *                                         EEM_Transaction::instance()->update(
1682
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1683
-     *                                         array(array('TXN_ID'=>34)));
1684
-     * @param array   $query_params            @see
1685
-     *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1686
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1687
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1688
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1689
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1690
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1691
-     *                                         TRUE, it is assumed that you've already called
1692
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1693
-     *                                         malicious javascript. However, if
1694
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1695
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1696
-     *                                         and every other field, before insertion. We provide this parameter
1697
-     *                                         because model objects perform their prepare_for_set function on all
1698
-     *                                         their values, and so don't need to be called again (and in many cases,
1699
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1700
-     *                                         prepare_for_set method...)
1701
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1702
-     *                                         in this model's entity map according to $fields_n_values that match
1703
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1704
-     *                                         by setting this to FALSE, but be aware that model objects being used
1705
-     *                                         could get out-of-sync with the database
1706
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1707
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1708
-     *                                         bad)
1709
-     * @throws EE_Error
1710
-     * @throws ReflectionException
1711
-     */
1712
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1713
-    {
1714
-        if (! is_array($query_params)) {
1715
-            EE_Error::doing_it_wrong(
1716
-                'EEM_Base::update',
1717
-                sprintf(
1718
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1719
-                    gettype($query_params)
1720
-                ),
1721
-                '4.6.0'
1722
-            );
1723
-            $query_params = [];
1724
-        }
1725
-        /**
1726
-         * Action called before a model update call has been made.
1727
-         *
1728
-         * @param EEM_Base $model
1729
-         * @param array    $fields_n_values the updated fields and their new values
1730
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1731
-         */
1732
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1733
-        /**
1734
-         * Filters the fields about to be updated given the query parameters. You can provide the
1735
-         * $query_params to $this->get_all() to find exactly which records will be updated
1736
-         *
1737
-         * @param array    $fields_n_values fields and their new values
1738
-         * @param EEM_Base $model           the model being queried
1739
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1740
-         */
1741
-        $fields_n_values = (array) apply_filters(
1742
-            'FHEE__EEM_Base__update__fields_n_values',
1743
-            $fields_n_values,
1744
-            $this,
1745
-            $query_params
1746
-        );
1747
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1748
-        // to do that, for each table, verify that it's PK isn't null.
1749
-        $tables = $this->get_tables();
1750
-        // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1751
-        // NOTE: we should make this code more efficient by NOT querying twice
1752
-        // before the real update, but that needs to first go through ALPHA testing
1753
-        // as it's dangerous. says Mike August 8 2014
1754
-        // we want to make sure the default_where strategy is ignored
1755
-        $this->_ignore_where_strategy = true;
1756
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1757
-        foreach ($wpdb_select_results as $wpdb_result) {
1758
-            // type cast stdClass as array
1759
-            $wpdb_result = (array) $wpdb_result;
1760
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1761
-            if ($this->has_primary_key_field()) {
1762
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1763
-            } else {
1764
-                // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1765
-                $main_table_pk_value = null;
1766
-            }
1767
-            // if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1768
-            // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1769
-            if (count($tables) > 1) {
1770
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1771
-                // in that table, and so we'll want to insert one
1772
-                foreach ($tables as $table_obj) {
1773
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1774
-                    // if there is no private key for this table on the results, it means there's no entry
1775
-                    // in this table, right? so insert a row in the current table, using any fields available
1776
-                    if (
1777
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1778
-                           && $wpdb_result[ $this_table_pk_column ])
1779
-                    ) {
1780
-                        $success = $this->_insert_into_specific_table(
1781
-                            $table_obj,
1782
-                            $fields_n_values,
1783
-                            $main_table_pk_value
1784
-                        );
1785
-                        // if we died here, report the error
1786
-                        if (! $success) {
1787
-                            return false;
1788
-                        }
1789
-                    }
1790
-                }
1791
-            }
1792
-            //              //and now check that if we have cached any models by that ID on the model, that
1793
-            //              //they also get updated properly
1794
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1795
-            //              if( $model_object ){
1796
-            //                  foreach( $fields_n_values as $field => $value ){
1797
-            //                      $model_object->set($field, $value);
1798
-            // let's make sure default_where strategy is followed now
1799
-            $this->_ignore_where_strategy = false;
1800
-        }
1801
-        // if we want to keep model objects in sync, AND
1802
-        // if this wasn't called from a model object (to update itself)
1803
-        // then we want to make sure we keep all the existing
1804
-        // model objects in sync with the db
1805
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1806
-            if ($this->has_primary_key_field()) {
1807
-                $model_objs_affected_ids = $this->get_col($query_params);
1808
-            } else {
1809
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1810
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1811
-                $model_objs_affected_ids     = [];
1812
-                foreach ($models_affected_key_columns as $row) {
1813
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1814
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1815
-                }
1816
-            }
1817
-            if (! $model_objs_affected_ids) {
1818
-                // wait wait wait- if nothing was affected let's stop here
1819
-                return 0;
1820
-            }
1821
-            foreach ($model_objs_affected_ids as $id) {
1822
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1823
-                if ($model_obj_in_entity_map) {
1824
-                    foreach ($fields_n_values as $field => $new_value) {
1825
-                        $model_obj_in_entity_map->set($field, $new_value);
1826
-                    }
1827
-                }
1828
-            }
1829
-            // if there is a primary key on this model, we can now do a slight optimization
1830
-            if ($this->has_primary_key_field()) {
1831
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1832
-                $query_params = [
1833
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1834
-                    'limit'                    => count($model_objs_affected_ids),
1835
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1836
-                ];
1837
-            }
1838
-        }
1839
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1840
-
1841
-        // note: the following query doesn't use _construct_2nd_half_of_select_query()
1842
-        // because it doesn't accept LIMIT, ORDER BY, etc.
1843
-        $rows_affected = $this->_do_wpdb_query(
1844
-            'query',
1845
-            [
1846
-                "UPDATE " . $model_query_info->get_full_join_sql()
1847
-                . " SET " . $this->_construct_update_sql($fields_n_values)
1848
-                . $model_query_info->get_where_sql(),
1849
-            ]
1850
-        );
1851
-
1852
-        /**
1853
-         * Action called after a model update call has been made.
1854
-         *
1855
-         * @param EEM_Base $model
1856
-         * @param array    $fields_n_values the updated fields and their new values
1857
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1858
-         * @param int      $rows_affected
1859
-         */
1860
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1861
-        return $rows_affected;// how many supposedly got updated
1862
-    }
1863
-
1864
-
1865
-    /**
1866
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1867
-     * are teh values of the field specified (or by default the primary key field)
1868
-     * that matched the query params. Note that you should pass the name of the
1869
-     * model FIELD, not the database table's column name.
1870
-     *
1871
-     * @param array  $query_params @see
1872
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1873
-     * @param string $field_to_select
1874
-     * @return array just like $wpdb->get_col()
1875
-     * @throws EE_Error
1876
-     * @throws ReflectionException
1877
-     */
1878
-    public function get_col($query_params = [], $field_to_select = null)
1879
-    {
1880
-        if ($field_to_select) {
1881
-            $field = $this->field_settings_for($field_to_select);
1882
-        } elseif ($this->has_primary_key_field()) {
1883
-            $field = $this->get_primary_key_field();
1884
-        } else {
1885
-            $field_settings = $this->field_settings();
1886
-            // no primary key, just grab the first column
1887
-            $field = reset($field_settings);
1888
-            // don't need this array now
1889
-            unset($field_settings);
1890
-        }
1891
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1892
-        $select_expressions = $field->get_qualified_column();
1893
-        $SQL                =
1894
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1895
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1896
-    }
1897
-
1898
-
1899
-    /**
1900
-     * Returns a single column value for a single row from the database
1901
-     *
1902
-     * @param array  $query_params    @see
1903
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1904
-     * @param string $field_to_select @see EEM_Base::get_col()
1905
-     * @return string
1906
-     * @throws EE_Error
1907
-     * @throws ReflectionException
1908
-     */
1909
-    public function get_var($query_params = [], $field_to_select = null)
1910
-    {
1911
-        $query_params['limit'] = 1;
1912
-        $col                   = $this->get_col($query_params, $field_to_select);
1913
-        if (! empty($col)) {
1914
-            return reset($col);
1915
-        }
1916
-        return null;
1917
-    }
1918
-
1919
-
1920
-    /**
1921
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1922
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1923
-     * injection, but currently no further filtering is done
1924
-     *
1925
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1926
-     *                               be updated to in the DB
1927
-     * @return string of SQL
1928
-     * @throws EE_Error
1929
-     * @global      $wpdb
1930
-     */
1931
-    public function _construct_update_sql($fields_n_values)
1932
-    {
1933
-        /** @type WPDB $wpdb */
1934
-        global $wpdb;
1935
-        $cols_n_values = [];
1936
-        foreach ($fields_n_values as $field_name => $value) {
1937
-            $field_obj = $this->field_settings_for($field_name);
1938
-            // if the value is NULL, we want to assign the value to that.
1939
-            // wpdb->prepare doesn't really handle that properly
1940
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1941
-            $value_sql       = $prepared_value === null
1942
-                ? 'NULL'
1943
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1944
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1945
-        }
1946
-        return implode(",", $cols_n_values);
1947
-    }
1948
-
1949
-
1950
-    /**
1951
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1952
-     * Performs a HARD delete, meaning the database row should always be removed,
1953
-     * not just have a flag field on it switched
1954
-     * Wrapper for EEM_Base::delete_permanently()
1955
-     *
1956
-     * @param mixed   $id
1957
-     * @param boolean $allow_blocking
1958
-     * @return int the number of rows deleted
1959
-     * @throws EE_Error
1960
-     * @throws ReflectionException
1961
-     */
1962
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1963
-    {
1964
-        return $this->delete_permanently(
1965
-            [
1966
-                [$this->get_primary_key_field()->get_name() => $id],
1967
-                'limit' => 1,
1968
-            ],
1969
-            $allow_blocking
1970
-        );
1971
-    }
1972
-
1973
-
1974
-    /**
1975
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1976
-     * Wrapper for EEM_Base::delete()
1977
-     *
1978
-     * @param mixed   $id
1979
-     * @param boolean $allow_blocking
1980
-     * @return int the number of rows deleted
1981
-     * @throws EE_Error
1982
-     * @throws ReflectionException
1983
-     */
1984
-    public function delete_by_ID($id, $allow_blocking = true)
1985
-    {
1986
-        return $this->delete(
1987
-            [
1988
-                [$this->get_primary_key_field()->get_name() => $id],
1989
-                'limit' => 1,
1990
-            ],
1991
-            $allow_blocking
1992
-        );
1993
-    }
1994
-
1995
-
1996
-    /**
1997
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1998
-     * meaning if the model has a field that indicates its been "trashed" or
1999
-     * "soft deleted", we will just set that instead of actually deleting the rows.
2000
-     *
2001
-     * @param array   $query_params
2002
-     * @param boolean $allow_blocking
2003
-     * @return int how many rows got deleted
2004
-     * @throws EE_Error
2005
-     * @throws ReflectionException
2006
-     * @see EEM_Base::delete_permanently
2007
-     */
2008
-    public function delete($query_params, $allow_blocking = true)
2009
-    {
2010
-        return $this->delete_permanently($query_params, $allow_blocking);
2011
-    }
2012
-
2013
-
2014
-    /**
2015
-     * Deletes the model objects that meet the query params. Note: this method is overridden
2016
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
2017
-     * as archived, not actually deleted
2018
-     *
2019
-     * @param array   $query_params   @see
2020
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2021
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
2022
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
2023
-     *                                deletes regardless of other objects which may depend on it. Its generally
2024
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
2025
-     *                                DB
2026
-     * @return int how many rows got deleted
2027
-     * @throws EE_Error
2028
-     * @throws ReflectionException
2029
-     */
2030
-    public function delete_permanently($query_params, $allow_blocking = true)
2031
-    {
2032
-        /**
2033
-         * Action called just before performing a real deletion query. You can use the
2034
-         * model and its $query_params to find exactly which items will be deleted
2035
-         *
2036
-         * @param EEM_Base $model
2037
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2038
-         * @param boolean  $allow_blocking whether or not to allow related model objects
2039
-         *                                 to block (prevent) this deletion
2040
-         */
2041
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
2042
-        // some MySQL databases may be running safe mode, which may restrict
2043
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
2044
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
2045
-        // to delete them
2046
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2047
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2048
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2049
-            $columns_and_ids_for_deleting
2050
-        );
2051
-        /**
2052
-         * Allows client code to act on the items being deleted before the query is actually executed.
2053
-         *
2054
-         * @param EEM_Base $this                            The model instance being acted on.
2055
-         * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
2056
-         * @param bool     $allow_blocking                  @see param description in method phpdoc block.
2057
-         * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
2058
-         *                                                  derived from the incoming query parameters.
2059
-         * @see details on the structure of this array in the phpdocs
2060
-         *                                                  for the `_get_ids_for_delete_method`
2061
-         */
2062
-        do_action(
2063
-            'AHEE__EEM_Base__delete__before_query',
2064
-            $this,
2065
-            $query_params,
2066
-            $allow_blocking,
2067
-            $columns_and_ids_for_deleting
2068
-        );
2069
-        $rows_deleted = 0;
2070
-        if ($deletion_where_query_part) {
2071
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2072
-            $table_aliases    = array_keys($this->_tables);
2073
-            $SQL              = "DELETE "
2074
-                                . implode(", ", $table_aliases)
2075
-                                . " FROM "
2076
-                                . $model_query_info->get_full_join_sql()
2077
-                                . " WHERE "
2078
-                                . $deletion_where_query_part;
2079
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2080
-        }
2081
-
2082
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2083
-        // there was no error with the delete query.
2084
-        if (
2085
-            $this->has_primary_key_field()
2086
-            && $rows_deleted !== false
2087
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2088
-        ) {
2089
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2090
-            foreach ($ids_for_removal as $id) {
2091
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2092
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2093
-                }
2094
-            }
2095
-
2096
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2097
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2098
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2099
-            // (although it is possible).
2100
-            // Note this can be skipped by using the provided filter and returning false.
2101
-            if (
2102
-                apply_filters(
2103
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2104
-                    ! $this instanceof EEM_Extra_Meta,
2105
-                    $this
2106
-                )
2107
-            ) {
2108
-                EEM_Extra_Meta::instance()->delete_permanently(
2109
-                    [
2110
-                        0 => [
2111
-                            'EXM_type' => $this->get_this_model_name(),
2112
-                            'OBJ_ID'   => [
2113
-                                'IN',
2114
-                                $ids_for_removal,
2115
-                            ],
2116
-                        ],
2117
-                    ]
2118
-                );
2119
-            }
2120
-        }
2121
-
2122
-        /**
2123
-         * Action called just after performing a real deletion query. Although at this point the
2124
-         * items should have been deleted
2125
-         *
2126
-         * @param EEM_Base $model
2127
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2128
-         * @param int      $rows_deleted
2129
-         */
2130
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2131
-        return (int) $rows_deleted;// how many supposedly got deleted
2132
-    }
2133
-
2134
-
2135
-    /**
2136
-     * Checks all the relations that throw error messages when there are blocking related objects
2137
-     * for related model objects. If there are any related model objects on those relations,
2138
-     * adds an EE_Error, and return true
2139
-     *
2140
-     * @param EE_Base_Class|int $this_model_obj_or_id
2141
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2142
-     *                                                 should be ignored when determining whether there are related
2143
-     *                                                 model objects which block this model object's deletion. Useful
2144
-     *                                                 if you know A is related to B and are considering deleting A,
2145
-     *                                                 but want to see if A has any other objects blocking its deletion
2146
-     *                                                 before removing the relation between A and B
2147
-     * @return boolean
2148
-     * @throws EE_Error
2149
-     * @throws ReflectionException
2150
-     */
2151
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2152
-    {
2153
-        // first, if $ignore_this_model_obj was supplied, get its model
2154
-        $ignored_model = $ignore_this_model_obj instanceof EE_Base_Class
2155
-            ? $ignore_this_model_obj->get_model()
2156
-            : null;
2157
-        // now check all the relations of $this_model_obj_or_id and see if there
2158
-        // are any related model objects blocking it?
2159
-        $is_blocked = false;
2160
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2161
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2162
-                // if $ignore_this_model_obj was supplied, then for the query
2163
-                // on that model needs to be told to ignore $ignore_this_model_obj
2164
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2165
-                    $related_model_objects = $relation_obj->get_all_related(
2166
-                        $this_model_obj_or_id,
2167
-                        [
2168
-                            [
2169
-                                $ignored_model->get_primary_key_field()->get_name() => [
2170
-                                    '!=',
2171
-                                    $ignore_this_model_obj->ID(),
2172
-                                ],
2173
-                            ],
2174
-                        ]
2175
-                    );
2176
-                } else {
2177
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2178
-                }
2179
-                if ($related_model_objects) {
2180
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2181
-                    $is_blocked = true;
2182
-                }
2183
-            }
2184
-        }
2185
-        return $is_blocked;
2186
-    }
2187
-
2188
-
2189
-    /**
2190
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2191
-     *
2192
-     * @param array $row_results_for_deleting
2193
-     * @param bool  $allow_blocking
2194
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2195
-     *                              model DOES have a primary_key_field, then the array will be a simple single
2196
-     *                              dimension array where the key is the fully qualified primary key column and the
2197
-     *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2198
-     *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2199
-     *                              be a two dimensional array where each element is a group of columns and values that
2200
-     *                              get deleted. Example: array(
2201
-     *                              0 => array(
2202
-     *                              'Term_Relationship.object_id' => 1
2203
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2204
-     *                              ),
2205
-     *                              1 => array(
2206
-     *                              'Term_Relationship.object_id' => 1
2207
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2208
-     *                              )
2209
-     *                              )
2210
-     * @throws EE_Error
2211
-     * @throws ReflectionException
2212
-     */
2213
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2214
-    {
2215
-        $ids_to_delete_indexed_by_column = [];
2216
-        if ($this->has_primary_key_field()) {
2217
-            $primary_table = $this->_get_main_table();
2218
-            // following lines are commented out because the variables were not being used
2219
-            // not deleting because unsure if calls were intentionally causing side effects
2220
-            // $primary_table_pk_field          =
2221
-            //     $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2222
-            // $other_tables                    = $this->_get_other_tables();
2223
-            $ids_to_delete_indexed_by_column = $query = [];
2224
-            foreach ($row_results_for_deleting as $item_to_delete) {
2225
-                // before we mark this item for deletion,
2226
-                // make sure there's no related entities blocking its deletion (if we're checking)
2227
-                if (
2228
-                    $allow_blocking
2229
-                    && $this->delete_is_blocked_by_related_models(
2230
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2231
-                    )
2232
-                ) {
2233
-                    continue;
2234
-                }
2235
-                // primary table deletes
2236
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2237
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2238
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2239
-                }
2240
-            }
2241
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2242
-            $fields = $this->get_combined_primary_key_fields();
2243
-            foreach ($row_results_for_deleting as $item_to_delete) {
2244
-                $ids_to_delete_indexed_by_column_for_row = [];
2245
-                foreach ($fields as $cpk_field) {
2246
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2247
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2248
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2249
-                    }
2250
-                }
2251
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2252
-            }
2253
-        } else {
2254
-            // so there's no primary key and no combined key...
2255
-            // sorry, can't help you
2256
-            throw new EE_Error(
2257
-                sprintf(
2258
-                    esc_html__(
2259
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2260
-                        "event_espresso"
2261
-                    ),
2262
-                    get_class($this)
2263
-                )
2264
-            );
2265
-        }
2266
-        return $ids_to_delete_indexed_by_column;
2267
-    }
2268
-
2269
-
2270
-    /**
2271
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2272
-     * the corresponding query_part for the query performing the delete.
2273
-     *
2274
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2275
-     * @return string
2276
-     * @throws EE_Error
2277
-     */
2278
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2279
-    {
2280
-        $query_part = '';
2281
-        if (empty($ids_to_delete_indexed_by_column)) {
2282
-            return $query_part;
2283
-        } elseif ($this->has_primary_key_field()) {
2284
-            $query = [];
2285
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2286
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2287
-            }
2288
-            $query_part = ! empty($query)
2289
-                ? implode(' AND ', $query)
2290
-                : $query_part;
2291
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2292
-            $ways_to_identify_a_row = [];
2293
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2294
-                $values_for_each_combined_primary_key_for_a_row = [];
2295
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2296
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2297
-                }
2298
-                $ways_to_identify_a_row[] = '('
2299
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2300
-                                            . ')';
2301
-            }
2302
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2303
-        }
2304
-        return $query_part;
2305
-    }
2306
-
2307
-
2308
-    /**
2309
-     * Gets the model field by the fully qualified name
2310
-     *
2311
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2312
-     * @return EE_Model_Field_Base
2313
-     * @throws EE_Error
2314
-     * @throws EE_Error
2315
-     */
2316
-    public function get_field_by_column($qualified_column_name)
2317
-    {
2318
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2319
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2320
-                return $field_obj;
2321
-            }
2322
-        }
2323
-        throw new EE_Error(
2324
-            sprintf(
2325
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2326
-                $this->get_this_model_name(),
2327
-                $qualified_column_name
2328
-            )
2329
-        );
2330
-    }
2331
-
2332
-
2333
-    /**
2334
-     * Count all the rows that match criteria the model query params.
2335
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2336
-     * column
2337
-     *
2338
-     * @param array  $query_params   @see
2339
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2340
-     * @param string $field_to_count field on model to count by (not column name)
2341
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2342
-     *                               that by the setting $distinct to TRUE;
2343
-     * @return int
2344
-     * @throws EE_Error
2345
-     * @throws ReflectionException
2346
-     */
2347
-    public function count($query_params = [], $field_to_count = null, $distinct = false)
2348
-    {
2349
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2350
-        if ($field_to_count) {
2351
-            $field_obj       = $this->field_settings_for($field_to_count);
2352
-            $column_to_count = $field_obj->get_qualified_column();
2353
-        } elseif ($this->has_primary_key_field()) {
2354
-            $pk_field_obj    = $this->get_primary_key_field();
2355
-            $column_to_count = $pk_field_obj->get_qualified_column();
2356
-        } else {
2357
-            // there's no primary key
2358
-            // if we're counting distinct items, and there's no primary key,
2359
-            // we need to list out the columns for distinction;
2360
-            // otherwise we can just use star
2361
-            if ($distinct) {
2362
-                $columns_to_use = [];
2363
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2364
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2365
-                }
2366
-                $column_to_count = implode(',', $columns_to_use);
2367
-            } else {
2368
-                $column_to_count = '*';
2369
-            }
2370
-        }
2371
-        $column_to_count = $distinct
2372
-            ? "DISTINCT " . $column_to_count
2373
-            : $column_to_count;
2374
-        $SQL             =
2375
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2376
-        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2377
-    }
2378
-
2379
-
2380
-    /**
2381
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2382
-     *
2383
-     * @param array  $query_params @see
2384
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2385
-     * @param string $field_to_sum name of field (array key in $_fields array)
2386
-     * @return float
2387
-     * @throws EE_Error
2388
-     * @throws ReflectionException
2389
-     */
2390
-    public function sum($query_params, $field_to_sum = null)
2391
-    {
2392
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2393
-        if ($field_to_sum) {
2394
-            $field_obj = $this->field_settings_for($field_to_sum);
2395
-        } else {
2396
-            $field_obj = $this->get_primary_key_field();
2397
-        }
2398
-        $column_to_count = $field_obj->get_qualified_column();
2399
-        $SQL             =
2400
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2401
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2402
-        $data_type       = $field_obj->get_wpdb_data_type();
2403
-        if ($data_type === '%d' || $data_type === '%s') {
2404
-            return (float) $return_value;
2405
-        }
2406
-        // must be %f
2407
-        return (float) $return_value;
2408
-    }
2409
-
2410
-
2411
-    /**
2412
-     * Just calls the specified method on $wpdb with the given arguments
2413
-     * Consolidates a little extra error handling code
2414
-     *
2415
-     * @param string $wpdb_method
2416
-     * @param array  $arguments_to_provide
2417
-     * @return mixed
2418
-     * @throws EE_Error
2419
-     * @global wpdb  $wpdb
2420
-     */
2421
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2422
-    {
2423
-        // if we're in maintenance mode level 2, DON'T run any queries
2424
-        // because level 2 indicates the database needs updating and
2425
-        // is probably out of sync with the code
2426
-        if (DbStatus::isOffline()) {
2427
-            throw new RuntimeException(
2428
-                esc_html__(
2429
-                    "Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2430
-                    "event_espresso"
2431
-                )
2432
-            );
2433
-        }
2434
-        /** @type WPDB $wpdb */
2435
-        global $wpdb;
2436
-        if (! method_exists($wpdb, $wpdb_method)) {
2437
-            throw new DomainException(
2438
-                sprintf(
2439
-                    esc_html__(
2440
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2441
-                        'event_espresso'
2442
-                    ),
2443
-                    $wpdb_method
2444
-                )
2445
-            );
2446
-        }
2447
-        $old_show_errors_value = $wpdb->show_errors;
2448
-        if (WP_DEBUG) {
2449
-            $wpdb->show_errors(false);
2450
-        }
2451
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2452
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2453
-        if (WP_DEBUG) {
2454
-            $wpdb->show_errors($old_show_errors_value);
2455
-            if (! empty($wpdb->last_error)) {
2456
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2457
-            }
2458
-            if ($result === false) {
2459
-                throw new EE_Error(
2460
-                    sprintf(
2461
-                        esc_html__(
2462
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2463
-                            'event_espresso'
2464
-                        ),
2465
-                        $wpdb_method,
2466
-                        var_export($arguments_to_provide, true)
2467
-                    )
2468
-                );
2469
-            }
2470
-        } elseif ($result === false) {
2471
-            EE_Error::add_error(
2472
-                sprintf(
2473
-                    esc_html__(
2474
-                        'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2475
-                        'event_espresso'
2476
-                    ),
2477
-                    $wpdb_method,
2478
-                    var_export($arguments_to_provide, true),
2479
-                    $wpdb->last_error
2480
-                ),
2481
-                __FILE__,
2482
-                __FUNCTION__,
2483
-                __LINE__
2484
-            );
2485
-        }
2486
-        return $result;
2487
-    }
2488
-
2489
-
2490
-    /**
2491
-     * Attempts to run the indicated WPDB method with the provided arguments,
2492
-     * and if there's an error tries to verify the DB is correct. Uses
2493
-     * the static property EEM_Base::$_db_verification_level to determine whether
2494
-     * we should try to fix the EE core db, the addons, or just give up
2495
-     *
2496
-     * @param string $wpdb_method
2497
-     * @param array  $arguments_to_provide
2498
-     * @return mixed
2499
-     */
2500
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2501
-    {
2502
-        /** @type WPDB $wpdb */
2503
-        global $wpdb;
2504
-        $wpdb->last_error = null;
2505
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2506
-        // was there an error running the query? but we don't care on new activations
2507
-        // (we're going to setup the DB anyway on new activations)
2508
-        if (
2509
-            ($result === false || ! empty($wpdb->last_error))
2510
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2511
-        ) {
2512
-            switch (EEM_Base::$_db_verification_level) {
2513
-                case EEM_Base::db_verified_none:
2514
-                    // let's double-check core's DB
2515
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2516
-                    break;
2517
-                case EEM_Base::db_verified_core:
2518
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2519
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2520
-                    break;
2521
-                case EEM_Base::db_verified_addons:
2522
-                    // ummmm... you in trouble
2523
-                    return $result;
2524
-            }
2525
-            if (! empty($error_message)) {
2526
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2527
-                trigger_error($error_message);
2528
-            }
2529
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2530
-        }
2531
-        return $result;
2532
-    }
2533
-
2534
-
2535
-    /**
2536
-     * Verifies the EE core database is up-to-date and records that we've done it on
2537
-     * EEM_Base::$_db_verification_level
2538
-     *
2539
-     * @param string $wpdb_method
2540
-     * @param array  $arguments_to_provide
2541
-     * @return string
2542
-     * @throws EE_Error
2543
-     * @throws ReflectionException
2544
-     */
2545
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2546
-    {
2547
-        /** @type WPDB $wpdb */
2548
-        global $wpdb;
2549
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2550
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2551
-        $error_message                    = sprintf(
2552
-            esc_html__(
2553
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2554
-                'event_espresso'
2555
-            ),
2556
-            $wpdb->last_error,
2557
-            $wpdb_method,
2558
-            wp_json_encode($arguments_to_provide)
2559
-        );
2560
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2561
-        return $error_message;
2562
-    }
2563
-
2564
-
2565
-    /**
2566
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2567
-     * EEM_Base::$_db_verification_level
2568
-     *
2569
-     * @param $wpdb_method
2570
-     * @param $arguments_to_provide
2571
-     * @return string
2572
-     * @throws EE_Error
2573
-     * @throws ReflectionException
2574
-     */
2575
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2576
-    {
2577
-        /** @type WPDB $wpdb */
2578
-        global $wpdb;
2579
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2580
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2581
-        $error_message                    = sprintf(
2582
-            esc_html__(
2583
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2584
-                'event_espresso'
2585
-            ),
2586
-            $wpdb->last_error,
2587
-            $wpdb_method,
2588
-            wp_json_encode($arguments_to_provide)
2589
-        );
2590
-        EE_System::instance()->initialize_addons();
2591
-        return $error_message;
2592
-    }
2593
-
2594
-
2595
-    /**
2596
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2597
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2598
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2599
-     * ..."
2600
-     *
2601
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2602
-     * @return string
2603
-     */
2604
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2605
-    {
2606
-        return " FROM " . $model_query_info->get_full_join_sql() .
2607
-               $model_query_info->get_where_sql() .
2608
-               $model_query_info->get_group_by_sql() .
2609
-               $model_query_info->get_having_sql() .
2610
-               $model_query_info->get_order_by_sql() .
2611
-               $model_query_info->get_limit_sql();
2612
-    }
2613
-
2614
-
2615
-    /**
2616
-     * Set to easily debug the next X queries ran from this model.
2617
-     *
2618
-     * @param int $count
2619
-     */
2620
-    public function show_next_x_db_queries($count = 1)
2621
-    {
2622
-        $this->_show_next_x_db_queries = $count;
2623
-    }
2624
-
2625
-
2626
-    /**
2627
-     * @param $sql_query
2628
-     */
2629
-    public function show_db_query_if_previously_requested($sql_query)
2630
-    {
2631
-        if ($this->_show_next_x_db_queries > 0) {
2632
-            $left = is_admin() ? '12rem' : '2rem';
2633
-            echo "
42
+	/**
43
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
44
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
45
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
46
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
47
+	 *
48
+	 * @var boolean
49
+	 */
50
+	private $_values_already_prepared_by_model_object = 0;
51
+
52
+	/**
53
+	 * when $_values_already_prepared_by_model_object equals this, we assume
54
+	 * the data is just like form input that needs to have the model fields'
55
+	 * prepare_for_set and prepare_for_use_in_db called on it
56
+	 */
57
+	const not_prepared_by_model_object = 0;
58
+
59
+	/**
60
+	 * when $_values_already_prepared_by_model_object equals this, we
61
+	 * assume this value is coming from a model object and doesn't need to have
62
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
63
+	 */
64
+	const prepared_by_model_object = 1;
65
+
66
+	/**
67
+	 * when $_values_already_prepared_by_model_object equals this, we assume
68
+	 * the values are already to be used in the database (ie no processing is done
69
+	 * on them by the model's fields)
70
+	 */
71
+	const prepared_for_use_in_db = 2;
72
+
73
+
74
+	protected $singular_item = 'Item';
75
+
76
+	protected $plural_item   = 'Items';
77
+
78
+	/**
79
+	 * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
80
+	 */
81
+	protected $_tables;
82
+
83
+	/**
84
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
85
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
86
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
87
+	 *
88
+	 * @var EE_Model_Field_Base[][] $_fields
89
+	 */
90
+	protected $_fields;
91
+
92
+	/**
93
+	 * array of different kinds of relations
94
+	 *
95
+	 * @var EE_Model_Relation_Base[] $_model_relations
96
+	 */
97
+	protected $_model_relations = [];
98
+
99
+	/**
100
+	 * @var EE_Index[] $_indexes
101
+	 */
102
+	protected $_indexes = [];
103
+
104
+	/**
105
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
106
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
107
+	 * by setting the same columns as used in these queries in the query yourself.
108
+	 *
109
+	 * @var EE_Default_Where_Conditions
110
+	 */
111
+	protected $_default_where_conditions_strategy;
112
+
113
+	/**
114
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
115
+	 * This is particularly useful when you want something between 'none' and 'default'
116
+	 *
117
+	 * @var EE_Default_Where_Conditions
118
+	 */
119
+	protected $_minimum_where_conditions_strategy;
120
+
121
+	/**
122
+	 * String describing how to find the "owner" of this model's objects.
123
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
124
+	 * But when there isn't, this indicates which related model, or transiently-related model,
125
+	 * has the foreign key to the wp_users table.
126
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
127
+	 * related to events, and events have a foreign key to wp_users.
128
+	 * On EEM_Transaction, this would be 'Transaction.Event'
129
+	 *
130
+	 * @var string
131
+	 */
132
+	protected $_model_chain_to_wp_user = '';
133
+
134
+	/**
135
+	 * String describing how to find the model with a password controlling access to this model. This property has the
136
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
137
+	 * This value is the path of models to follow to arrive at the model with the password field.
138
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
139
+	 * model with a password that should affect reading this on the front-end.
140
+	 * Eg this is an empty string for the Event model because it has a password.
141
+	 * This is null for the Registration model, because its event's password has no bearing on whether
142
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
143
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
144
+	 * should hide tickets for datetimes for events that have a password set.
145
+	 *
146
+	 * @var string |null
147
+	 */
148
+	protected $model_chain_to_password = null;
149
+
150
+	/**
151
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
+	 * don't need it (particularly CPT models)
153
+	 *
154
+	 * @var bool
155
+	 */
156
+	protected $_ignore_where_strategy = false;
157
+
158
+	/**
159
+	 * String used in caps relating to this model. Eg, if the caps relating to this
160
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
+	 *
162
+	 * @var string. If null it hasn't been initialized yet. If false then we
163
+	 * have indicated capabilities don't apply to this
164
+	 */
165
+	protected $_caps_slug = null;
166
+
167
+	/**
168
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
+	 * and next-level keys are capability names, and each's value is a
170
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
172
+	 * and then each capability in the corresponding sub-array that they're missing
173
+	 * adds the where conditions onto the query.
174
+	 *
175
+	 * @var array
176
+	 */
177
+	protected $_cap_restrictions = [
178
+		self::caps_read       => [],
179
+		self::caps_read_admin => [],
180
+		self::caps_edit       => [],
181
+		self::caps_delete     => [],
182
+	];
183
+
184
+	/**
185
+	 * Array defining which cap restriction generators to use to create default
186
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
187
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
+	 * automatically set this to false (not just null).
190
+	 *
191
+	 * @var EE_Restriction_Generator_Base[]
192
+	 */
193
+	protected $_cap_restriction_generators = [];
194
+
195
+	/**
196
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
+	 */
198
+	const caps_read       = 'read';
199
+
200
+	const caps_read_admin = 'read_admin';
201
+
202
+	const caps_edit       = 'edit';
203
+
204
+	const caps_delete     = 'delete';
205
+
206
+	/**
207
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
+	 * maps to 'read' because when looking for relevant permissions we're going to use
210
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
211
+	 *
212
+	 * @var array
213
+	 */
214
+	protected $_cap_contexts_to_cap_action_map = [
215
+		self::caps_read       => 'read',
216
+		self::caps_read_admin => 'read',
217
+		self::caps_edit       => 'edit',
218
+		self::caps_delete     => 'delete',
219
+	];
220
+
221
+	/**
222
+	 * Timezone
223
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
+	 * EE_Datetime_Field data type will have access to it.
227
+	 *
228
+	 * @var string
229
+	 */
230
+	protected $_timezone;
231
+
232
+
233
+	/**
234
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
+	 * multisite.
236
+	 *
237
+	 * @var int
238
+	 */
239
+	protected static $_model_query_blog_id;
240
+
241
+	/**
242
+	 * A copy of _fields, except the array keys are the model names pointed to by
243
+	 * the field
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cache_foreign_key_to_fields = [];
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, indexed by their name
251
+	 *
252
+	 * @var EE_Model_Field_Base[]
253
+	 */
254
+	private $_cached_fields = null;
255
+
256
+	/**
257
+	 * Cached list of all the fields on the model, except those that are
258
+	 * marked as only pertinent to the database
259
+	 *
260
+	 * @var EE_Model_Field_Base[]
261
+	 */
262
+	private $_cached_fields_non_db_only = null;
263
+
264
+	/**
265
+	 * A cached reference to the primary key for quick lookup
266
+	 *
267
+	 * @var EE_Model_Field_Base
268
+	 */
269
+	private $_primary_key_field = null;
270
+
271
+	/**
272
+	 * Flag indicating whether this model has a primary key or not
273
+	 *
274
+	 * @var boolean
275
+	 */
276
+	protected $_has_primary_key_field = null;
277
+
278
+	/**
279
+	 * array in the format:  [ FK alias => full PK ]
280
+	 * where keys are local column name aliases for foreign keys
281
+	 * and values are the fully qualified column name for the primary key they represent
282
+	 *  ex:
283
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
+	 *
285
+	 * @var array $foreign_key_aliases
286
+	 */
287
+	protected $foreign_key_aliases = [];
288
+
289
+	/**
290
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
291
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
+	 * This should be true for models that deal with data that should exist independent of EE.
293
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
295
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
297
+	 *
298
+	 * @var boolean
299
+	 */
300
+	protected $_wp_core_model = false;
301
+
302
+	/**
303
+	 * @var bool stores whether this model has a password field or not.
304
+	 * null until initialized by hasPasswordField()
305
+	 */
306
+	protected $has_password_field;
307
+
308
+	/**
309
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
310
+	 */
311
+	protected $password_field;
312
+
313
+	/**
314
+	 *    List of valid operators that can be used for querying.
315
+	 * The keys are all operators we'll accept, the values are the real SQL
316
+	 * operators used
317
+	 *
318
+	 * @var array
319
+	 */
320
+	protected $_valid_operators = [
321
+		'='           => '=',
322
+		'<='          => '<=',
323
+		'<'           => '<',
324
+		'>='          => '>=',
325
+		'>'           => '>',
326
+		'!='          => '!=',
327
+		'LIKE'        => 'LIKE',
328
+		'like'        => 'LIKE',
329
+		'NOT_LIKE'    => 'NOT LIKE',
330
+		'not_like'    => 'NOT LIKE',
331
+		'NOT LIKE'    => 'NOT LIKE',
332
+		'not like'    => 'NOT LIKE',
333
+		'IN'          => 'IN',
334
+		'in'          => 'IN',
335
+		'NOT_IN'      => 'NOT IN',
336
+		'not_in'      => 'NOT IN',
337
+		'NOT IN'      => 'NOT IN',
338
+		'not in'      => 'NOT IN',
339
+		'between'     => 'BETWEEN',
340
+		'BETWEEN'     => 'BETWEEN',
341
+		'IS_NOT_NULL' => 'IS NOT NULL',
342
+		'is_not_null' => 'IS NOT NULL',
343
+		'IS NOT NULL' => 'IS NOT NULL',
344
+		'is not null' => 'IS NOT NULL',
345
+		'IS_NULL'     => 'IS NULL',
346
+		'is_null'     => 'IS NULL',
347
+		'IS NULL'     => 'IS NULL',
348
+		'is null'     => 'IS NULL',
349
+		'REGEXP'      => 'REGEXP',
350
+		'regexp'      => 'REGEXP',
351
+		'NOT_REGEXP'  => 'NOT REGEXP',
352
+		'not_regexp'  => 'NOT REGEXP',
353
+		'NOT REGEXP'  => 'NOT REGEXP',
354
+		'not regexp'  => 'NOT REGEXP',
355
+	];
356
+
357
+	/**
358
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
359
+	 *
360
+	 * @var array
361
+	 */
362
+	protected $_in_style_operators = ['IN', 'NOT IN'];
363
+
364
+	/**
365
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
366
+	 * '12-31-2012'"
367
+	 *
368
+	 * @var array
369
+	 */
370
+	protected $_between_style_operators = ['BETWEEN'];
371
+
372
+	/**
373
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
374
+	 *
375
+	 * @var array
376
+	 */
377
+	protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
378
+
379
+	/**
380
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
381
+	 * on a join table.
382
+	 *
383
+	 * @var array
384
+	 */
385
+	protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
386
+
387
+	/**
388
+	 * Allowed values for $query_params['order'] for ordering in queries
389
+	 *
390
+	 * @var array
391
+	 */
392
+	protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
393
+
394
+	/**
395
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
396
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
397
+	 *
398
+	 * @var array
399
+	 */
400
+	private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
401
+
402
+	/**
403
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
404
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
405
+	 *
406
+	 * @var array
407
+	 */
408
+	private $_allowed_query_params = [
409
+		0,
410
+		'limit',
411
+		'order_by',
412
+		'group_by',
413
+		'having',
414
+		'force_join',
415
+		'order',
416
+		'on_join_limit',
417
+		'default_where_conditions',
418
+		'caps',
419
+		'extra_selects',
420
+		'exclude_protected',
421
+	];
422
+
423
+	/**
424
+	 * All the data types that can be used in $wpdb->prepare statements.
425
+	 *
426
+	 * @var array
427
+	 */
428
+	private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
429
+
430
+	/**
431
+	 * @var EE_Registry $EE
432
+	 */
433
+	protected $EE = null;
434
+
435
+
436
+	/**
437
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
438
+	 *
439
+	 * @var int
440
+	 */
441
+	protected $_show_next_x_db_queries = 0;
442
+
443
+	/**
444
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
445
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
446
+	 * WHERE, GROUP_BY, etc.
447
+	 *
448
+	 * @var CustomSelects
449
+	 */
450
+	protected $_custom_selections = [];
451
+
452
+	/**
453
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
454
+	 * caches every model object we've fetched from the DB on this request
455
+	 *
456
+	 * @var array
457
+	 */
458
+	protected $_entity_map;
459
+
460
+	/**
461
+	 * @var LoaderInterface
462
+	 */
463
+	protected static $loader;
464
+
465
+	/**
466
+	 * @var Mirror
467
+	 */
468
+	private static $mirror;
469
+
470
+
471
+	/**
472
+	 * constant used to show EEM_Base has not yet verified the db on this http request
473
+	 */
474
+	const db_verified_none = 0;
475
+
476
+	/**
477
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
478
+	 * but not the addons' dbs
479
+	 */
480
+	const db_verified_core = 1;
481
+
482
+	/**
483
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
484
+	 * the EE core db too)
485
+	 */
486
+	const db_verified_addons = 2;
487
+
488
+	/**
489
+	 * indicates whether an EEM_Base child has already re-verified the DB
490
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
491
+	 * looking like EEM_Base::db_verified_*
492
+	 *
493
+	 * @var int - 0 = none, 1 = core, 2 = addons
494
+	 */
495
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
496
+
497
+	/**
498
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
499
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
500
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
501
+	 */
502
+	const default_where_conditions_all = 'all';
503
+
504
+	/**
505
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
506
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
507
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
508
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
509
+	 *        models which share tables with other models, this can return data for the wrong model.
510
+	 */
511
+	const default_where_conditions_this_only = 'this_model_only';
512
+
513
+	/**
514
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
515
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
516
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
517
+	 */
518
+	const default_where_conditions_others_only = 'other_models_only';
519
+
520
+	/**
521
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
522
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
523
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
524
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
525
+	 *        (regardless of whether those events and venues are trashed)
526
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
527
+	 *        events.
528
+	 */
529
+	const default_where_conditions_minimum_all = 'minimum';
530
+
531
+	/**
532
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
533
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
534
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
535
+	 *        not)
536
+	 */
537
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
538
+
539
+	/**
540
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
541
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
542
+	 *        it's possible it will return table entries for other models. You should use
543
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
544
+	 */
545
+	const default_where_conditions_none = 'none';
546
+
547
+
548
+	/**
549
+	 * About all child constructors:
550
+	 * they should define the _tables, _fields and _model_relations arrays.
551
+	 * Should ALWAYS be called after child constructor.
552
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
553
+	 * finalizes constructing all the object's attributes.
554
+	 * Generally, rather than requiring a child to code
555
+	 * $this->_tables = array(
556
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
557
+	 *        ...);
558
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
559
+	 * each EE_Table has a function to set the table's alias after the constructor, using
560
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
561
+	 * do something similar.
562
+	 *
563
+	 * @param string|null $timezone
564
+	 * @throws EE_Error
565
+	 * @throws Exception
566
+	 */
567
+	protected function __construct($timezone = '')
568
+	{
569
+		// check that the model has not been loaded too soon
570
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
+			throw new EE_Error(
572
+				sprintf(
573
+					esc_html__(
574
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
575
+						'event_espresso'
576
+					),
577
+					get_class($this)
578
+				)
579
+			);
580
+		}
581
+		/**
582
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
+		 */
584
+		if (empty(EEM_Base::$_model_query_blog_id)) {
585
+			EEM_Base::set_model_query_blog_id();
586
+		}
587
+		/**
588
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
+		 * just use EE_Register_Model_Extension
590
+		 *
591
+		 * @var EE_Table_Base[] $_tables
592
+		 */
593
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
+		foreach ($this->_tables as $table_alias => $table_obj) {
595
+			/** @var $table_obj EE_Table_Base */
596
+			$table_obj->_construct_finalize_with_alias($table_alias);
597
+			if ($table_obj instanceof EE_Secondary_Table) {
598
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
599
+			}
600
+		}
601
+		/**
602
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
603
+		 * EE_Register_Model_Extension
604
+		 *
605
+		 * @param EE_Model_Field_Base[] $_fields
606
+		 */
607
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
608
+		$this->_invalidate_field_caches();
609
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
610
+			if (! array_key_exists($table_alias, $this->_tables)) {
611
+				throw new EE_Error(
612
+					sprintf(
613
+						esc_html__(
614
+							"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
615
+							'event_espresso'
616
+						),
617
+						$table_alias,
618
+						implode(",", $this->_fields)
619
+					)
620
+				);
621
+			}
622
+			foreach ($fields_for_table as $field_name => $field_obj) {
623
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
624
+				// primary key field base has a slightly different _construct_finalize
625
+				/** @var $field_obj EE_Model_Field_Base */
626
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
627
+			}
628
+		}
629
+		// everything is related to Extra_Meta
630
+		if (get_class($this) !== 'EEM_Extra_Meta') {
631
+			// make extra meta related to everything, but don't block deleting things just
632
+			// because they have related extra meta info. For now just orphan those extra meta
633
+			// in the future we should automatically delete them
634
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
635
+		}
636
+		// and change logs
637
+		if (get_class($this) !== 'EEM_Change_Log') {
638
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
639
+		}
640
+		/**
641
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
642
+		 * EE_Register_Model_Extension
643
+		 *
644
+		 * @param EE_Model_Relation_Base[] $_model_relations
645
+		 */
646
+		$this->_model_relations = (array) apply_filters(
647
+			'FHEE__' . get_class($this) . '__construct__model_relations',
648
+			$this->_model_relations
649
+		);
650
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
651
+			/** @var $relation_obj EE_Model_Relation_Base */
652
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
653
+		}
654
+		foreach ($this->_indexes as $index_name => $index_obj) {
655
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
656
+		}
657
+		$this->set_timezone($timezone);
658
+		// finalize default where condition strategy, or set default
659
+		if (! $this->_default_where_conditions_strategy) {
660
+			// nothing was set during child constructor, so set default
661
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
662
+		}
663
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
664
+		if (! $this->_minimum_where_conditions_strategy) {
665
+			// nothing was set during child constructor, so set default
666
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
667
+		}
668
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
669
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
670
+		// to indicate to NOT set it, set it to the logical default
671
+		if ($this->_caps_slug === null) {
672
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
673
+		}
674
+		// initialize the standard cap restriction generators if none were specified by the child constructor
675
+		if (is_array($this->_cap_restriction_generators)) {
676
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
677
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
678
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
679
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
680
+						new EE_Restriction_Generator_Protected(),
681
+						$cap_context,
682
+						$this
683
+					);
684
+				}
685
+			}
686
+		}
687
+		// if there are cap restriction generators, use them to make the default cap restrictions
688
+		if (is_array($this->_cap_restriction_generators)) {
689
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
690
+				if (! $generator_object) {
691
+					continue;
692
+				}
693
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
694
+					throw new EE_Error(
695
+						sprintf(
696
+							esc_html__(
697
+								'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
698
+								'event_espresso'
699
+							),
700
+							$context,
701
+							$this->get_this_model_name()
702
+						)
703
+					);
704
+				}
705
+				$action = $this->cap_action_for_context($context);
706
+				if (! $generator_object->construction_finalized()) {
707
+					$generator_object->_construct_finalize($this, $action);
708
+				}
709
+			}
710
+		}
711
+		do_action('AHEE__' . get_class($this) . '__construct__end');
712
+	}
713
+
714
+
715
+	/**
716
+	 * @return LoaderInterface
717
+	 * @throws InvalidArgumentException
718
+	 * @throws InvalidDataTypeException
719
+	 * @throws InvalidInterfaceException
720
+	 */
721
+	protected static function getLoader(): LoaderInterface
722
+	{
723
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
724
+			EEM_Base::$loader = LoaderFactory::getLoader();
725
+		}
726
+		return EEM_Base::$loader;
727
+	}
728
+
729
+
730
+	/**
731
+	 * @return Mirror
732
+	 * @since   5.0.0.p
733
+	 */
734
+	private static function getMirror(): Mirror
735
+	{
736
+		if (! EEM_Base::$mirror instanceof Mirror) {
737
+			EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
738
+		}
739
+		return EEM_Base::$mirror;
740
+	}
741
+
742
+
743
+	/**
744
+	 * @param string $model_class_Name
745
+	 * @param string $timezone
746
+	 * @return array
747
+	 * @throws ReflectionException
748
+	 * @since   5.0.0.p
749
+	 */
750
+	private static function getModelArguments(string $model_class_Name, string $timezone): array
751
+	{
752
+		$arguments = [$timezone];
753
+		$params    = EEM_Base::getMirror()->getParameters($model_class_Name);
754
+		if (count($params) > 1) {
755
+			if ($params[1]->getName() === 'model_field_factory') {
756
+				$arguments = [
757
+					$timezone,
758
+					EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
759
+				];
760
+			} elseif ($model_class_Name === 'EEM_Form_Section') {
761
+				$arguments = [
762
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
763
+					$timezone,
764
+				];
765
+			} elseif ($model_class_Name === 'EEM_Form_Element') {
766
+				$arguments = [
767
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
768
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
769
+					$timezone,
770
+				];
771
+			}
772
+		}
773
+		return $arguments;
774
+	}
775
+
776
+
777
+	/**
778
+	 * This function is a singleton method used to instantiate the Espresso_model object
779
+	 *
780
+	 * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
781
+	 *                                (and any incoming timezone data that gets saved).
782
+	 *                                Note this just sends the timezone info to the date time model field objects.
783
+	 *                                Default is NULL
784
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
785
+	 * @return static (as in the concrete child class)
786
+	 * @throws EE_Error
787
+	 * @throws ReflectionException
788
+	 */
789
+	public static function instance($timezone = '')
790
+	{
791
+		// check if instance of Espresso_model already exists
792
+		if (! static::$_instance instanceof static) {
793
+			$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
794
+			$model     = new static(...$arguments);
795
+			EEM_Base::getLoader()->share(static::class, $model, $arguments);
796
+			static::$_instance = $model;
797
+		}
798
+		// we might have a timezone set, let set_timezone decide what to do with it
799
+		if ($timezone) {
800
+			static::$_instance->set_timezone($timezone);
801
+		}
802
+		// Espresso_model object
803
+		return static::$_instance;
804
+	}
805
+
806
+
807
+	/**
808
+	 * resets the model and returns it
809
+	 *
810
+	 * @param string|null $timezone
811
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
812
+	 * all its properties reset; if it wasn't instantiated, returns null)
813
+	 * @throws EE_Error
814
+	 * @throws ReflectionException
815
+	 * @throws InvalidArgumentException
816
+	 * @throws InvalidDataTypeException
817
+	 * @throws InvalidInterfaceException
818
+	 */
819
+	public static function reset($timezone = '')
820
+	{
821
+		if (! static::$_instance instanceof EEM_Base) {
822
+			return null;
823
+		}
824
+		// Let's NOT swap out the current instance for a new one
825
+		// because if someone has a reference to it, we can't remove their reference.
826
+		// It's best to keep using the same reference but change the original object instead,
827
+		// so reset all its properties to their original values as defined in the class.
828
+		$static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
829
+		foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
830
+			// don't set instance to null like it was originally,
831
+			// but it's static anyways, and we're ignoring static properties (for now at least)
832
+			if (! isset($static_properties[ $property ])) {
833
+				static::$_instance->{$property} = $value;
834
+			}
835
+		}
836
+		// and then directly call its constructor again, like we would if we were creating a new one
837
+		$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
838
+		static::$_instance->__construct(...$arguments);
839
+		return self::instance();
840
+	}
841
+
842
+
843
+	/**
844
+	 * Used to set the $_model_query_blog_id static property.
845
+	 *
846
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
847
+	 *                      value for get_current_blog_id() will be used.
848
+	 */
849
+	public static function set_model_query_blog_id($blog_id = 0)
850
+	{
851
+		EEM_Base::$_model_query_blog_id = $blog_id > 0
852
+			? (int) $blog_id
853
+			: get_current_blog_id();
854
+	}
855
+
856
+
857
+	/**
858
+	 * Returns whatever is set as the internal $model_query_blog_id.
859
+	 *
860
+	 * @return int
861
+	 */
862
+	public static function get_model_query_blog_id()
863
+	{
864
+		return EEM_Base::$_model_query_blog_id;
865
+	}
866
+
867
+
868
+	/**
869
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
870
+	 *
871
+	 * @param boolean $translated return localized strings or JUST the array.
872
+	 * @return array
873
+	 * @throws EE_Error
874
+	 * @throws InvalidArgumentException
875
+	 * @throws InvalidDataTypeException
876
+	 * @throws InvalidInterfaceException
877
+	 * @throws ReflectionException
878
+	 */
879
+	public function status_array($translated = false)
880
+	{
881
+		if (! array_key_exists('Status', $this->_model_relations)) {
882
+			return [];
883
+		}
884
+		$model_name   = $this->get_this_model_name();
885
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
886
+		$stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
887
+		$status_array = [];
888
+		foreach ($stati as $status) {
889
+			$status_array[ $status->ID() ] = $status->get('STS_code');
890
+		}
891
+		return $translated
892
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
893
+			: $status_array;
894
+	}
895
+
896
+
897
+	/**
898
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
899
+	 *
900
+	 * @param array $query_params             @see
901
+	 *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
+	 *                                        or if you have the development copy of EE you can view this at the path:
903
+	 *                                        /docs/G--Model-System/model-query-params.md
904
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
905
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
906
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
907
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
908
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
909
+	 *                                        'OR'=>array(
910
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
911
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
912
+	 *                                        )
913
+	 *                                        ),
914
+	 *                                        'limit'=>10,
915
+	 *                                        'group_by'=>'TXN_ID'
916
+	 *                                        ));
917
+	 *                                        get all the answers to the question titled "shirt size" for event with id
918
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
919
+	 *                                        'Question.QST_display_text'=>'shirt size',
920
+	 *                                        'Registration.Event.EVT_ID'=>12
921
+	 *                                        ),
922
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
923
+	 *                                        ));
924
+	 * @throws EE_Error
925
+	 * @throws ReflectionException
926
+	 */
927
+	public function get_all($query_params = [])
928
+	{
929
+		if (
930
+			isset($query_params['limit'])
931
+			&& ! isset($query_params['group_by'])
932
+		) {
933
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
+		}
935
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
936
+	}
937
+
938
+
939
+	/**
940
+	 * Modifies the query parameters so we only get back model objects
941
+	 * that "belong" to the current user
942
+	 *
943
+	 * @param array $query_params @see
944
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
945
+	 * @return array @see
946
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
947
+	 * @throws ReflectionException
948
+	 * @throws ReflectionException
949
+	 */
950
+	public function alter_query_params_to_only_include_mine($query_params = [])
951
+	{
952
+		$wp_user_field_name = $this->wp_user_field_name();
953
+		if ($wp_user_field_name) {
954
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
955
+		}
956
+		return $query_params;
957
+	}
958
+
959
+
960
+	/**
961
+	 * Returns the name of the field's name that points to the WP_User table
962
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
963
+	 * foreign key to the WP_User table)
964
+	 *
965
+	 * @return string|boolean string on success, boolean false when there is no
966
+	 * foreign key to the WP_User table
967
+	 * @throws ReflectionException
968
+	 * @throws ReflectionException
969
+	 */
970
+	public function wp_user_field_name()
971
+	{
972
+		try {
973
+			if (! empty($this->_model_chain_to_wp_user)) {
974
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
975
+				$last_model_name              = end($models_to_follow_to_wp_users);
976
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
977
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
978
+			} else {
979
+				$model_with_fk_to_wp_users = $this;
980
+				$model_chain_to_wp_user    = '';
981
+			}
982
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
983
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
984
+		} catch (EE_Error $e) {
985
+			return false;
986
+		}
987
+	}
988
+
989
+
990
+	/**
991
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
992
+	 * (or transiently-related model) has a foreign key to the wp_users table;
993
+	 * useful for finding if model objects of this type are 'owned' by the current user.
994
+	 * This is an empty string when the foreign key is on this model and when it isn't,
995
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
996
+	 * (or transiently-related model)
997
+	 *
998
+	 * @return string
999
+	 */
1000
+	public function model_chain_to_wp_user()
1001
+	{
1002
+		return $this->_model_chain_to_wp_user;
1003
+	}
1004
+
1005
+
1006
+	/**
1007
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1008
+	 * like how registrations don't have a foreign key to wp_users, but the
1009
+	 * events they are for are), or is unrelated to wp users.
1010
+	 * generally available
1011
+	 *
1012
+	 * @return boolean
1013
+	 */
1014
+	public function is_owned()
1015
+	{
1016
+		if ($this->model_chain_to_wp_user()) {
1017
+			return true;
1018
+		}
1019
+		try {
1020
+			$this->get_foreign_key_to('WP_User');
1021
+			return true;
1022
+		} catch (EE_Error $e) {
1023
+			return false;
1024
+		}
1025
+	}
1026
+
1027
+
1028
+	/**
1029
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
+	 * the model)
1032
+	 *
1033
+	 * @param array  $query_params      @see
1034
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1035
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
+	 * @param mixed  $columns_to_select What columns to select. By default, we select all columns specified by the
1037
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1038
+	 *                                  override this and set the select to "*", or a specific column name, like
1039
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
+	 *                                  the aliases used to refer to this selection, and values are to be
1042
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
+	 * @throws EE_Error
1046
+	 * @throws InvalidArgumentException
1047
+	 * @throws ReflectionException
1048
+	 */
1049
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1050
+	{
1051
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1052
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1053
+		$select_expressions       = $columns_to_select === null
1054
+			? $this->_construct_default_select_sql($model_query_info)
1055
+			: '';
1056
+		if ($this->_custom_selections instanceof CustomSelects) {
1057
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1058
+			$select_expressions .= $select_expressions
1059
+				? ', ' . $custom_expressions
1060
+				: $custom_expressions;
1061
+		}
1062
+
1063
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1064
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1065
+	}
1066
+
1067
+
1068
+	/**
1069
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1070
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1071
+	 * method of including extra select information.
1072
+	 *
1073
+	 * @param array             $query_params
1074
+	 * @param null|array|string $columns_to_select
1075
+	 * @return null|CustomSelects
1076
+	 * @throws InvalidArgumentException
1077
+	 */
1078
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1079
+	{
1080
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1081
+			return null;
1082
+		}
1083
+		$selects = $query_params['extra_selects'] ?? $columns_to_select;
1084
+		$selects = is_string($selects)
1085
+			? explode(',', $selects)
1086
+			: $selects;
1087
+		return new CustomSelects($selects);
1088
+	}
1089
+
1090
+
1091
+	/**
1092
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1093
+	 * but you can use the model query params to more easily
1094
+	 * take care of joins, field preparation etc.
1095
+	 *
1096
+	 * @param array  $query_params      @see
1097
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1098
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1099
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1100
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1101
+	 *                                  override this and set the select to "*", or a specific column name, like
1102
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1103
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1104
+	 *                                  the aliases used to refer to this selection, and values are to be
1105
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1106
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1107
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1108
+	 * @throws EE_Error
1109
+	 * @throws ReflectionException
1110
+	 */
1111
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1112
+	{
1113
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1114
+	}
1115
+
1116
+
1117
+	/**
1118
+	 * For creating a custom select statement
1119
+	 *
1120
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1121
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1122
+	 *                                 SQL, and 1=>is the datatype
1123
+	 * @return string
1124
+	 * @throws EE_Error
1125
+	 */
1126
+	private function _construct_select_from_input($columns_to_select)
1127
+	{
1128
+		if (is_array($columns_to_select)) {
1129
+			$select_sql_array = [];
1130
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1131
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1132
+					throw new EE_Error(
1133
+						sprintf(
1134
+							esc_html__(
1135
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1136
+								'event_espresso'
1137
+							),
1138
+							$selection_and_datatype,
1139
+							$alias
1140
+						)
1141
+					);
1142
+				}
1143
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1144
+					throw new EE_Error(
1145
+						sprintf(
1146
+							esc_html__(
1147
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1148
+								'event_espresso'
1149
+							),
1150
+							$selection_and_datatype[1],
1151
+							$selection_and_datatype[0],
1152
+							$alias,
1153
+							implode(', ', $this->_valid_wpdb_data_types)
1154
+						)
1155
+					);
1156
+				}
1157
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1158
+			}
1159
+			$columns_to_select_string = implode(', ', $select_sql_array);
1160
+		} else {
1161
+			$columns_to_select_string = $columns_to_select;
1162
+		}
1163
+		return $columns_to_select_string;
1164
+	}
1165
+
1166
+
1167
+	/**
1168
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1169
+	 *
1170
+	 * @return string
1171
+	 * @throws EE_Error
1172
+	 */
1173
+	public function primary_key_name()
1174
+	{
1175
+		return $this->get_primary_key_field()->get_name();
1176
+	}
1177
+
1178
+
1179
+	/**
1180
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1181
+	 * If there is no primary key on this model, $id is treated as primary key string
1182
+	 *
1183
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1184
+	 * @return EE_Base_Class|mixed|null
1185
+	 * @throws EE_Error
1186
+	 * @throws ReflectionException
1187
+	 */
1188
+	public function get_one_by_ID($id)
1189
+	{
1190
+		// since entities with no ID can still have properties, we need to check the cache for them
1191
+		$cached_value = $this->get_from_entity_map($id);
1192
+		if ($cached_value) {
1193
+			return $cached_value;
1194
+		}
1195
+		// but if no cahced property AND no id is passed, just return null
1196
+		if (empty($id)) {
1197
+			return null;
1198
+		}
1199
+		$model_object = $this->get_one(
1200
+			$this->alter_query_params_to_restrict_by_ID(
1201
+				$id,
1202
+				['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1203
+			)
1204
+		);
1205
+		$className    = $this->_get_class_name();
1206
+		if ($model_object instanceof $className) {
1207
+			// make sure valid objects get added to the entity map
1208
+			// so that the next call to this method doesn't trigger another trip to the db
1209
+			$this->add_to_entity_map($model_object);
1210
+		}
1211
+		return $model_object;
1212
+	}
1213
+
1214
+
1215
+	/**
1216
+	 * Alters query parameters to only get items with this ID are returned.
1217
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1218
+	 * or could just be a simple primary key ID
1219
+	 *
1220
+	 * @param int   $id
1221
+	 * @param array $query_params
1222
+	 * @return array of normal query params, @see
1223
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1224
+	 * @throws EE_Error
1225
+	 */
1226
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1227
+	{
1228
+		if (! isset($query_params[0])) {
1229
+			$query_params[0] = [];
1230
+		}
1231
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1232
+		if ($conditions_from_id === null) {
1233
+			$query_params[0][ $this->primary_key_name() ] = $id;
1234
+		} else {
1235
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1236
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1237
+		}
1238
+		return $query_params;
1239
+	}
1240
+
1241
+
1242
+	/**
1243
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1244
+	 * array. If no item is found, null is returned.
1245
+	 *
1246
+	 * @param array $query_params like EEM_Base's $query_params variable.
1247
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1248
+	 * @throws EE_Error
1249
+	 * @throws ReflectionException
1250
+	 */
1251
+	public function get_one($query_params = [])
1252
+	{
1253
+		if (! is_array($query_params)) {
1254
+			EE_Error::doing_it_wrong(
1255
+				'EEM_Base::get_one',
1256
+				sprintf(
1257
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1258
+					gettype($query_params)
1259
+				),
1260
+				'4.6.0'
1261
+			);
1262
+			$query_params = [];
1263
+		}
1264
+		$query_params['limit'] = 1;
1265
+		$items                 = $this->get_all($query_params);
1266
+		if (empty($items)) {
1267
+			return null;
1268
+		}
1269
+		return array_shift($items);
1270
+	}
1271
+
1272
+
1273
+	/**
1274
+	 * Returns the next x number of items in sequence from the given value as
1275
+	 * found in the database matching the given query conditions.
1276
+	 *
1277
+	 * @param mixed $current_field_value    Value used for the reference point.
1278
+	 * @param null  $field_to_order_by      What field is used for the
1279
+	 *                                      reference point.
1280
+	 * @param int   $limit                  How many to return.
1281
+	 * @param array $query_params           Extra conditions on the query.
1282
+	 * @param null  $columns_to_select      If left null, then an array of
1283
+	 *                                      EE_Base_Class objects is returned,
1284
+	 *                                      otherwise you can indicate just the
1285
+	 *                                      columns you want returned.
1286
+	 * @return EE_Base_Class[]|array
1287
+	 * @throws EE_Error
1288
+	 * @throws ReflectionException
1289
+	 */
1290
+	public function next_x(
1291
+		$current_field_value,
1292
+		$field_to_order_by = null,
1293
+		$limit = 1,
1294
+		$query_params = [],
1295
+		$columns_to_select = null
1296
+	) {
1297
+		return $this->_get_consecutive(
1298
+			$current_field_value,
1299
+			'>',
1300
+			$field_to_order_by,
1301
+			$limit,
1302
+			$query_params,
1303
+			$columns_to_select
1304
+		);
1305
+	}
1306
+
1307
+
1308
+	/**
1309
+	 * Returns the previous x number of items in sequence from the given value
1310
+	 * as found in the database matching the given query conditions.
1311
+	 *
1312
+	 * @param mixed $current_field_value    Value used for the reference point.
1313
+	 * @param null  $field_to_order_by      What field is used for the
1314
+	 *                                      reference point.
1315
+	 * @param int   $limit                  How many to return.
1316
+	 * @param array $query_params           Extra conditions on the query.
1317
+	 * @param null  $columns_to_select      If left null, then an array of
1318
+	 *                                      EE_Base_Class objects is returned,
1319
+	 *                                      otherwise you can indicate just the
1320
+	 *                                      columns you want returned.
1321
+	 * @return EE_Base_Class[]|array
1322
+	 * @throws EE_Error
1323
+	 * @throws ReflectionException
1324
+	 */
1325
+	public function previous_x(
1326
+		$current_field_value,
1327
+		$field_to_order_by = null,
1328
+		$limit = 1,
1329
+		$query_params = [],
1330
+		$columns_to_select = null
1331
+	) {
1332
+		return $this->_get_consecutive(
1333
+			$current_field_value,
1334
+			'<',
1335
+			$field_to_order_by,
1336
+			$limit,
1337
+			$query_params,
1338
+			$columns_to_select
1339
+		);
1340
+	}
1341
+
1342
+
1343
+	/**
1344
+	 * Returns the next item in sequence from the given value as found in the
1345
+	 * database matching the given query conditions.
1346
+	 *
1347
+	 * @param mixed $current_field_value    Value used for the reference point.
1348
+	 * @param null  $field_to_order_by      What field is used for the
1349
+	 *                                      reference point.
1350
+	 * @param array $query_params           Extra conditions on the query.
1351
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1352
+	 *                                      object is returned, otherwise you
1353
+	 *                                      can indicate just the columns you
1354
+	 *                                      want and a single array indexed by
1355
+	 *                                      the columns will be returned.
1356
+	 * @return EE_Base_Class|null|array()
1357
+	 * @throws EE_Error
1358
+	 * @throws ReflectionException
1359
+	 */
1360
+	public function next(
1361
+		$current_field_value,
1362
+		$field_to_order_by = null,
1363
+		$query_params = [],
1364
+		$columns_to_select = null
1365
+	) {
1366
+		$results = $this->_get_consecutive(
1367
+			$current_field_value,
1368
+			'>',
1369
+			$field_to_order_by,
1370
+			1,
1371
+			$query_params,
1372
+			$columns_to_select
1373
+		);
1374
+		return empty($results)
1375
+			? null
1376
+			: reset($results);
1377
+	}
1378
+
1379
+
1380
+	/**
1381
+	 * Returns the previous item in sequence from the given value as found in
1382
+	 * the database matching the given query conditions.
1383
+	 *
1384
+	 * @param mixed $current_field_value    Value used for the reference point.
1385
+	 * @param null  $field_to_order_by      What field is used for the
1386
+	 *                                      reference point.
1387
+	 * @param array $query_params           Extra conditions on the query.
1388
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1389
+	 *                                      object is returned, otherwise you
1390
+	 *                                      can indicate just the columns you
1391
+	 *                                      want and a single array indexed by
1392
+	 *                                      the columns will be returned.
1393
+	 * @return EE_Base_Class|null|array()
1394
+	 * @throws EE_Error
1395
+	 * @throws ReflectionException
1396
+	 */
1397
+	public function previous(
1398
+		$current_field_value,
1399
+		$field_to_order_by = null,
1400
+		$query_params = [],
1401
+		$columns_to_select = null
1402
+	) {
1403
+		$results = $this->_get_consecutive(
1404
+			$current_field_value,
1405
+			'<',
1406
+			$field_to_order_by,
1407
+			1,
1408
+			$query_params,
1409
+			$columns_to_select
1410
+		);
1411
+		return empty($results)
1412
+			? null
1413
+			: reset($results);
1414
+	}
1415
+
1416
+
1417
+	/**
1418
+	 * Returns the a consecutive number of items in sequence from the given
1419
+	 * value as found in the database matching the given query conditions.
1420
+	 *
1421
+	 * @param mixed  $current_field_value   Value used for the reference point.
1422
+	 * @param string $operand               What operand is used for the sequence.
1423
+	 * @param string $field_to_order_by     What field is used for the reference point.
1424
+	 * @param int    $limit                 How many to return.
1425
+	 * @param array  $query_params          Extra conditions on the query.
1426
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1427
+	 *                                      otherwise you can indicate just the columns you want returned.
1428
+	 * @return EE_Base_Class[]|array
1429
+	 * @throws EE_Error
1430
+	 * @throws ReflectionException
1431
+	 */
1432
+	protected function _get_consecutive(
1433
+		$current_field_value,
1434
+		$operand = '>',
1435
+		$field_to_order_by = null,
1436
+		$limit = 1,
1437
+		$query_params = [],
1438
+		$columns_to_select = null
1439
+	) {
1440
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1441
+		if (empty($field_to_order_by)) {
1442
+			if ($this->has_primary_key_field()) {
1443
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1444
+			} else {
1445
+				if (WP_DEBUG) {
1446
+					throw new EE_Error(
1447
+						esc_html__(
1448
+							'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1449
+							'event_espresso'
1450
+						)
1451
+					);
1452
+				}
1453
+				EE_Error::add_error(
1454
+					esc_html__('There was an error with the query.', 'event_espresso'),
1455
+					__FILE__,
1456
+					__FUNCTION__,
1457
+					__LINE__
1458
+				);
1459
+				return [];
1460
+			}
1461
+		}
1462
+		if (! is_array($query_params)) {
1463
+			EE_Error::doing_it_wrong(
1464
+				'EEM_Base::_get_consecutive',
1465
+				sprintf(
1466
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1467
+					gettype($query_params)
1468
+				),
1469
+				'4.6.0'
1470
+			);
1471
+			$query_params = [];
1472
+		}
1473
+		// let's add the where query param for consecutive look up.
1474
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1475
+		$query_params['limit']                 = $limit;
1476
+		// set direction
1477
+		$incoming_orderby         = isset($query_params['order_by'])
1478
+			? (array) $query_params['order_by']
1479
+			: [];
1480
+		$query_params['order_by'] = $operand === '>'
1481
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1482
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1483
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1484
+		if (empty($columns_to_select)) {
1485
+			return $this->get_all($query_params);
1486
+		}
1487
+		// getting just the fields
1488
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1489
+	}
1490
+
1491
+
1492
+	/**
1493
+	 * This sets the _timezone property after model object has been instantiated.
1494
+	 *
1495
+	 * @param string|null $timezone valid PHP DateTimeZone timezone string
1496
+	 * @throws Exception
1497
+	 */
1498
+	public function set_timezone(?string $timezone = '')
1499
+	{
1500
+		if (! $timezone) {
1501
+			return;
1502
+		}
1503
+		$this->_timezone = $timezone;
1504
+		// note we need to loop through relations and set the timezone on those objects as well.
1505
+		foreach ($this->_model_relations as $relation) {
1506
+			$relation->set_timezone($timezone);
1507
+		}
1508
+		// and finally we do the same for any datetime fields
1509
+		foreach ($this->_fields as $field) {
1510
+			if ($field instanceof EE_Datetime_Field) {
1511
+				$field->set_timezone($timezone);
1512
+			}
1513
+		}
1514
+	}
1515
+
1516
+
1517
+	/**
1518
+	 * This just returns whatever is set for the current timezone.
1519
+	 *
1520
+	 * @access public
1521
+	 * @return string
1522
+	 * @throws Exception
1523
+	 */
1524
+	public function get_timezone()
1525
+	{
1526
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1527
+		if (empty($this->_timezone)) {
1528
+			foreach ($this->_fields as $field) {
1529
+				if ($field instanceof EE_Datetime_Field) {
1530
+					$this->set_timezone($field->get_timezone());
1531
+					break;
1532
+				}
1533
+			}
1534
+		}
1535
+		// if timezone STILL empty then return the default timezone for the site.
1536
+		if (empty($this->_timezone)) {
1537
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1538
+		}
1539
+		return $this->_timezone;
1540
+	}
1541
+
1542
+
1543
+	/**
1544
+	 * This returns the date formats set for the given field name and also ensures that
1545
+	 * $this->_timezone property is set correctly.
1546
+	 *
1547
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1548
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1549
+	 * @return array formats in an array with the date format first, and the time format last.
1550
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1551
+	 * @since 4.6.x
1552
+	 */
1553
+	public function get_formats_for($field_name, $pretty = false)
1554
+	{
1555
+		$field_settings = $this->field_settings_for($field_name);
1556
+		// if not a valid EE_Datetime_Field then throw error
1557
+		if (! $field_settings instanceof EE_Datetime_Field) {
1558
+			throw new EE_Error(
1559
+				sprintf(
1560
+					esc_html__(
1561
+						'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1562
+						'event_espresso'
1563
+					),
1564
+					$field_name
1565
+				)
1566
+			);
1567
+		}
1568
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1569
+		// the field.
1570
+		$this->_timezone = $field_settings->get_timezone();
1571
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1572
+	}
1573
+
1574
+
1575
+	/**
1576
+	 * This returns the current time in a format setup for a query on this model.
1577
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1578
+	 * it will return:
1579
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1580
+	 *  NOW
1581
+	 *  - or a unix timestamp (equivalent to time())
1582
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1583
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1584
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1585
+	 *
1586
+	 * @param string $field_name       The field the current time is needed for.
1587
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1588
+	 *                                 formatted string matching the set format for the field in the set timezone will
1589
+	 *                                 be returned.
1590
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1591
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1592
+	 *                                 exception is triggered.
1593
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1594
+	 * @throws Exception
1595
+	 * @since 4.6.x
1596
+	 */
1597
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1598
+	{
1599
+		$formats  = $this->get_formats_for($field_name);
1600
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1601
+		if ($timestamp) {
1602
+			return $DateTime->format('U');
1603
+		}
1604
+		// not returning timestamp, so return formatted string in timezone.
1605
+		switch ($what) {
1606
+			case 'time':
1607
+				return $DateTime->format($formats[1]);
1608
+			case 'date':
1609
+				return $DateTime->format($formats[0]);
1610
+			default:
1611
+				return $DateTime->format(implode(' ', $formats));
1612
+		}
1613
+	}
1614
+
1615
+
1616
+	/**
1617
+	 * This receives a time string for a given field and ensures
1618
+	 * that it is set up to match what the internal settings for the model are.
1619
+	 * Returns a DateTime object.
1620
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1621
+	 * (functionally the equivalent of UTC+0).
1622
+	 * So when you send it in, whatever timezone string you include is ignored.
1623
+	 *
1624
+	 * @param string      $field_name      The field being setup.
1625
+	 * @param string      $timestring      The date time string being used.
1626
+	 * @param string      $incoming_format The format for the time string.
1627
+	 * @param string|null $timezone_string By default, it is assumed the incoming time string is in timezone for
1628
+	 *                                     the blog.  If this is not the case, then it can be specified here.  If
1629
+	 *                                     incoming format is
1630
+	 *                                     'U', this is ignored.
1631
+	 * @return DbSafeDateTime
1632
+	 * @throws EE_Error
1633
+	 * @throws Exception
1634
+	 */
1635
+	public function convert_datetime_for_query(
1636
+		string $field_name,
1637
+		string $timestring,
1638
+		string $incoming_format,
1639
+		?string $timezone_string = ''
1640
+	): DbSafeDateTime {
1641
+		// just using this to ensure the timezone is set correctly internally
1642
+		$this->get_formats_for($field_name);
1643
+		// load EEH_DTT_Helper
1644
+		$timezone_string     = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1645
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($timezone_string));
1646
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1647
+		return DbSafeDateTime::createFromDateTime($incomingDateTime);
1648
+	}
1649
+
1650
+
1651
+	/**
1652
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1653
+	 *
1654
+	 * @return EE_Table_Base[]
1655
+	 */
1656
+	public function get_tables()
1657
+	{
1658
+		return $this->_tables;
1659
+	}
1660
+
1661
+
1662
+	/**
1663
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1664
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1665
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1666
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1667
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1668
+	 * model object with EVT_ID = 1
1669
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1670
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1671
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1672
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1673
+	 * are not specified)
1674
+	 *
1675
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1676
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1677
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1678
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1679
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1680
+	 *                                         ID=34, we'd use this method as follows:
1681
+	 *                                         EEM_Transaction::instance()->update(
1682
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1683
+	 *                                         array(array('TXN_ID'=>34)));
1684
+	 * @param array   $query_params            @see
1685
+	 *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1686
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1687
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1688
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1689
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1690
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1691
+	 *                                         TRUE, it is assumed that you've already called
1692
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1693
+	 *                                         malicious javascript. However, if
1694
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1695
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1696
+	 *                                         and every other field, before insertion. We provide this parameter
1697
+	 *                                         because model objects perform their prepare_for_set function on all
1698
+	 *                                         their values, and so don't need to be called again (and in many cases,
1699
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1700
+	 *                                         prepare_for_set method...)
1701
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1702
+	 *                                         in this model's entity map according to $fields_n_values that match
1703
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1704
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1705
+	 *                                         could get out-of-sync with the database
1706
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1707
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1708
+	 *                                         bad)
1709
+	 * @throws EE_Error
1710
+	 * @throws ReflectionException
1711
+	 */
1712
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1713
+	{
1714
+		if (! is_array($query_params)) {
1715
+			EE_Error::doing_it_wrong(
1716
+				'EEM_Base::update',
1717
+				sprintf(
1718
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1719
+					gettype($query_params)
1720
+				),
1721
+				'4.6.0'
1722
+			);
1723
+			$query_params = [];
1724
+		}
1725
+		/**
1726
+		 * Action called before a model update call has been made.
1727
+		 *
1728
+		 * @param EEM_Base $model
1729
+		 * @param array    $fields_n_values the updated fields and their new values
1730
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1731
+		 */
1732
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1733
+		/**
1734
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1735
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1736
+		 *
1737
+		 * @param array    $fields_n_values fields and their new values
1738
+		 * @param EEM_Base $model           the model being queried
1739
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1740
+		 */
1741
+		$fields_n_values = (array) apply_filters(
1742
+			'FHEE__EEM_Base__update__fields_n_values',
1743
+			$fields_n_values,
1744
+			$this,
1745
+			$query_params
1746
+		);
1747
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1748
+		// to do that, for each table, verify that it's PK isn't null.
1749
+		$tables = $this->get_tables();
1750
+		// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1751
+		// NOTE: we should make this code more efficient by NOT querying twice
1752
+		// before the real update, but that needs to first go through ALPHA testing
1753
+		// as it's dangerous. says Mike August 8 2014
1754
+		// we want to make sure the default_where strategy is ignored
1755
+		$this->_ignore_where_strategy = true;
1756
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1757
+		foreach ($wpdb_select_results as $wpdb_result) {
1758
+			// type cast stdClass as array
1759
+			$wpdb_result = (array) $wpdb_result;
1760
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1761
+			if ($this->has_primary_key_field()) {
1762
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1763
+			} else {
1764
+				// if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1765
+				$main_table_pk_value = null;
1766
+			}
1767
+			// if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1768
+			// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1769
+			if (count($tables) > 1) {
1770
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1771
+				// in that table, and so we'll want to insert one
1772
+				foreach ($tables as $table_obj) {
1773
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1774
+					// if there is no private key for this table on the results, it means there's no entry
1775
+					// in this table, right? so insert a row in the current table, using any fields available
1776
+					if (
1777
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1778
+						   && $wpdb_result[ $this_table_pk_column ])
1779
+					) {
1780
+						$success = $this->_insert_into_specific_table(
1781
+							$table_obj,
1782
+							$fields_n_values,
1783
+							$main_table_pk_value
1784
+						);
1785
+						// if we died here, report the error
1786
+						if (! $success) {
1787
+							return false;
1788
+						}
1789
+					}
1790
+				}
1791
+			}
1792
+			//              //and now check that if we have cached any models by that ID on the model, that
1793
+			//              //they also get updated properly
1794
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1795
+			//              if( $model_object ){
1796
+			//                  foreach( $fields_n_values as $field => $value ){
1797
+			//                      $model_object->set($field, $value);
1798
+			// let's make sure default_where strategy is followed now
1799
+			$this->_ignore_where_strategy = false;
1800
+		}
1801
+		// if we want to keep model objects in sync, AND
1802
+		// if this wasn't called from a model object (to update itself)
1803
+		// then we want to make sure we keep all the existing
1804
+		// model objects in sync with the db
1805
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1806
+			if ($this->has_primary_key_field()) {
1807
+				$model_objs_affected_ids = $this->get_col($query_params);
1808
+			} else {
1809
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1810
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1811
+				$model_objs_affected_ids     = [];
1812
+				foreach ($models_affected_key_columns as $row) {
1813
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1814
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1815
+				}
1816
+			}
1817
+			if (! $model_objs_affected_ids) {
1818
+				// wait wait wait- if nothing was affected let's stop here
1819
+				return 0;
1820
+			}
1821
+			foreach ($model_objs_affected_ids as $id) {
1822
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1823
+				if ($model_obj_in_entity_map) {
1824
+					foreach ($fields_n_values as $field => $new_value) {
1825
+						$model_obj_in_entity_map->set($field, $new_value);
1826
+					}
1827
+				}
1828
+			}
1829
+			// if there is a primary key on this model, we can now do a slight optimization
1830
+			if ($this->has_primary_key_field()) {
1831
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1832
+				$query_params = [
1833
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1834
+					'limit'                    => count($model_objs_affected_ids),
1835
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1836
+				];
1837
+			}
1838
+		}
1839
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1840
+
1841
+		// note: the following query doesn't use _construct_2nd_half_of_select_query()
1842
+		// because it doesn't accept LIMIT, ORDER BY, etc.
1843
+		$rows_affected = $this->_do_wpdb_query(
1844
+			'query',
1845
+			[
1846
+				"UPDATE " . $model_query_info->get_full_join_sql()
1847
+				. " SET " . $this->_construct_update_sql($fields_n_values)
1848
+				. $model_query_info->get_where_sql(),
1849
+			]
1850
+		);
1851
+
1852
+		/**
1853
+		 * Action called after a model update call has been made.
1854
+		 *
1855
+		 * @param EEM_Base $model
1856
+		 * @param array    $fields_n_values the updated fields and their new values
1857
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1858
+		 * @param int      $rows_affected
1859
+		 */
1860
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1861
+		return $rows_affected;// how many supposedly got updated
1862
+	}
1863
+
1864
+
1865
+	/**
1866
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1867
+	 * are teh values of the field specified (or by default the primary key field)
1868
+	 * that matched the query params. Note that you should pass the name of the
1869
+	 * model FIELD, not the database table's column name.
1870
+	 *
1871
+	 * @param array  $query_params @see
1872
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1873
+	 * @param string $field_to_select
1874
+	 * @return array just like $wpdb->get_col()
1875
+	 * @throws EE_Error
1876
+	 * @throws ReflectionException
1877
+	 */
1878
+	public function get_col($query_params = [], $field_to_select = null)
1879
+	{
1880
+		if ($field_to_select) {
1881
+			$field = $this->field_settings_for($field_to_select);
1882
+		} elseif ($this->has_primary_key_field()) {
1883
+			$field = $this->get_primary_key_field();
1884
+		} else {
1885
+			$field_settings = $this->field_settings();
1886
+			// no primary key, just grab the first column
1887
+			$field = reset($field_settings);
1888
+			// don't need this array now
1889
+			unset($field_settings);
1890
+		}
1891
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1892
+		$select_expressions = $field->get_qualified_column();
1893
+		$SQL                =
1894
+			"SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1895
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1896
+	}
1897
+
1898
+
1899
+	/**
1900
+	 * Returns a single column value for a single row from the database
1901
+	 *
1902
+	 * @param array  $query_params    @see
1903
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1904
+	 * @param string $field_to_select @see EEM_Base::get_col()
1905
+	 * @return string
1906
+	 * @throws EE_Error
1907
+	 * @throws ReflectionException
1908
+	 */
1909
+	public function get_var($query_params = [], $field_to_select = null)
1910
+	{
1911
+		$query_params['limit'] = 1;
1912
+		$col                   = $this->get_col($query_params, $field_to_select);
1913
+		if (! empty($col)) {
1914
+			return reset($col);
1915
+		}
1916
+		return null;
1917
+	}
1918
+
1919
+
1920
+	/**
1921
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1922
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1923
+	 * injection, but currently no further filtering is done
1924
+	 *
1925
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1926
+	 *                               be updated to in the DB
1927
+	 * @return string of SQL
1928
+	 * @throws EE_Error
1929
+	 * @global      $wpdb
1930
+	 */
1931
+	public function _construct_update_sql($fields_n_values)
1932
+	{
1933
+		/** @type WPDB $wpdb */
1934
+		global $wpdb;
1935
+		$cols_n_values = [];
1936
+		foreach ($fields_n_values as $field_name => $value) {
1937
+			$field_obj = $this->field_settings_for($field_name);
1938
+			// if the value is NULL, we want to assign the value to that.
1939
+			// wpdb->prepare doesn't really handle that properly
1940
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1941
+			$value_sql       = $prepared_value === null
1942
+				? 'NULL'
1943
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1944
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1945
+		}
1946
+		return implode(",", $cols_n_values);
1947
+	}
1948
+
1949
+
1950
+	/**
1951
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1952
+	 * Performs a HARD delete, meaning the database row should always be removed,
1953
+	 * not just have a flag field on it switched
1954
+	 * Wrapper for EEM_Base::delete_permanently()
1955
+	 *
1956
+	 * @param mixed   $id
1957
+	 * @param boolean $allow_blocking
1958
+	 * @return int the number of rows deleted
1959
+	 * @throws EE_Error
1960
+	 * @throws ReflectionException
1961
+	 */
1962
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1963
+	{
1964
+		return $this->delete_permanently(
1965
+			[
1966
+				[$this->get_primary_key_field()->get_name() => $id],
1967
+				'limit' => 1,
1968
+			],
1969
+			$allow_blocking
1970
+		);
1971
+	}
1972
+
1973
+
1974
+	/**
1975
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1976
+	 * Wrapper for EEM_Base::delete()
1977
+	 *
1978
+	 * @param mixed   $id
1979
+	 * @param boolean $allow_blocking
1980
+	 * @return int the number of rows deleted
1981
+	 * @throws EE_Error
1982
+	 * @throws ReflectionException
1983
+	 */
1984
+	public function delete_by_ID($id, $allow_blocking = true)
1985
+	{
1986
+		return $this->delete(
1987
+			[
1988
+				[$this->get_primary_key_field()->get_name() => $id],
1989
+				'limit' => 1,
1990
+			],
1991
+			$allow_blocking
1992
+		);
1993
+	}
1994
+
1995
+
1996
+	/**
1997
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1998
+	 * meaning if the model has a field that indicates its been "trashed" or
1999
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
2000
+	 *
2001
+	 * @param array   $query_params
2002
+	 * @param boolean $allow_blocking
2003
+	 * @return int how many rows got deleted
2004
+	 * @throws EE_Error
2005
+	 * @throws ReflectionException
2006
+	 * @see EEM_Base::delete_permanently
2007
+	 */
2008
+	public function delete($query_params, $allow_blocking = true)
2009
+	{
2010
+		return $this->delete_permanently($query_params, $allow_blocking);
2011
+	}
2012
+
2013
+
2014
+	/**
2015
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
2016
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
2017
+	 * as archived, not actually deleted
2018
+	 *
2019
+	 * @param array   $query_params   @see
2020
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2021
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
2022
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
2023
+	 *                                deletes regardless of other objects which may depend on it. Its generally
2024
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
2025
+	 *                                DB
2026
+	 * @return int how many rows got deleted
2027
+	 * @throws EE_Error
2028
+	 * @throws ReflectionException
2029
+	 */
2030
+	public function delete_permanently($query_params, $allow_blocking = true)
2031
+	{
2032
+		/**
2033
+		 * Action called just before performing a real deletion query. You can use the
2034
+		 * model and its $query_params to find exactly which items will be deleted
2035
+		 *
2036
+		 * @param EEM_Base $model
2037
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2038
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
2039
+		 *                                 to block (prevent) this deletion
2040
+		 */
2041
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
2042
+		// some MySQL databases may be running safe mode, which may restrict
2043
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
2044
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
2045
+		// to delete them
2046
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2047
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2048
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2049
+			$columns_and_ids_for_deleting
2050
+		);
2051
+		/**
2052
+		 * Allows client code to act on the items being deleted before the query is actually executed.
2053
+		 *
2054
+		 * @param EEM_Base $this                            The model instance being acted on.
2055
+		 * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
2056
+		 * @param bool     $allow_blocking                  @see param description in method phpdoc block.
2057
+		 * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
2058
+		 *                                                  derived from the incoming query parameters.
2059
+		 * @see details on the structure of this array in the phpdocs
2060
+		 *                                                  for the `_get_ids_for_delete_method`
2061
+		 */
2062
+		do_action(
2063
+			'AHEE__EEM_Base__delete__before_query',
2064
+			$this,
2065
+			$query_params,
2066
+			$allow_blocking,
2067
+			$columns_and_ids_for_deleting
2068
+		);
2069
+		$rows_deleted = 0;
2070
+		if ($deletion_where_query_part) {
2071
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2072
+			$table_aliases    = array_keys($this->_tables);
2073
+			$SQL              = "DELETE "
2074
+								. implode(", ", $table_aliases)
2075
+								. " FROM "
2076
+								. $model_query_info->get_full_join_sql()
2077
+								. " WHERE "
2078
+								. $deletion_where_query_part;
2079
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2080
+		}
2081
+
2082
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2083
+		// there was no error with the delete query.
2084
+		if (
2085
+			$this->has_primary_key_field()
2086
+			&& $rows_deleted !== false
2087
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2088
+		) {
2089
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2090
+			foreach ($ids_for_removal as $id) {
2091
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2092
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2093
+				}
2094
+			}
2095
+
2096
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2097
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2098
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2099
+			// (although it is possible).
2100
+			// Note this can be skipped by using the provided filter and returning false.
2101
+			if (
2102
+				apply_filters(
2103
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2104
+					! $this instanceof EEM_Extra_Meta,
2105
+					$this
2106
+				)
2107
+			) {
2108
+				EEM_Extra_Meta::instance()->delete_permanently(
2109
+					[
2110
+						0 => [
2111
+							'EXM_type' => $this->get_this_model_name(),
2112
+							'OBJ_ID'   => [
2113
+								'IN',
2114
+								$ids_for_removal,
2115
+							],
2116
+						],
2117
+					]
2118
+				);
2119
+			}
2120
+		}
2121
+
2122
+		/**
2123
+		 * Action called just after performing a real deletion query. Although at this point the
2124
+		 * items should have been deleted
2125
+		 *
2126
+		 * @param EEM_Base $model
2127
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2128
+		 * @param int      $rows_deleted
2129
+		 */
2130
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2131
+		return (int) $rows_deleted;// how many supposedly got deleted
2132
+	}
2133
+
2134
+
2135
+	/**
2136
+	 * Checks all the relations that throw error messages when there are blocking related objects
2137
+	 * for related model objects. If there are any related model objects on those relations,
2138
+	 * adds an EE_Error, and return true
2139
+	 *
2140
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2141
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2142
+	 *                                                 should be ignored when determining whether there are related
2143
+	 *                                                 model objects which block this model object's deletion. Useful
2144
+	 *                                                 if you know A is related to B and are considering deleting A,
2145
+	 *                                                 but want to see if A has any other objects blocking its deletion
2146
+	 *                                                 before removing the relation between A and B
2147
+	 * @return boolean
2148
+	 * @throws EE_Error
2149
+	 * @throws ReflectionException
2150
+	 */
2151
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2152
+	{
2153
+		// first, if $ignore_this_model_obj was supplied, get its model
2154
+		$ignored_model = $ignore_this_model_obj instanceof EE_Base_Class
2155
+			? $ignore_this_model_obj->get_model()
2156
+			: null;
2157
+		// now check all the relations of $this_model_obj_or_id and see if there
2158
+		// are any related model objects blocking it?
2159
+		$is_blocked = false;
2160
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2161
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2162
+				// if $ignore_this_model_obj was supplied, then for the query
2163
+				// on that model needs to be told to ignore $ignore_this_model_obj
2164
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2165
+					$related_model_objects = $relation_obj->get_all_related(
2166
+						$this_model_obj_or_id,
2167
+						[
2168
+							[
2169
+								$ignored_model->get_primary_key_field()->get_name() => [
2170
+									'!=',
2171
+									$ignore_this_model_obj->ID(),
2172
+								],
2173
+							],
2174
+						]
2175
+					);
2176
+				} else {
2177
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2178
+				}
2179
+				if ($related_model_objects) {
2180
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2181
+					$is_blocked = true;
2182
+				}
2183
+			}
2184
+		}
2185
+		return $is_blocked;
2186
+	}
2187
+
2188
+
2189
+	/**
2190
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2191
+	 *
2192
+	 * @param array $row_results_for_deleting
2193
+	 * @param bool  $allow_blocking
2194
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2195
+	 *                              model DOES have a primary_key_field, then the array will be a simple single
2196
+	 *                              dimension array where the key is the fully qualified primary key column and the
2197
+	 *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2198
+	 *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2199
+	 *                              be a two dimensional array where each element is a group of columns and values that
2200
+	 *                              get deleted. Example: array(
2201
+	 *                              0 => array(
2202
+	 *                              'Term_Relationship.object_id' => 1
2203
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2204
+	 *                              ),
2205
+	 *                              1 => array(
2206
+	 *                              'Term_Relationship.object_id' => 1
2207
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2208
+	 *                              )
2209
+	 *                              )
2210
+	 * @throws EE_Error
2211
+	 * @throws ReflectionException
2212
+	 */
2213
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2214
+	{
2215
+		$ids_to_delete_indexed_by_column = [];
2216
+		if ($this->has_primary_key_field()) {
2217
+			$primary_table = $this->_get_main_table();
2218
+			// following lines are commented out because the variables were not being used
2219
+			// not deleting because unsure if calls were intentionally causing side effects
2220
+			// $primary_table_pk_field          =
2221
+			//     $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2222
+			// $other_tables                    = $this->_get_other_tables();
2223
+			$ids_to_delete_indexed_by_column = $query = [];
2224
+			foreach ($row_results_for_deleting as $item_to_delete) {
2225
+				// before we mark this item for deletion,
2226
+				// make sure there's no related entities blocking its deletion (if we're checking)
2227
+				if (
2228
+					$allow_blocking
2229
+					&& $this->delete_is_blocked_by_related_models(
2230
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2231
+					)
2232
+				) {
2233
+					continue;
2234
+				}
2235
+				// primary table deletes
2236
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2237
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2238
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2239
+				}
2240
+			}
2241
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2242
+			$fields = $this->get_combined_primary_key_fields();
2243
+			foreach ($row_results_for_deleting as $item_to_delete) {
2244
+				$ids_to_delete_indexed_by_column_for_row = [];
2245
+				foreach ($fields as $cpk_field) {
2246
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2247
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2248
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2249
+					}
2250
+				}
2251
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2252
+			}
2253
+		} else {
2254
+			// so there's no primary key and no combined key...
2255
+			// sorry, can't help you
2256
+			throw new EE_Error(
2257
+				sprintf(
2258
+					esc_html__(
2259
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2260
+						"event_espresso"
2261
+					),
2262
+					get_class($this)
2263
+				)
2264
+			);
2265
+		}
2266
+		return $ids_to_delete_indexed_by_column;
2267
+	}
2268
+
2269
+
2270
+	/**
2271
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2272
+	 * the corresponding query_part for the query performing the delete.
2273
+	 *
2274
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2275
+	 * @return string
2276
+	 * @throws EE_Error
2277
+	 */
2278
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2279
+	{
2280
+		$query_part = '';
2281
+		if (empty($ids_to_delete_indexed_by_column)) {
2282
+			return $query_part;
2283
+		} elseif ($this->has_primary_key_field()) {
2284
+			$query = [];
2285
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2286
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2287
+			}
2288
+			$query_part = ! empty($query)
2289
+				? implode(' AND ', $query)
2290
+				: $query_part;
2291
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2292
+			$ways_to_identify_a_row = [];
2293
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2294
+				$values_for_each_combined_primary_key_for_a_row = [];
2295
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2296
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2297
+				}
2298
+				$ways_to_identify_a_row[] = '('
2299
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2300
+											. ')';
2301
+			}
2302
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2303
+		}
2304
+		return $query_part;
2305
+	}
2306
+
2307
+
2308
+	/**
2309
+	 * Gets the model field by the fully qualified name
2310
+	 *
2311
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2312
+	 * @return EE_Model_Field_Base
2313
+	 * @throws EE_Error
2314
+	 * @throws EE_Error
2315
+	 */
2316
+	public function get_field_by_column($qualified_column_name)
2317
+	{
2318
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2319
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2320
+				return $field_obj;
2321
+			}
2322
+		}
2323
+		throw new EE_Error(
2324
+			sprintf(
2325
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2326
+				$this->get_this_model_name(),
2327
+				$qualified_column_name
2328
+			)
2329
+		);
2330
+	}
2331
+
2332
+
2333
+	/**
2334
+	 * Count all the rows that match criteria the model query params.
2335
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2336
+	 * column
2337
+	 *
2338
+	 * @param array  $query_params   @see
2339
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2340
+	 * @param string $field_to_count field on model to count by (not column name)
2341
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2342
+	 *                               that by the setting $distinct to TRUE;
2343
+	 * @return int
2344
+	 * @throws EE_Error
2345
+	 * @throws ReflectionException
2346
+	 */
2347
+	public function count($query_params = [], $field_to_count = null, $distinct = false)
2348
+	{
2349
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2350
+		if ($field_to_count) {
2351
+			$field_obj       = $this->field_settings_for($field_to_count);
2352
+			$column_to_count = $field_obj->get_qualified_column();
2353
+		} elseif ($this->has_primary_key_field()) {
2354
+			$pk_field_obj    = $this->get_primary_key_field();
2355
+			$column_to_count = $pk_field_obj->get_qualified_column();
2356
+		} else {
2357
+			// there's no primary key
2358
+			// if we're counting distinct items, and there's no primary key,
2359
+			// we need to list out the columns for distinction;
2360
+			// otherwise we can just use star
2361
+			if ($distinct) {
2362
+				$columns_to_use = [];
2363
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2364
+					$columns_to_use[] = $field_obj->get_qualified_column();
2365
+				}
2366
+				$column_to_count = implode(',', $columns_to_use);
2367
+			} else {
2368
+				$column_to_count = '*';
2369
+			}
2370
+		}
2371
+		$column_to_count = $distinct
2372
+			? "DISTINCT " . $column_to_count
2373
+			: $column_to_count;
2374
+		$SQL             =
2375
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2376
+		return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2377
+	}
2378
+
2379
+
2380
+	/**
2381
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2382
+	 *
2383
+	 * @param array  $query_params @see
2384
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2385
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2386
+	 * @return float
2387
+	 * @throws EE_Error
2388
+	 * @throws ReflectionException
2389
+	 */
2390
+	public function sum($query_params, $field_to_sum = null)
2391
+	{
2392
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2393
+		if ($field_to_sum) {
2394
+			$field_obj = $this->field_settings_for($field_to_sum);
2395
+		} else {
2396
+			$field_obj = $this->get_primary_key_field();
2397
+		}
2398
+		$column_to_count = $field_obj->get_qualified_column();
2399
+		$SQL             =
2400
+			"SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2401
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2402
+		$data_type       = $field_obj->get_wpdb_data_type();
2403
+		if ($data_type === '%d' || $data_type === '%s') {
2404
+			return (float) $return_value;
2405
+		}
2406
+		// must be %f
2407
+		return (float) $return_value;
2408
+	}
2409
+
2410
+
2411
+	/**
2412
+	 * Just calls the specified method on $wpdb with the given arguments
2413
+	 * Consolidates a little extra error handling code
2414
+	 *
2415
+	 * @param string $wpdb_method
2416
+	 * @param array  $arguments_to_provide
2417
+	 * @return mixed
2418
+	 * @throws EE_Error
2419
+	 * @global wpdb  $wpdb
2420
+	 */
2421
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2422
+	{
2423
+		// if we're in maintenance mode level 2, DON'T run any queries
2424
+		// because level 2 indicates the database needs updating and
2425
+		// is probably out of sync with the code
2426
+		if (DbStatus::isOffline()) {
2427
+			throw new RuntimeException(
2428
+				esc_html__(
2429
+					"Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2430
+					"event_espresso"
2431
+				)
2432
+			);
2433
+		}
2434
+		/** @type WPDB $wpdb */
2435
+		global $wpdb;
2436
+		if (! method_exists($wpdb, $wpdb_method)) {
2437
+			throw new DomainException(
2438
+				sprintf(
2439
+					esc_html__(
2440
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2441
+						'event_espresso'
2442
+					),
2443
+					$wpdb_method
2444
+				)
2445
+			);
2446
+		}
2447
+		$old_show_errors_value = $wpdb->show_errors;
2448
+		if (WP_DEBUG) {
2449
+			$wpdb->show_errors(false);
2450
+		}
2451
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2452
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2453
+		if (WP_DEBUG) {
2454
+			$wpdb->show_errors($old_show_errors_value);
2455
+			if (! empty($wpdb->last_error)) {
2456
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2457
+			}
2458
+			if ($result === false) {
2459
+				throw new EE_Error(
2460
+					sprintf(
2461
+						esc_html__(
2462
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2463
+							'event_espresso'
2464
+						),
2465
+						$wpdb_method,
2466
+						var_export($arguments_to_provide, true)
2467
+					)
2468
+				);
2469
+			}
2470
+		} elseif ($result === false) {
2471
+			EE_Error::add_error(
2472
+				sprintf(
2473
+					esc_html__(
2474
+						'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2475
+						'event_espresso'
2476
+					),
2477
+					$wpdb_method,
2478
+					var_export($arguments_to_provide, true),
2479
+					$wpdb->last_error
2480
+				),
2481
+				__FILE__,
2482
+				__FUNCTION__,
2483
+				__LINE__
2484
+			);
2485
+		}
2486
+		return $result;
2487
+	}
2488
+
2489
+
2490
+	/**
2491
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2492
+	 * and if there's an error tries to verify the DB is correct. Uses
2493
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2494
+	 * we should try to fix the EE core db, the addons, or just give up
2495
+	 *
2496
+	 * @param string $wpdb_method
2497
+	 * @param array  $arguments_to_provide
2498
+	 * @return mixed
2499
+	 */
2500
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2501
+	{
2502
+		/** @type WPDB $wpdb */
2503
+		global $wpdb;
2504
+		$wpdb->last_error = null;
2505
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2506
+		// was there an error running the query? but we don't care on new activations
2507
+		// (we're going to setup the DB anyway on new activations)
2508
+		if (
2509
+			($result === false || ! empty($wpdb->last_error))
2510
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2511
+		) {
2512
+			switch (EEM_Base::$_db_verification_level) {
2513
+				case EEM_Base::db_verified_none:
2514
+					// let's double-check core's DB
2515
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2516
+					break;
2517
+				case EEM_Base::db_verified_core:
2518
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2519
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2520
+					break;
2521
+				case EEM_Base::db_verified_addons:
2522
+					// ummmm... you in trouble
2523
+					return $result;
2524
+			}
2525
+			if (! empty($error_message)) {
2526
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2527
+				trigger_error($error_message);
2528
+			}
2529
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2530
+		}
2531
+		return $result;
2532
+	}
2533
+
2534
+
2535
+	/**
2536
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2537
+	 * EEM_Base::$_db_verification_level
2538
+	 *
2539
+	 * @param string $wpdb_method
2540
+	 * @param array  $arguments_to_provide
2541
+	 * @return string
2542
+	 * @throws EE_Error
2543
+	 * @throws ReflectionException
2544
+	 */
2545
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2546
+	{
2547
+		/** @type WPDB $wpdb */
2548
+		global $wpdb;
2549
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2550
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2551
+		$error_message                    = sprintf(
2552
+			esc_html__(
2553
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2554
+				'event_espresso'
2555
+			),
2556
+			$wpdb->last_error,
2557
+			$wpdb_method,
2558
+			wp_json_encode($arguments_to_provide)
2559
+		);
2560
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2561
+		return $error_message;
2562
+	}
2563
+
2564
+
2565
+	/**
2566
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2567
+	 * EEM_Base::$_db_verification_level
2568
+	 *
2569
+	 * @param $wpdb_method
2570
+	 * @param $arguments_to_provide
2571
+	 * @return string
2572
+	 * @throws EE_Error
2573
+	 * @throws ReflectionException
2574
+	 */
2575
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2576
+	{
2577
+		/** @type WPDB $wpdb */
2578
+		global $wpdb;
2579
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2580
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2581
+		$error_message                    = sprintf(
2582
+			esc_html__(
2583
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2584
+				'event_espresso'
2585
+			),
2586
+			$wpdb->last_error,
2587
+			$wpdb_method,
2588
+			wp_json_encode($arguments_to_provide)
2589
+		);
2590
+		EE_System::instance()->initialize_addons();
2591
+		return $error_message;
2592
+	}
2593
+
2594
+
2595
+	/**
2596
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2597
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2598
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2599
+	 * ..."
2600
+	 *
2601
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2602
+	 * @return string
2603
+	 */
2604
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2605
+	{
2606
+		return " FROM " . $model_query_info->get_full_join_sql() .
2607
+			   $model_query_info->get_where_sql() .
2608
+			   $model_query_info->get_group_by_sql() .
2609
+			   $model_query_info->get_having_sql() .
2610
+			   $model_query_info->get_order_by_sql() .
2611
+			   $model_query_info->get_limit_sql();
2612
+	}
2613
+
2614
+
2615
+	/**
2616
+	 * Set to easily debug the next X queries ran from this model.
2617
+	 *
2618
+	 * @param int $count
2619
+	 */
2620
+	public function show_next_x_db_queries($count = 1)
2621
+	{
2622
+		$this->_show_next_x_db_queries = $count;
2623
+	}
2624
+
2625
+
2626
+	/**
2627
+	 * @param $sql_query
2628
+	 */
2629
+	public function show_db_query_if_previously_requested($sql_query)
2630
+	{
2631
+		if ($this->_show_next_x_db_queries > 0) {
2632
+			$left = is_admin() ? '12rem' : '2rem';
2633
+			echo "
2634 2634
             <div class='ee-status-outline ee-status-bg--attention' style='margin: 2rem 2rem 2rem $left;'>
2635 2635
                 " . esc_html($sql_query) . "
2636 2636
             </div>";
2637
-            $this->_show_next_x_db_queries--;
2638
-        }
2639
-    }
2640
-
2641
-
2642
-    /**
2643
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2644
-     * There are the 3 cases:
2645
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2646
-     * $otherModelObject has no ID, it is first saved.
2647
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2648
-     * has no ID, it is first saved.
2649
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2650
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2651
-     * join table
2652
-     *
2653
-     * @param EE_Base_Class|int $id_or_obj                        EE_base_Class or ID of $thisModelObject
2654
-     * @param EE_Base_Class|int $other_model_id_or_obj            EE_base_Class or ID of other Model Object
2655
-     * @param string            $relationName                     , key in EEM_Base::_relations
2656
-     *                                                            an attendee to a group, you also want to specify
2657
-     *                                                            which role they will have in that group. So you would
2658
-     *                                                            use this parameter to specify
2659
-     *                                                            array('role-column-name'=>'role-id')
2660
-     * @param array|null        $extra_join_model_fields_n_values This allows you to enter further query params for the
2661
-     *                                                            relation to for relation to methods that allow you to
2662
-     *                                                            further specify extra columns to join by (such as
2663
-     *                                                            HABTM).  Keep in mind that the only acceptable
2664
-     *                                                            query_params is strict "col" => "value" pairs because
2665
-     *                                                            these will be inserted in any new rows created as
2666
-     *                                                            well.
2667
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2668
-     * @throws EE_Error
2669
-     */
2670
-    public function add_relationship_to(
2671
-        $id_or_obj,
2672
-        $other_model_id_or_obj,
2673
-        $relationName,
2674
-        $extra_join_model_fields_n_values = []
2675
-    ) {
2676
-        $relation_obj = $this->related_settings_for($relationName);
2677
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2678
-    }
2679
-
2680
-
2681
-    /**
2682
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2683
-     * There are the 3 cases:
2684
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2685
-     * error
2686
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2687
-     * an error
2688
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2689
-     *
2690
-     * @param EE_Base_Class|int $id_or_obj             EE_base_Class or ID of $thisModelObject
2691
-     * @param EE_Base_Class|int $other_model_id_or_obj EE_base_Class or ID of other Model Object
2692
-     * @param string            $relationName          key in EEM_Base::_relations
2693
-     * @param array|null        $where_query           This allows you to enter further query params for the relation
2694
-     *                                                 to for relation to methods that allow you to further specify
2695
-     *                                                 extra columns to join by (such as HABTM). Keep in mind that the
2696
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2697
-     *                                                 because these will be inserted in any new rows created as well.
2698
-     * @return EE_Base_Class
2699
-     * @throws EE_Error
2700
-     */
2701
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2702
-    {
2703
-        $relation_obj = $this->related_settings_for($relationName);
2704
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2705
-    }
2706
-
2707
-
2708
-    /**
2709
-     * @param mixed       $id_or_obj
2710
-     * @param string      $relationName
2711
-     * @param array|null  $where_query_params
2712
-     * @return EE_Base_Class[]
2713
-     * @throws EE_Error
2714
-     * @throws ReflectionException
2715
-     */
2716
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2717
-    {
2718
-        $relation_obj = $this->related_settings_for($relationName);
2719
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2720
-    }
2721
-
2722
-
2723
-    /**
2724
-     * Gets all the related items of the specified $model_name, using $query_params.
2725
-     * Note: by default, we remove the "default query params"
2726
-     * because we want to get even deleted items etc.
2727
-     *
2728
-     * @param mixed       $id_or_obj    EE_Base_Class child or its ID
2729
-     * @param string      $model_name   like 'Event', 'Registration', etc. always singular
2730
-     * @param array|null  $query_params @see
2731
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2732
-     * @return EE_Base_Class[]
2733
-     * @throws EE_Error
2734
-     * @throws ReflectionException
2735
-     */
2736
-    public function get_all_related($id_or_obj, $model_name, ?array $query_params = [])
2737
-    {
2738
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2739
-        $relation_settings = $this->related_settings_for($model_name);
2740
-        return $relation_settings->get_all_related($model_obj, $query_params);
2741
-    }
2742
-
2743
-
2744
-    /**
2745
-     * Deletes all the model objects across the relation indicated by $model_name
2746
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2747
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2748
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2749
-     *
2750
-     * @param EE_Base_Class|int|string $id_or_obj
2751
-     * @param string                   $model_name
2752
-     * @param array|null               $query_params
2753
-     * @return int how many deleted
2754
-     * @throws EE_Error
2755
-     * @throws ReflectionException
2756
-     */
2757
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2758
-    {
2759
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2760
-        $relation_settings = $this->related_settings_for($model_name);
2761
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2762
-    }
2763
-
2764
-
2765
-    /**
2766
-     * Hard deletes all the model objects across the relation indicated by $model_name
2767
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2768
-     * the model objects can't be hard deleted because of blocking related model objects,
2769
-     * just does a soft-delete on them instead.
2770
-     *
2771
-     * @param EE_Base_Class|int|string $id_or_obj
2772
-     * @param string                   $model_name
2773
-     * @param array|null               $query_params
2774
-     * @return int how many deleted
2775
-     * @throws EE_Error
2776
-     * @throws ReflectionException
2777
-     */
2778
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2779
-    {
2780
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2781
-        $relation_settings = $this->related_settings_for($model_name);
2782
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2783
-    }
2784
-
2785
-
2786
-    /**
2787
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2788
-     * unless otherwise specified in the $query_params
2789
-     *
2790
-     * @param EE_Base_Class|int|string $id_or_obj
2791
-     * @param string                   $model_name     like 'Event', or 'Registration'
2792
-     * @param array|null               $query_params   @see
2793
-     *                                                 https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2794
-     * @param string                   $field_to_count name of field to count by. By default, uses primary key
2795
-     * @param bool                     $distinct       if we want to only count the distinct values for the column then
2796
-     *                                                 you can trigger that by the setting $distinct to TRUE;
2797
-     * @return int
2798
-     * @throws EE_Error
2799
-     * @throws ReflectionException
2800
-     */
2801
-    public function count_related(
2802
-        $id_or_obj,
2803
-        $model_name,
2804
-        $query_params = [],
2805
-        $field_to_count = null,
2806
-        $distinct = false
2807
-    ) {
2808
-        $related_model = $this->get_related_model_obj($model_name);
2809
-        // we're just going to use the query params on the related model's normal get_all query,
2810
-        // except add a condition to say to match the current mod
2811
-        if (! isset($query_params['default_where_conditions'])) {
2812
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2813
-        }
2814
-        $this_model_name                                                 = $this->get_this_model_name();
2815
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2816
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2817
-        return $related_model->count($query_params, $field_to_count, $distinct);
2818
-    }
2819
-
2820
-
2821
-    /**
2822
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2823
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2824
-     *
2825
-     * @param EE_Base_Class|int|string $id_or_obj
2826
-     * @param string                   $model_name   like 'Event', or 'Registration'
2827
-     * @param array|null               $query_params @see
2828
-     *                                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2829
-     * @param string                   $field_to_sum name of field to count by. By default, uses primary key
2830
-     * @return float
2831
-     * @throws EE_Error
2832
-     * @throws ReflectionException
2833
-     */
2834
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2835
-    {
2836
-        $related_model = $this->get_related_model_obj($model_name);
2837
-        if (! is_array($query_params)) {
2838
-            EE_Error::doing_it_wrong(
2839
-                'EEM_Base::sum_related',
2840
-                sprintf(
2841
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2842
-                    gettype($query_params)
2843
-                ),
2844
-                '4.6.0'
2845
-            );
2846
-            $query_params = [];
2847
-        }
2848
-        // we're just going to use the query params on the related model's normal get_all query,
2849
-        // except add a condition to say to match the current mod
2850
-        if (! isset($query_params['default_where_conditions'])) {
2851
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2852
-        }
2853
-        $this_model_name                                                 = $this->get_this_model_name();
2854
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2855
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2856
-        return $related_model->sum($query_params, $field_to_sum);
2857
-    }
2858
-
2859
-
2860
-    /**
2861
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2862
-     * $modelObject
2863
-     *
2864
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2865
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2866
-     * @param array|null          $query_params     @see
2867
-     *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2868
-     * @return EE_Base_Class
2869
-     * @throws EE_Error
2870
-     * @throws ReflectionException
2871
-     */
2872
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2873
-    {
2874
-        $query_params['limit'] = 1;
2875
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2876
-        if ($results) {
2877
-            return array_shift($results);
2878
-        }
2879
-        return null;
2880
-    }
2881
-
2882
-
2883
-    /**
2884
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2885
-     *
2886
-     * @return string
2887
-     */
2888
-    public function get_this_model_name()
2889
-    {
2890
-        return str_replace("EEM_", "", get_class($this));
2891
-    }
2892
-
2893
-
2894
-    /**
2895
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2896
-     *
2897
-     * @return EE_Any_Foreign_Model_Name_Field
2898
-     * @throws EE_Error
2899
-     */
2900
-    public function get_field_containing_related_model_name()
2901
-    {
2902
-        foreach ($this->field_settings(true) as $field) {
2903
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2904
-                $field_with_model_name = $field;
2905
-            }
2906
-        }
2907
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2908
-            throw new EE_Error(
2909
-                sprintf(
2910
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2911
-                    $this->get_this_model_name()
2912
-                )
2913
-            );
2914
-        }
2915
-        return $field_with_model_name;
2916
-    }
2917
-
2918
-
2919
-    /**
2920
-     * Inserts a new entry into the database, for each table.
2921
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2922
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2923
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2924
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2925
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2926
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2927
-     *
2928
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2929
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2930
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2931
-     *                              of EEM_Base)
2932
-     * @return int|string new primary key on main table that got inserted
2933
-     * @throws EE_Error
2934
-     * @throws ReflectionException
2935
-     */
2936
-    public function insert($field_n_values)
2937
-    {
2938
-        /**
2939
-         * Filters the fields and their values before inserting an item using the models
2940
-         *
2941
-         * @param array    $fields_n_values keys are the fields and values are their new values
2942
-         * @param EEM_Base $model           the model used
2943
-         */
2944
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2945
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2946
-            $main_table = $this->_get_main_table();
2947
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2948
-            if ($new_id !== false) {
2949
-                foreach ($this->_get_other_tables() as $other_table) {
2950
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2951
-                }
2952
-            }
2953
-            /**
2954
-             * Done just after attempting to insert a new model object
2955
-             *
2956
-             * @param EEM_Base $model           used
2957
-             * @param array    $fields_n_values fields and their values
2958
-             * @param int|string the              ID of the newly-inserted model object
2959
-             */
2960
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2961
-            return $new_id;
2962
-        }
2963
-        return false;
2964
-    }
2965
-
2966
-
2967
-    /**
2968
-     * Checks that the result would satisfy the unique indexes on this model
2969
-     *
2970
-     * @param array  $field_n_values
2971
-     * @param string $action
2972
-     * @return boolean
2973
-     * @throws EE_Error
2974
-     * @throws ReflectionException
2975
-     */
2976
-    protected function _satisfies_unique_indexes(array $field_n_values, $action = 'insert')
2977
-    {
2978
-        foreach ($this->unique_indexes() as $index_name => $index) {
2979
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2980
-            if ($this->exists([$uniqueness_where_params])) {
2981
-                EE_Error::add_error(
2982
-                    sprintf(
2983
-                        esc_html__(
2984
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2985
-                            "event_espresso"
2986
-                        ),
2987
-                        $action,
2988
-                        $this->_get_class_name(),
2989
-                        $index_name,
2990
-                        implode(",", $index->field_names()),
2991
-                        http_build_query($uniqueness_where_params)
2992
-                    ),
2993
-                    __FILE__,
2994
-                    __FUNCTION__,
2995
-                    __LINE__
2996
-                );
2997
-                return false;
2998
-            }
2999
-        }
3000
-        return true;
3001
-    }
3002
-
3003
-
3004
-    /**
3005
-     * Checks the database for an item that conflicts (ie, if this item were
3006
-     * saved to the DB would break some uniqueness requirement, like a primary key
3007
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
3008
-     * can be either an EE_Base_Class or an array of fields n values
3009
-     *
3010
-     * @param EE_Base_Class|array $obj_or_fields_array
3011
-     * @param boolean             $include_primary_key whether to use the model object's primary key
3012
-     *                                                 when looking for conflicts
3013
-     *                                                 (ie, if false, we ignore the model object's primary key
3014
-     *                                                 when finding "conflicts". If true, it's also considered).
3015
-     *                                                 Only works for INT primary key,
3016
-     *                                                 STRING primary keys cannot be ignored
3017
-     * @return EE_Base_Class|array
3018
-     * @throws EE_Error
3019
-     * @throws ReflectionException
3020
-     */
3021
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
3022
-    {
3023
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
3024
-            $fields_n_values = $obj_or_fields_array->model_field_array();
3025
-        } elseif (is_array($obj_or_fields_array)) {
3026
-            $fields_n_values = $obj_or_fields_array;
3027
-        } else {
3028
-            throw new EE_Error(
3029
-                sprintf(
3030
-                    esc_html__(
3031
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
3032
-                        "event_espresso"
3033
-                    ),
3034
-                    get_class($this),
3035
-                    $obj_or_fields_array
3036
-                )
3037
-            );
3038
-        }
3039
-        $query_params = [];
3040
-        if (
3041
-            $this->has_primary_key_field()
3042
-            && ($include_primary_key
3043
-                || $this->get_primary_key_field()
3044
-                   instanceof
3045
-                   EE_Primary_Key_String_Field)
3046
-            && isset($fields_n_values[ $this->primary_key_name() ])
3047
-        ) {
3048
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3049
-        }
3050
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3051
-            $uniqueness_where_params                              =
3052
-                array_intersect_key($fields_n_values, $unique_index->fields());
3053
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3054
-        }
3055
-        // if there is nothing to base this search on, then we shouldn't find anything
3056
-        if (empty($query_params)) {
3057
-            return [];
3058
-        }
3059
-        return $this->get_one($query_params);
3060
-    }
3061
-
3062
-
3063
-    /**
3064
-     * Like count, but is optimized and returns a boolean instead of an int
3065
-     *
3066
-     * @param array $query_params
3067
-     * @return boolean
3068
-     * @throws EE_Error
3069
-     * @throws ReflectionException
3070
-     */
3071
-    public function exists($query_params)
3072
-    {
3073
-        $query_params['limit'] = 1;
3074
-        return $this->count($query_params) > 0;
3075
-    }
3076
-
3077
-
3078
-    /**
3079
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
3080
-     *
3081
-     * @param int|string $id
3082
-     * @return boolean
3083
-     * @throws EE_Error
3084
-     * @throws ReflectionException
3085
-     */
3086
-    public function exists_by_ID($id)
3087
-    {
3088
-        return $this->exists(
3089
-            [
3090
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3091
-                [
3092
-                    $this->primary_key_name() => $id,
3093
-                ],
3094
-            ]
3095
-        );
3096
-    }
3097
-
3098
-
3099
-    /**
3100
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3101
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3102
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3103
-     * on the main table)
3104
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3105
-     * cases where we want to call it directly rather than via insert().
3106
-     *
3107
-     * @access   protected
3108
-     * @param EE_Table_Base $table
3109
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3110
-     *                                       float
3111
-     * @param int           $new_id          for now we assume only int keys
3112
-     * @return int ID of new row inserted, or FALSE on failure
3113
-     * @throws EE_Error
3114
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3115
-     */
3116
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3117
-    {
3118
-        global $wpdb;
3119
-        $insertion_col_n_values = [];
3120
-        $format_for_insertion   = [];
3121
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3122
-        foreach ($fields_on_table as $field_obj) {
3123
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3124
-            if ($field_obj->is_auto_increment()) {
3125
-                continue;
3126
-            }
3127
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3128
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3129
-            if ($prepared_value !== null) {
3130
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3131
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3132
-            }
3133
-        }
3134
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3135
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3136
-            // so add the fk to the main table as a column
3137
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3138
-            $format_for_insertion[]                              =
3139
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3140
-        }
3141
-
3142
-        // insert the new entry
3143
-        $result = $this->_do_wpdb_query(
3144
-            'insert',
3145
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3146
-        );
3147
-        if ($result === false) {
3148
-            return false;
3149
-        }
3150
-        // ok, now what do we return for the ID of the newly-inserted thing?
3151
-        if ($this->has_primary_key_field()) {
3152
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3153
-                return $wpdb->insert_id;
3154
-            }
3155
-            // it's not an auto-increment primary key, so
3156
-            // it must have been supplied
3157
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3158
-        }
3159
-        // we can't return a  primary key because there is none. instead return
3160
-        // a unique string indicating this model
3161
-        return $this->get_index_primary_key_string($fields_n_values);
3162
-    }
3163
-
3164
-
3165
-    /**
3166
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3167
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3168
-     * and there is no default, we pass it along. WPDB will take care of it)
3169
-     *
3170
-     * @param EE_Model_Field_Base $field_obj
3171
-     * @param array               $fields_n_values
3172
-     * @return mixed string|int|float depending on what the table column will be expecting
3173
-     * @throws EE_Error
3174
-     */
3175
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3176
-    {
3177
-        $field_name = $field_obj->get_name();
3178
-        // if this field doesn't allow nullable, don't allow it
3179
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3180
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3181
-        }
3182
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3183
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3184
-    }
3185
-
3186
-
3187
-    /**
3188
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3189
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3190
-     * the field's prepare_for_set() method.
3191
-     *
3192
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3193
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3194
-     *                                   top of file)
3195
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3196
-     *                                   $value is a custom selection
3197
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3198
-     */
3199
-    private function _prepare_value_for_use_in_db($value, $field)
3200
-    {
3201
-        if ($field instanceof EE_Model_Field_Base) {
3202
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3203
-            switch ($this->_values_already_prepared_by_model_object) {
3204
-                /** @noinspection PhpMissingBreakStatementInspection */
3205
-                case self::not_prepared_by_model_object:
3206
-                    $value = $field->prepare_for_set($value);
3207
-                // purposefully left out "return"
3208
-                // no break
3209
-                case self::prepared_by_model_object:
3210
-                    /** @noinspection SuspiciousAssignmentsInspection */
3211
-                    $value = $field->prepare_for_use_in_db($value);
3212
-                // no break
3213
-                case self::prepared_for_use_in_db:
3214
-                    // leave the value alone
3215
-            }
3216
-            // phpcs:enable
3217
-        }
3218
-        return $value;
3219
-    }
3220
-
3221
-
3222
-    /**
3223
-     * Returns the main table on this model
3224
-     *
3225
-     * @return EE_Primary_Table
3226
-     * @throws EE_Error
3227
-     */
3228
-    protected function _get_main_table()
3229
-    {
3230
-        foreach ($this->_tables as $table) {
3231
-            if ($table instanceof EE_Primary_Table) {
3232
-                return $table;
3233
-            }
3234
-        }
3235
-        throw new EE_Error(
3236
-            sprintf(
3237
-                esc_html__(
3238
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3239
-                    'event_espresso'
3240
-                ),
3241
-                get_class($this)
3242
-            )
3243
-        );
3244
-    }
3245
-
3246
-
3247
-    /**
3248
-     * table
3249
-     * returns EE_Primary_Table table name
3250
-     *
3251
-     * @return string
3252
-     * @throws EE_Error
3253
-     */
3254
-    public function table()
3255
-    {
3256
-        return $this->_get_main_table()->get_table_name();
3257
-    }
3258
-
3259
-
3260
-    /**
3261
-     * table
3262
-     * returns first EE_Secondary_Table table name
3263
-     *
3264
-     * @return string
3265
-     */
3266
-    public function second_table()
3267
-    {
3268
-        // grab second table from tables array
3269
-        $second_table = end($this->_tables);
3270
-        return $second_table instanceof EE_Secondary_Table
3271
-            ? $second_table->get_table_name()
3272
-            : null;
3273
-    }
3274
-
3275
-
3276
-    /**
3277
-     * get_table_obj_by_alias
3278
-     * returns table name given it's alias
3279
-     *
3280
-     * @param string $table_alias
3281
-     * @return EE_Primary_Table | EE_Secondary_Table
3282
-     */
3283
-    public function get_table_obj_by_alias($table_alias = '')
3284
-    {
3285
-        return $this->_tables[ $table_alias ] ?? null;
3286
-    }
3287
-
3288
-
3289
-    /**
3290
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3291
-     *
3292
-     * @return EE_Secondary_Table[]
3293
-     */
3294
-    protected function _get_other_tables()
3295
-    {
3296
-        $other_tables = [];
3297
-        foreach ($this->_tables as $table_alias => $table) {
3298
-            if ($table instanceof EE_Secondary_Table) {
3299
-                $other_tables[ $table_alias ] = $table;
3300
-            }
3301
-        }
3302
-        return $other_tables;
3303
-    }
3304
-
3305
-
3306
-    /**
3307
-     * Finds all the fields that correspond to the given table
3308
-     *
3309
-     * @param string $table_alias , array key in EEM_Base::_tables
3310
-     * @return EE_Model_Field_Base[]
3311
-     */
3312
-    public function _get_fields_for_table($table_alias)
3313
-    {
3314
-        return $this->_fields[ $table_alias ];
3315
-    }
3316
-
3317
-
3318
-    /**
3319
-     * Recurses through all the where parameters, and finds all the related models we'll need
3320
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3321
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3322
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3323
-     * related Registration, Transaction, and Payment models.
3324
-     *
3325
-     * @param array $query_params @see
3326
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3327
-     * @return EE_Model_Query_Info_Carrier
3328
-     * @throws EE_Error
3329
-     */
3330
-    public function _extract_related_models_from_query($query_params)
3331
-    {
3332
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3333
-        if (array_key_exists(0, $query_params)) {
3334
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3335
-        }
3336
-        if (array_key_exists('group_by', $query_params)) {
3337
-            if (is_array($query_params['group_by'])) {
3338
-                $this->_extract_related_models_from_sub_params_array_values(
3339
-                    $query_params['group_by'],
3340
-                    $query_info_carrier,
3341
-                    'group_by'
3342
-                );
3343
-            } elseif (! empty($query_params['group_by'])) {
3344
-                $this->_extract_related_model_info_from_query_param(
3345
-                    $query_params['group_by'],
3346
-                    $query_info_carrier,
3347
-                    'group_by'
3348
-                );
3349
-            }
3350
-        }
3351
-        if (array_key_exists('having', $query_params)) {
3352
-            $this->_extract_related_models_from_sub_params_array_keys(
3353
-                $query_params[0],
3354
-                $query_info_carrier,
3355
-                'having'
3356
-            );
3357
-        }
3358
-        if (array_key_exists('order_by', $query_params)) {
3359
-            if (is_array($query_params['order_by'])) {
3360
-                $this->_extract_related_models_from_sub_params_array_keys(
3361
-                    $query_params['order_by'],
3362
-                    $query_info_carrier,
3363
-                    'order_by'
3364
-                );
3365
-            } elseif (! empty($query_params['order_by'])) {
3366
-                $this->_extract_related_model_info_from_query_param(
3367
-                    $query_params['order_by'],
3368
-                    $query_info_carrier,
3369
-                    'order_by'
3370
-                );
3371
-            }
3372
-        }
3373
-        if (array_key_exists('force_join', $query_params)) {
3374
-            $this->_extract_related_models_from_sub_params_array_values(
3375
-                $query_params['force_join'],
3376
-                $query_info_carrier,
3377
-                'force_join'
3378
-            );
3379
-        }
3380
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3381
-        return $query_info_carrier;
3382
-    }
3383
-
3384
-
3385
-    /**
3386
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3387
-     *
3388
-     * @param array                       $sub_query_params
3389
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3390
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3391
-     * @return EE_Model_Query_Info_Carrier
3392
-     * @throws EE_Error
3393
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3394
-     */
3395
-    private function _extract_related_models_from_sub_params_array_keys(
3396
-        $sub_query_params,
3397
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3398
-        $query_param_type
3399
-    ) {
3400
-        if (! empty($sub_query_params)) {
3401
-            $sub_query_params = (array) $sub_query_params;
3402
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3403
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3404
-                $this->_extract_related_model_info_from_query_param(
3405
-                    $param,
3406
-                    $model_query_info_carrier,
3407
-                    $query_param_type
3408
-                );
3409
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3410
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3411
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3412
-                // of array('Registration.TXN_ID'=>23)
3413
-                $query_param_sans_stars =
3414
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3415
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3416
-                    if (! is_array($possibly_array_of_params)) {
3417
-                        throw new EE_Error(
3418
-                            sprintf(
3419
-                                esc_html__(
3420
-                                    "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3421
-                                    "event_espresso"
3422
-                                ),
3423
-                                $param,
3424
-                                $possibly_array_of_params
3425
-                            )
3426
-                        );
3427
-                    }
3428
-                    $this->_extract_related_models_from_sub_params_array_keys(
3429
-                        $possibly_array_of_params,
3430
-                        $model_query_info_carrier,
3431
-                        $query_param_type
3432
-                    );
3433
-                } elseif (
3434
-                    $query_param_type === 0 // ie WHERE
3435
-                    && is_array($possibly_array_of_params) // need is_array() check so we don't try to explode a string
3436
-                    && isset($possibly_array_of_params[2])
3437
-                    && $possibly_array_of_params[2]
3438
-                ) {
3439
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3440
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3441
-                    // from which we should extract query parameters!
3442
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3443
-                        throw new EE_Error(
3444
-                            sprintf(
3445
-                                esc_html__(
3446
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3447
-                                    "event_espresso"
3448
-                                ),
3449
-                                $query_param_type,
3450
-                                implode(",", $possibly_array_of_params)
3451
-                            )
3452
-                        );
3453
-                    }
3454
-                    $this->_extract_related_model_info_from_query_param(
3455
-                        $possibly_array_of_params[1],
3456
-                        $model_query_info_carrier,
3457
-                        $query_param_type
3458
-                    );
3459
-                }
3460
-            }
3461
-        }
3462
-        return $model_query_info_carrier;
3463
-    }
3464
-
3465
-
3466
-    /**
3467
-     * For extracting related models from forced_joins, where the array values contain the info about what
3468
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3469
-     *
3470
-     * @param array                       $sub_query_params @see
3471
-     *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3472
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3473
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3474
-     * @return EE_Model_Query_Info_Carrier
3475
-     * @throws EE_Error
3476
-     */
3477
-    private function _extract_related_models_from_sub_params_array_values(
3478
-        $sub_query_params,
3479
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3480
-        $query_param_type
3481
-    ) {
3482
-        if (! empty($sub_query_params)) {
3483
-            if (! is_array($sub_query_params)) {
3484
-                throw new EE_Error(
3485
-                    sprintf(
3486
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3487
-                        $sub_query_params
3488
-                    )
3489
-                );
3490
-            }
3491
-            foreach ($sub_query_params as $param) {
3492
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3493
-                $this->_extract_related_model_info_from_query_param(
3494
-                    $param,
3495
-                    $model_query_info_carrier,
3496
-                    $query_param_type
3497
-                );
3498
-            }
3499
-        }
3500
-        return $model_query_info_carrier;
3501
-    }
3502
-
3503
-
3504
-    /**
3505
-     * Extract all the query parts from  model query params
3506
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3507
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3508
-     * but use them in a different order. Eg, we need to know what models we are querying
3509
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3510
-     * other models before we can finalize the where clause SQL.
3511
-     *
3512
-     * @param array $query_params
3513
-     * @return EE_Model_Query_Info_Carrier
3514
-     * @throws EE_Error
3515
-     * @throws ModelConfigurationException
3516
-     * @throws ReflectionException
3517
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3518
-     */
3519
-    public function _create_model_query_info_carrier($query_params)
3520
-    {
3521
-        if (! is_array($query_params)) {
3522
-            EE_Error::doing_it_wrong(
3523
-                'EEM_Base::_create_model_query_info_carrier',
3524
-                sprintf(
3525
-                    esc_html__(
3526
-                        '$query_params should be an array, you passed a variable of type %s',
3527
-                        'event_espresso'
3528
-                    ),
3529
-                    gettype($query_params)
3530
-                ),
3531
-                '4.6.0'
3532
-            );
3533
-            $query_params = [];
3534
-        }
3535
-        $query_params[0] = $query_params[0] ?? [];
3536
-        // first check if we should alter the query to account for caps or not
3537
-        // because the caps might require us to do extra joins
3538
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3539
-            $query_params[0] = array_replace_recursive(
3540
-                $query_params[0],
3541
-                $this->caps_where_conditions($query_params['caps'])
3542
-            );
3543
-        }
3544
-
3545
-        // check if we should alter the query to remove data related to protected
3546
-        // custom post types
3547
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3548
-            $where_param_key_for_password = $this->modelChainAndPassword();
3549
-            // only include if related to a cpt where no password has been set
3550
-            $query_params[0]['OR*nopassword'] = [
3551
-                $where_param_key_for_password       => '',
3552
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3553
-            ];
3554
-        }
3555
-        $query_object = $this->_extract_related_models_from_query($query_params);
3556
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3557
-        foreach ($query_params[0] as $key => $value) {
3558
-            if (is_int($key)) {
3559
-                throw new EE_Error(
3560
-                    sprintf(
3561
-                        esc_html__(
3562
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3563
-                            "event_espresso"
3564
-                        ),
3565
-                        $key,
3566
-                        var_export($value, true),
3567
-                        var_export($query_params, true),
3568
-                        get_class($this)
3569
-                    )
3570
-                );
3571
-            }
3572
-        }
3573
-        if (
3574
-            array_key_exists('default_where_conditions', $query_params)
3575
-            && ! empty($query_params['default_where_conditions'])
3576
-        ) {
3577
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3578
-        } else {
3579
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3580
-        }
3581
-        $query_params[0] = array_merge(
3582
-            $this->_get_default_where_conditions_for_models_in_query(
3583
-                $query_object,
3584
-                $use_default_where_conditions,
3585
-                $query_params[0]
3586
-            ),
3587
-            $query_params[0]
3588
-        );
3589
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3590
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3591
-        // So we need to setup a subquery and use that for the main join.
3592
-        // Note for now this only works on the primary table for the model.
3593
-        // So for instance, you could set the limit array like this:
3594
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3595
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3596
-            $query_object->set_main_model_join_sql(
3597
-                $this->_construct_limit_join_select(
3598
-                    $query_params['on_join_limit'][0],
3599
-                    $query_params['on_join_limit'][1]
3600
-                )
3601
-            );
3602
-        }
3603
-        // set limit
3604
-        if (array_key_exists('limit', $query_params)) {
3605
-            if (is_array($query_params['limit'])) {
3606
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3607
-                    $e = sprintf(
3608
-                        esc_html__(
3609
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3610
-                            "event_espresso"
3611
-                        ),
3612
-                        http_build_query($query_params['limit'])
3613
-                    );
3614
-                    throw new EE_Error($e . "|" . $e);
3615
-                }
3616
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3617
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3618
-            } elseif (! empty($query_params['limit'])) {
3619
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3620
-            }
3621
-        }
3622
-        // set order by
3623
-        if (array_key_exists('order_by', $query_params)) {
3624
-            if (is_array($query_params['order_by'])) {
3625
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3626
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3627
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3628
-                if (array_key_exists('order', $query_params)) {
3629
-                    throw new EE_Error(
3630
-                        sprintf(
3631
-                            esc_html__(
3632
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3633
-                                "event_espresso"
3634
-                            ),
3635
-                            get_class($this),
3636
-                            implode(", ", array_keys($query_params['order_by'])),
3637
-                            implode(", ", $query_params['order_by']),
3638
-                            $query_params['order']
3639
-                        )
3640
-                    );
3641
-                }
3642
-                $this->_extract_related_models_from_sub_params_array_keys(
3643
-                    $query_params['order_by'],
3644
-                    $query_object,
3645
-                    'order_by'
3646
-                );
3647
-                // assume it's an array of fields to order by
3648
-                $order_array = [];
3649
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3650
-                    $order         = $this->_extract_order($order);
3651
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3652
-                }
3653
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3654
-            } elseif (! empty($query_params['order_by'])) {
3655
-                $this->_extract_related_model_info_from_query_param(
3656
-                    $query_params['order_by'],
3657
-                    $query_object,
3658
-                    'order',
3659
-                    $query_params['order_by']
3660
-                );
3661
-                $order = isset($query_params['order'])
3662
-                    ? $this->_extract_order($query_params['order'])
3663
-                    : 'DESC';
3664
-                $query_object->set_order_by_sql(
3665
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3666
-                );
3667
-            }
3668
-        }
3669
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3670
-        if (
3671
-            ! array_key_exists('order_by', $query_params)
3672
-            && array_key_exists('order', $query_params)
3673
-            && ! empty($query_params['order'])
3674
-        ) {
3675
-            $pk_field = $this->get_primary_key_field();
3676
-            $order    = $this->_extract_order($query_params['order']);
3677
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3678
-        }
3679
-        // set group by
3680
-        if (array_key_exists('group_by', $query_params)) {
3681
-            if (is_array($query_params['group_by'])) {
3682
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3683
-                $group_by_array = [];
3684
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3685
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3686
-                }
3687
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3688
-            } elseif (! empty($query_params['group_by'])) {
3689
-                $query_object->set_group_by_sql(
3690
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3691
-                );
3692
-            }
3693
-        }
3694
-        // set having
3695
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3696
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3697
-        }
3698
-        // now, just verify they didn't pass anything wack
3699
-        foreach ($query_params as $query_key => $query_value) {
3700
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3701
-                throw new EE_Error(
3702
-                    sprintf(
3703
-                        esc_html__(
3704
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3705
-                            'event_espresso'
3706
-                        ),
3707
-                        $query_key,
3708
-                        get_class($this),
3709
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3710
-                        implode(',', $this->_allowed_query_params)
3711
-                    )
3712
-                );
3713
-            }
3714
-        }
3715
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3716
-        if (empty($main_model_join_sql)) {
3717
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3718
-        }
3719
-        return $query_object;
3720
-    }
3721
-
3722
-
3723
-    /**
3724
-     * Gets the where conditions that should be imposed on the query based on the
3725
-     * context (eg reading frontend, backend, edit or delete).
3726
-     *
3727
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3728
-     * @return array @see
3729
-     *                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3730
-     * @throws EE_Error
3731
-     */
3732
-    public function caps_where_conditions($context = self::caps_read)
3733
-    {
3734
-        EEM_Base::verify_is_valid_cap_context($context);
3735
-        $cap_where_conditions = [];
3736
-        $cap_restrictions     = $this->caps_missing($context);
3737
-        foreach ($cap_restrictions as $restriction_if_no_cap) {
3738
-            $cap_where_conditions = array_replace_recursive(
3739
-                $cap_where_conditions,
3740
-                $restriction_if_no_cap->get_default_where_conditions()
3741
-            );
3742
-        }
3743
-        return apply_filters(
3744
-            'FHEE__EEM_Base__caps_where_conditions__return',
3745
-            $cap_where_conditions,
3746
-            $this,
3747
-            $context,
3748
-            $cap_restrictions
3749
-        );
3750
-    }
3751
-
3752
-
3753
-    /**
3754
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3755
-     * otherwise throws an exception
3756
-     *
3757
-     * @param string $should_be_order_string
3758
-     * @return string either ASC, asc, DESC or desc
3759
-     * @throws EE_Error
3760
-     */
3761
-    private function _extract_order($should_be_order_string)
3762
-    {
3763
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3764
-            return $should_be_order_string;
3765
-        }
3766
-        throw new EE_Error(
3767
-            sprintf(
3768
-                esc_html__(
3769
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3770
-                    "event_espresso"
3771
-                ),
3772
-                get_class($this),
3773
-                $should_be_order_string
3774
-            )
3775
-        );
3776
-    }
3777
-
3778
-
3779
-    /**
3780
-     * Looks at all the models which are included in this query, and asks each
3781
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3782
-     * so they can be merged
3783
-     *
3784
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3785
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3786
-     *                                                                  'none' means NO default where conditions will
3787
-     *                                                                  be used AT ALL during this query.
3788
-     *                                                                  'other_models_only' means default where
3789
-     *                                                                  conditions from other models will be used, but
3790
-     *                                                                  not for this primary model. 'all', the default,
3791
-     *                                                                  means default where conditions will apply as
3792
-     *                                                                  normal
3793
-     * @param array                       $where_query_params
3794
-     * @return array
3795
-     * @throws EE_Error
3796
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params
3797
-     *                                                                  .md#0-where-conditions
3798
-     */
3799
-    private function _get_default_where_conditions_for_models_in_query(
3800
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3801
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3802
-        $where_query_params = []
3803
-    ) {
3804
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3805
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3806
-            throw new EE_Error(
3807
-                sprintf(
3808
-                    esc_html__(
3809
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3810
-                        "event_espresso"
3811
-                    ),
3812
-                    $use_default_where_conditions,
3813
-                    implode(", ", $allowed_used_default_where_conditions_values)
3814
-                )
3815
-            );
3816
-        }
3817
-        $universal_query_params = [];
3818
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3819
-            $universal_query_params = $this->_get_default_where_conditions();
3820
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3821
-            $universal_query_params = $this->_get_minimum_where_conditions();
3822
-        }
3823
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3824
-            $related_model = $this->get_related_model_obj($model_name);
3825
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3826
-                $related_model_universal_where_params =
3827
-                    $related_model->_get_default_where_conditions($model_relation_path);
3828
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3829
-                $related_model_universal_where_params =
3830
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3831
-            } else {
3832
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3833
-                continue;
3834
-            }
3835
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3836
-                $related_model_universal_where_params,
3837
-                $where_query_params,
3838
-                $related_model,
3839
-                $model_relation_path
3840
-            );
3841
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3842
-                $universal_query_params,
3843
-                $overrides
3844
-            );
3845
-        }
3846
-        return $universal_query_params;
3847
-    }
3848
-
3849
-
3850
-    /**
3851
-     * Determines whether or not we should use default where conditions for the model in question
3852
-     * (this model, or other related models).
3853
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3854
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3855
-     * We should use default where conditions on related models when they requested to use default where conditions
3856
-     * on all models, or specifically just on other related models
3857
-     *
3858
-     * @param      $default_where_conditions_value
3859
-     * @param bool $for_this_model false means this is for OTHER related models
3860
-     * @return bool
3861
-     */
3862
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3863
-    {
3864
-        return (
3865
-                   $for_this_model
3866
-                   && in_array(
3867
-                       $default_where_conditions_value,
3868
-                       [
3869
-                           EEM_Base::default_where_conditions_all,
3870
-                           EEM_Base::default_where_conditions_this_only,
3871
-                           EEM_Base::default_where_conditions_minimum_others,
3872
-                       ],
3873
-                       true
3874
-                   )
3875
-               )
3876
-               || (
3877
-                   ! $for_this_model
3878
-                   && in_array(
3879
-                       $default_where_conditions_value,
3880
-                       [
3881
-                           EEM_Base::default_where_conditions_all,
3882
-                           EEM_Base::default_where_conditions_others_only,
3883
-                       ],
3884
-                       true
3885
-                   )
3886
-               );
3887
-    }
3888
-
3889
-
3890
-    /**
3891
-     * Determines whether or not we should use default minimum conditions for the model in question
3892
-     * (this model, or other related models).
3893
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3894
-     * where conditions.
3895
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3896
-     * on this model or others
3897
-     *
3898
-     * @param      $default_where_conditions_value
3899
-     * @param bool $for_this_model false means this is for OTHER related models
3900
-     * @return bool
3901
-     */
3902
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3903
-    {
3904
-        return (
3905
-                   $for_this_model
3906
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3907
-               )
3908
-               || (
3909
-                   ! $for_this_model
3910
-                   && in_array(
3911
-                       $default_where_conditions_value,
3912
-                       [
3913
-                           EEM_Base::default_where_conditions_minimum_others,
3914
-                           EEM_Base::default_where_conditions_minimum_all,
3915
-                       ],
3916
-                       true
3917
-                   )
3918
-               );
3919
-    }
3920
-
3921
-
3922
-    /**
3923
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3924
-     * then we also add a special where condition which allows for that model's primary key
3925
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3926
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3927
-     *
3928
-     * @param array    $default_where_conditions
3929
-     * @param array    $provided_where_conditions
3930
-     * @param EEM_Base $model
3931
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3932
-     * @return array @see
3933
-     *                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3934
-     * @throws EE_Error
3935
-     */
3936
-    private function _override_defaults_or_make_null_friendly(
3937
-        $default_where_conditions,
3938
-        $provided_where_conditions,
3939
-        $model,
3940
-        $model_relation_path
3941
-    ) {
3942
-        $null_friendly_where_conditions = [];
3943
-        $none_overridden                = true;
3944
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3945
-        foreach ($default_where_conditions as $key => $val) {
3946
-            if (isset($provided_where_conditions[ $key ])) {
3947
-                $none_overridden = false;
3948
-            } else {
3949
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3950
-            }
3951
-        }
3952
-        if ($none_overridden && $default_where_conditions) {
3953
-            if ($model->has_primary_key_field()) {
3954
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3955
-                                                                                   . "."
3956
-                                                                                   . $model->primary_key_name() ] =
3957
-                    ['IS NULL'];
3958
-            }/*else{
2637
+			$this->_show_next_x_db_queries--;
2638
+		}
2639
+	}
2640
+
2641
+
2642
+	/**
2643
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2644
+	 * There are the 3 cases:
2645
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2646
+	 * $otherModelObject has no ID, it is first saved.
2647
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2648
+	 * has no ID, it is first saved.
2649
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2650
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2651
+	 * join table
2652
+	 *
2653
+	 * @param EE_Base_Class|int $id_or_obj                        EE_base_Class or ID of $thisModelObject
2654
+	 * @param EE_Base_Class|int $other_model_id_or_obj            EE_base_Class or ID of other Model Object
2655
+	 * @param string            $relationName                     , key in EEM_Base::_relations
2656
+	 *                                                            an attendee to a group, you also want to specify
2657
+	 *                                                            which role they will have in that group. So you would
2658
+	 *                                                            use this parameter to specify
2659
+	 *                                                            array('role-column-name'=>'role-id')
2660
+	 * @param array|null        $extra_join_model_fields_n_values This allows you to enter further query params for the
2661
+	 *                                                            relation to for relation to methods that allow you to
2662
+	 *                                                            further specify extra columns to join by (such as
2663
+	 *                                                            HABTM).  Keep in mind that the only acceptable
2664
+	 *                                                            query_params is strict "col" => "value" pairs because
2665
+	 *                                                            these will be inserted in any new rows created as
2666
+	 *                                                            well.
2667
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2668
+	 * @throws EE_Error
2669
+	 */
2670
+	public function add_relationship_to(
2671
+		$id_or_obj,
2672
+		$other_model_id_or_obj,
2673
+		$relationName,
2674
+		$extra_join_model_fields_n_values = []
2675
+	) {
2676
+		$relation_obj = $this->related_settings_for($relationName);
2677
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2678
+	}
2679
+
2680
+
2681
+	/**
2682
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2683
+	 * There are the 3 cases:
2684
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2685
+	 * error
2686
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2687
+	 * an error
2688
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2689
+	 *
2690
+	 * @param EE_Base_Class|int $id_or_obj             EE_base_Class or ID of $thisModelObject
2691
+	 * @param EE_Base_Class|int $other_model_id_or_obj EE_base_Class or ID of other Model Object
2692
+	 * @param string            $relationName          key in EEM_Base::_relations
2693
+	 * @param array|null        $where_query           This allows you to enter further query params for the relation
2694
+	 *                                                 to for relation to methods that allow you to further specify
2695
+	 *                                                 extra columns to join by (such as HABTM). Keep in mind that the
2696
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2697
+	 *                                                 because these will be inserted in any new rows created as well.
2698
+	 * @return EE_Base_Class
2699
+	 * @throws EE_Error
2700
+	 */
2701
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2702
+	{
2703
+		$relation_obj = $this->related_settings_for($relationName);
2704
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2705
+	}
2706
+
2707
+
2708
+	/**
2709
+	 * @param mixed       $id_or_obj
2710
+	 * @param string      $relationName
2711
+	 * @param array|null  $where_query_params
2712
+	 * @return EE_Base_Class[]
2713
+	 * @throws EE_Error
2714
+	 * @throws ReflectionException
2715
+	 */
2716
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2717
+	{
2718
+		$relation_obj = $this->related_settings_for($relationName);
2719
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2720
+	}
2721
+
2722
+
2723
+	/**
2724
+	 * Gets all the related items of the specified $model_name, using $query_params.
2725
+	 * Note: by default, we remove the "default query params"
2726
+	 * because we want to get even deleted items etc.
2727
+	 *
2728
+	 * @param mixed       $id_or_obj    EE_Base_Class child or its ID
2729
+	 * @param string      $model_name   like 'Event', 'Registration', etc. always singular
2730
+	 * @param array|null  $query_params @see
2731
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2732
+	 * @return EE_Base_Class[]
2733
+	 * @throws EE_Error
2734
+	 * @throws ReflectionException
2735
+	 */
2736
+	public function get_all_related($id_or_obj, $model_name, ?array $query_params = [])
2737
+	{
2738
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2739
+		$relation_settings = $this->related_settings_for($model_name);
2740
+		return $relation_settings->get_all_related($model_obj, $query_params);
2741
+	}
2742
+
2743
+
2744
+	/**
2745
+	 * Deletes all the model objects across the relation indicated by $model_name
2746
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2747
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2748
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2749
+	 *
2750
+	 * @param EE_Base_Class|int|string $id_or_obj
2751
+	 * @param string                   $model_name
2752
+	 * @param array|null               $query_params
2753
+	 * @return int how many deleted
2754
+	 * @throws EE_Error
2755
+	 * @throws ReflectionException
2756
+	 */
2757
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2758
+	{
2759
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2760
+		$relation_settings = $this->related_settings_for($model_name);
2761
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2762
+	}
2763
+
2764
+
2765
+	/**
2766
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2767
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2768
+	 * the model objects can't be hard deleted because of blocking related model objects,
2769
+	 * just does a soft-delete on them instead.
2770
+	 *
2771
+	 * @param EE_Base_Class|int|string $id_or_obj
2772
+	 * @param string                   $model_name
2773
+	 * @param array|null               $query_params
2774
+	 * @return int how many deleted
2775
+	 * @throws EE_Error
2776
+	 * @throws ReflectionException
2777
+	 */
2778
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2779
+	{
2780
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2781
+		$relation_settings = $this->related_settings_for($model_name);
2782
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2783
+	}
2784
+
2785
+
2786
+	/**
2787
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2788
+	 * unless otherwise specified in the $query_params
2789
+	 *
2790
+	 * @param EE_Base_Class|int|string $id_or_obj
2791
+	 * @param string                   $model_name     like 'Event', or 'Registration'
2792
+	 * @param array|null               $query_params   @see
2793
+	 *                                                 https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2794
+	 * @param string                   $field_to_count name of field to count by. By default, uses primary key
2795
+	 * @param bool                     $distinct       if we want to only count the distinct values for the column then
2796
+	 *                                                 you can trigger that by the setting $distinct to TRUE;
2797
+	 * @return int
2798
+	 * @throws EE_Error
2799
+	 * @throws ReflectionException
2800
+	 */
2801
+	public function count_related(
2802
+		$id_or_obj,
2803
+		$model_name,
2804
+		$query_params = [],
2805
+		$field_to_count = null,
2806
+		$distinct = false
2807
+	) {
2808
+		$related_model = $this->get_related_model_obj($model_name);
2809
+		// we're just going to use the query params on the related model's normal get_all query,
2810
+		// except add a condition to say to match the current mod
2811
+		if (! isset($query_params['default_where_conditions'])) {
2812
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2813
+		}
2814
+		$this_model_name                                                 = $this->get_this_model_name();
2815
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2816
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2817
+		return $related_model->count($query_params, $field_to_count, $distinct);
2818
+	}
2819
+
2820
+
2821
+	/**
2822
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2823
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2824
+	 *
2825
+	 * @param EE_Base_Class|int|string $id_or_obj
2826
+	 * @param string                   $model_name   like 'Event', or 'Registration'
2827
+	 * @param array|null               $query_params @see
2828
+	 *                                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2829
+	 * @param string                   $field_to_sum name of field to count by. By default, uses primary key
2830
+	 * @return float
2831
+	 * @throws EE_Error
2832
+	 * @throws ReflectionException
2833
+	 */
2834
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2835
+	{
2836
+		$related_model = $this->get_related_model_obj($model_name);
2837
+		if (! is_array($query_params)) {
2838
+			EE_Error::doing_it_wrong(
2839
+				'EEM_Base::sum_related',
2840
+				sprintf(
2841
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2842
+					gettype($query_params)
2843
+				),
2844
+				'4.6.0'
2845
+			);
2846
+			$query_params = [];
2847
+		}
2848
+		// we're just going to use the query params on the related model's normal get_all query,
2849
+		// except add a condition to say to match the current mod
2850
+		if (! isset($query_params['default_where_conditions'])) {
2851
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2852
+		}
2853
+		$this_model_name                                                 = $this->get_this_model_name();
2854
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2855
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2856
+		return $related_model->sum($query_params, $field_to_sum);
2857
+	}
2858
+
2859
+
2860
+	/**
2861
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2862
+	 * $modelObject
2863
+	 *
2864
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2865
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2866
+	 * @param array|null          $query_params     @see
2867
+	 *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2868
+	 * @return EE_Base_Class
2869
+	 * @throws EE_Error
2870
+	 * @throws ReflectionException
2871
+	 */
2872
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2873
+	{
2874
+		$query_params['limit'] = 1;
2875
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2876
+		if ($results) {
2877
+			return array_shift($results);
2878
+		}
2879
+		return null;
2880
+	}
2881
+
2882
+
2883
+	/**
2884
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2885
+	 *
2886
+	 * @return string
2887
+	 */
2888
+	public function get_this_model_name()
2889
+	{
2890
+		return str_replace("EEM_", "", get_class($this));
2891
+	}
2892
+
2893
+
2894
+	/**
2895
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2896
+	 *
2897
+	 * @return EE_Any_Foreign_Model_Name_Field
2898
+	 * @throws EE_Error
2899
+	 */
2900
+	public function get_field_containing_related_model_name()
2901
+	{
2902
+		foreach ($this->field_settings(true) as $field) {
2903
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2904
+				$field_with_model_name = $field;
2905
+			}
2906
+		}
2907
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2908
+			throw new EE_Error(
2909
+				sprintf(
2910
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2911
+					$this->get_this_model_name()
2912
+				)
2913
+			);
2914
+		}
2915
+		return $field_with_model_name;
2916
+	}
2917
+
2918
+
2919
+	/**
2920
+	 * Inserts a new entry into the database, for each table.
2921
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2922
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2923
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2924
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2925
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2926
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2927
+	 *
2928
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2929
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2930
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2931
+	 *                              of EEM_Base)
2932
+	 * @return int|string new primary key on main table that got inserted
2933
+	 * @throws EE_Error
2934
+	 * @throws ReflectionException
2935
+	 */
2936
+	public function insert($field_n_values)
2937
+	{
2938
+		/**
2939
+		 * Filters the fields and their values before inserting an item using the models
2940
+		 *
2941
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2942
+		 * @param EEM_Base $model           the model used
2943
+		 */
2944
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2945
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2946
+			$main_table = $this->_get_main_table();
2947
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2948
+			if ($new_id !== false) {
2949
+				foreach ($this->_get_other_tables() as $other_table) {
2950
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2951
+				}
2952
+			}
2953
+			/**
2954
+			 * Done just after attempting to insert a new model object
2955
+			 *
2956
+			 * @param EEM_Base $model           used
2957
+			 * @param array    $fields_n_values fields and their values
2958
+			 * @param int|string the              ID of the newly-inserted model object
2959
+			 */
2960
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2961
+			return $new_id;
2962
+		}
2963
+		return false;
2964
+	}
2965
+
2966
+
2967
+	/**
2968
+	 * Checks that the result would satisfy the unique indexes on this model
2969
+	 *
2970
+	 * @param array  $field_n_values
2971
+	 * @param string $action
2972
+	 * @return boolean
2973
+	 * @throws EE_Error
2974
+	 * @throws ReflectionException
2975
+	 */
2976
+	protected function _satisfies_unique_indexes(array $field_n_values, $action = 'insert')
2977
+	{
2978
+		foreach ($this->unique_indexes() as $index_name => $index) {
2979
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2980
+			if ($this->exists([$uniqueness_where_params])) {
2981
+				EE_Error::add_error(
2982
+					sprintf(
2983
+						esc_html__(
2984
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2985
+							"event_espresso"
2986
+						),
2987
+						$action,
2988
+						$this->_get_class_name(),
2989
+						$index_name,
2990
+						implode(",", $index->field_names()),
2991
+						http_build_query($uniqueness_where_params)
2992
+					),
2993
+					__FILE__,
2994
+					__FUNCTION__,
2995
+					__LINE__
2996
+				);
2997
+				return false;
2998
+			}
2999
+		}
3000
+		return true;
3001
+	}
3002
+
3003
+
3004
+	/**
3005
+	 * Checks the database for an item that conflicts (ie, if this item were
3006
+	 * saved to the DB would break some uniqueness requirement, like a primary key
3007
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
3008
+	 * can be either an EE_Base_Class or an array of fields n values
3009
+	 *
3010
+	 * @param EE_Base_Class|array $obj_or_fields_array
3011
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
3012
+	 *                                                 when looking for conflicts
3013
+	 *                                                 (ie, if false, we ignore the model object's primary key
3014
+	 *                                                 when finding "conflicts". If true, it's also considered).
3015
+	 *                                                 Only works for INT primary key,
3016
+	 *                                                 STRING primary keys cannot be ignored
3017
+	 * @return EE_Base_Class|array
3018
+	 * @throws EE_Error
3019
+	 * @throws ReflectionException
3020
+	 */
3021
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
3022
+	{
3023
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
3024
+			$fields_n_values = $obj_or_fields_array->model_field_array();
3025
+		} elseif (is_array($obj_or_fields_array)) {
3026
+			$fields_n_values = $obj_or_fields_array;
3027
+		} else {
3028
+			throw new EE_Error(
3029
+				sprintf(
3030
+					esc_html__(
3031
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
3032
+						"event_espresso"
3033
+					),
3034
+					get_class($this),
3035
+					$obj_or_fields_array
3036
+				)
3037
+			);
3038
+		}
3039
+		$query_params = [];
3040
+		if (
3041
+			$this->has_primary_key_field()
3042
+			&& ($include_primary_key
3043
+				|| $this->get_primary_key_field()
3044
+				   instanceof
3045
+				   EE_Primary_Key_String_Field)
3046
+			&& isset($fields_n_values[ $this->primary_key_name() ])
3047
+		) {
3048
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3049
+		}
3050
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3051
+			$uniqueness_where_params                              =
3052
+				array_intersect_key($fields_n_values, $unique_index->fields());
3053
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3054
+		}
3055
+		// if there is nothing to base this search on, then we shouldn't find anything
3056
+		if (empty($query_params)) {
3057
+			return [];
3058
+		}
3059
+		return $this->get_one($query_params);
3060
+	}
3061
+
3062
+
3063
+	/**
3064
+	 * Like count, but is optimized and returns a boolean instead of an int
3065
+	 *
3066
+	 * @param array $query_params
3067
+	 * @return boolean
3068
+	 * @throws EE_Error
3069
+	 * @throws ReflectionException
3070
+	 */
3071
+	public function exists($query_params)
3072
+	{
3073
+		$query_params['limit'] = 1;
3074
+		return $this->count($query_params) > 0;
3075
+	}
3076
+
3077
+
3078
+	/**
3079
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
3080
+	 *
3081
+	 * @param int|string $id
3082
+	 * @return boolean
3083
+	 * @throws EE_Error
3084
+	 * @throws ReflectionException
3085
+	 */
3086
+	public function exists_by_ID($id)
3087
+	{
3088
+		return $this->exists(
3089
+			[
3090
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3091
+				[
3092
+					$this->primary_key_name() => $id,
3093
+				],
3094
+			]
3095
+		);
3096
+	}
3097
+
3098
+
3099
+	/**
3100
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3101
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3102
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3103
+	 * on the main table)
3104
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3105
+	 * cases where we want to call it directly rather than via insert().
3106
+	 *
3107
+	 * @access   protected
3108
+	 * @param EE_Table_Base $table
3109
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3110
+	 *                                       float
3111
+	 * @param int           $new_id          for now we assume only int keys
3112
+	 * @return int ID of new row inserted, or FALSE on failure
3113
+	 * @throws EE_Error
3114
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3115
+	 */
3116
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3117
+	{
3118
+		global $wpdb;
3119
+		$insertion_col_n_values = [];
3120
+		$format_for_insertion   = [];
3121
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3122
+		foreach ($fields_on_table as $field_obj) {
3123
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3124
+			if ($field_obj->is_auto_increment()) {
3125
+				continue;
3126
+			}
3127
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3128
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3129
+			if ($prepared_value !== null) {
3130
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3131
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3132
+			}
3133
+		}
3134
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3135
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3136
+			// so add the fk to the main table as a column
3137
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3138
+			$format_for_insertion[]                              =
3139
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3140
+		}
3141
+
3142
+		// insert the new entry
3143
+		$result = $this->_do_wpdb_query(
3144
+			'insert',
3145
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3146
+		);
3147
+		if ($result === false) {
3148
+			return false;
3149
+		}
3150
+		// ok, now what do we return for the ID of the newly-inserted thing?
3151
+		if ($this->has_primary_key_field()) {
3152
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3153
+				return $wpdb->insert_id;
3154
+			}
3155
+			// it's not an auto-increment primary key, so
3156
+			// it must have been supplied
3157
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3158
+		}
3159
+		// we can't return a  primary key because there is none. instead return
3160
+		// a unique string indicating this model
3161
+		return $this->get_index_primary_key_string($fields_n_values);
3162
+	}
3163
+
3164
+
3165
+	/**
3166
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3167
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3168
+	 * and there is no default, we pass it along. WPDB will take care of it)
3169
+	 *
3170
+	 * @param EE_Model_Field_Base $field_obj
3171
+	 * @param array               $fields_n_values
3172
+	 * @return mixed string|int|float depending on what the table column will be expecting
3173
+	 * @throws EE_Error
3174
+	 */
3175
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3176
+	{
3177
+		$field_name = $field_obj->get_name();
3178
+		// if this field doesn't allow nullable, don't allow it
3179
+		if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3180
+			$fields_n_values[ $field_name ] = $field_obj->get_default_value();
3181
+		}
3182
+		$unprepared_value = $fields_n_values[ $field_name ] ?? null;
3183
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3184
+	}
3185
+
3186
+
3187
+	/**
3188
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3189
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3190
+	 * the field's prepare_for_set() method.
3191
+	 *
3192
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3193
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3194
+	 *                                   top of file)
3195
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3196
+	 *                                   $value is a custom selection
3197
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3198
+	 */
3199
+	private function _prepare_value_for_use_in_db($value, $field)
3200
+	{
3201
+		if ($field instanceof EE_Model_Field_Base) {
3202
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3203
+			switch ($this->_values_already_prepared_by_model_object) {
3204
+				/** @noinspection PhpMissingBreakStatementInspection */
3205
+				case self::not_prepared_by_model_object:
3206
+					$value = $field->prepare_for_set($value);
3207
+				// purposefully left out "return"
3208
+				// no break
3209
+				case self::prepared_by_model_object:
3210
+					/** @noinspection SuspiciousAssignmentsInspection */
3211
+					$value = $field->prepare_for_use_in_db($value);
3212
+				// no break
3213
+				case self::prepared_for_use_in_db:
3214
+					// leave the value alone
3215
+			}
3216
+			// phpcs:enable
3217
+		}
3218
+		return $value;
3219
+	}
3220
+
3221
+
3222
+	/**
3223
+	 * Returns the main table on this model
3224
+	 *
3225
+	 * @return EE_Primary_Table
3226
+	 * @throws EE_Error
3227
+	 */
3228
+	protected function _get_main_table()
3229
+	{
3230
+		foreach ($this->_tables as $table) {
3231
+			if ($table instanceof EE_Primary_Table) {
3232
+				return $table;
3233
+			}
3234
+		}
3235
+		throw new EE_Error(
3236
+			sprintf(
3237
+				esc_html__(
3238
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3239
+					'event_espresso'
3240
+				),
3241
+				get_class($this)
3242
+			)
3243
+		);
3244
+	}
3245
+
3246
+
3247
+	/**
3248
+	 * table
3249
+	 * returns EE_Primary_Table table name
3250
+	 *
3251
+	 * @return string
3252
+	 * @throws EE_Error
3253
+	 */
3254
+	public function table()
3255
+	{
3256
+		return $this->_get_main_table()->get_table_name();
3257
+	}
3258
+
3259
+
3260
+	/**
3261
+	 * table
3262
+	 * returns first EE_Secondary_Table table name
3263
+	 *
3264
+	 * @return string
3265
+	 */
3266
+	public function second_table()
3267
+	{
3268
+		// grab second table from tables array
3269
+		$second_table = end($this->_tables);
3270
+		return $second_table instanceof EE_Secondary_Table
3271
+			? $second_table->get_table_name()
3272
+			: null;
3273
+	}
3274
+
3275
+
3276
+	/**
3277
+	 * get_table_obj_by_alias
3278
+	 * returns table name given it's alias
3279
+	 *
3280
+	 * @param string $table_alias
3281
+	 * @return EE_Primary_Table | EE_Secondary_Table
3282
+	 */
3283
+	public function get_table_obj_by_alias($table_alias = '')
3284
+	{
3285
+		return $this->_tables[ $table_alias ] ?? null;
3286
+	}
3287
+
3288
+
3289
+	/**
3290
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3291
+	 *
3292
+	 * @return EE_Secondary_Table[]
3293
+	 */
3294
+	protected function _get_other_tables()
3295
+	{
3296
+		$other_tables = [];
3297
+		foreach ($this->_tables as $table_alias => $table) {
3298
+			if ($table instanceof EE_Secondary_Table) {
3299
+				$other_tables[ $table_alias ] = $table;
3300
+			}
3301
+		}
3302
+		return $other_tables;
3303
+	}
3304
+
3305
+
3306
+	/**
3307
+	 * Finds all the fields that correspond to the given table
3308
+	 *
3309
+	 * @param string $table_alias , array key in EEM_Base::_tables
3310
+	 * @return EE_Model_Field_Base[]
3311
+	 */
3312
+	public function _get_fields_for_table($table_alias)
3313
+	{
3314
+		return $this->_fields[ $table_alias ];
3315
+	}
3316
+
3317
+
3318
+	/**
3319
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3320
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3321
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3322
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3323
+	 * related Registration, Transaction, and Payment models.
3324
+	 *
3325
+	 * @param array $query_params @see
3326
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3327
+	 * @return EE_Model_Query_Info_Carrier
3328
+	 * @throws EE_Error
3329
+	 */
3330
+	public function _extract_related_models_from_query($query_params)
3331
+	{
3332
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3333
+		if (array_key_exists(0, $query_params)) {
3334
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3335
+		}
3336
+		if (array_key_exists('group_by', $query_params)) {
3337
+			if (is_array($query_params['group_by'])) {
3338
+				$this->_extract_related_models_from_sub_params_array_values(
3339
+					$query_params['group_by'],
3340
+					$query_info_carrier,
3341
+					'group_by'
3342
+				);
3343
+			} elseif (! empty($query_params['group_by'])) {
3344
+				$this->_extract_related_model_info_from_query_param(
3345
+					$query_params['group_by'],
3346
+					$query_info_carrier,
3347
+					'group_by'
3348
+				);
3349
+			}
3350
+		}
3351
+		if (array_key_exists('having', $query_params)) {
3352
+			$this->_extract_related_models_from_sub_params_array_keys(
3353
+				$query_params[0],
3354
+				$query_info_carrier,
3355
+				'having'
3356
+			);
3357
+		}
3358
+		if (array_key_exists('order_by', $query_params)) {
3359
+			if (is_array($query_params['order_by'])) {
3360
+				$this->_extract_related_models_from_sub_params_array_keys(
3361
+					$query_params['order_by'],
3362
+					$query_info_carrier,
3363
+					'order_by'
3364
+				);
3365
+			} elseif (! empty($query_params['order_by'])) {
3366
+				$this->_extract_related_model_info_from_query_param(
3367
+					$query_params['order_by'],
3368
+					$query_info_carrier,
3369
+					'order_by'
3370
+				);
3371
+			}
3372
+		}
3373
+		if (array_key_exists('force_join', $query_params)) {
3374
+			$this->_extract_related_models_from_sub_params_array_values(
3375
+				$query_params['force_join'],
3376
+				$query_info_carrier,
3377
+				'force_join'
3378
+			);
3379
+		}
3380
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3381
+		return $query_info_carrier;
3382
+	}
3383
+
3384
+
3385
+	/**
3386
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3387
+	 *
3388
+	 * @param array                       $sub_query_params
3389
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3390
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3391
+	 * @return EE_Model_Query_Info_Carrier
3392
+	 * @throws EE_Error
3393
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3394
+	 */
3395
+	private function _extract_related_models_from_sub_params_array_keys(
3396
+		$sub_query_params,
3397
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3398
+		$query_param_type
3399
+	) {
3400
+		if (! empty($sub_query_params)) {
3401
+			$sub_query_params = (array) $sub_query_params;
3402
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3403
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3404
+				$this->_extract_related_model_info_from_query_param(
3405
+					$param,
3406
+					$model_query_info_carrier,
3407
+					$query_param_type
3408
+				);
3409
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3410
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3411
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3412
+				// of array('Registration.TXN_ID'=>23)
3413
+				$query_param_sans_stars =
3414
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3415
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3416
+					if (! is_array($possibly_array_of_params)) {
3417
+						throw new EE_Error(
3418
+							sprintf(
3419
+								esc_html__(
3420
+									"You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3421
+									"event_espresso"
3422
+								),
3423
+								$param,
3424
+								$possibly_array_of_params
3425
+							)
3426
+						);
3427
+					}
3428
+					$this->_extract_related_models_from_sub_params_array_keys(
3429
+						$possibly_array_of_params,
3430
+						$model_query_info_carrier,
3431
+						$query_param_type
3432
+					);
3433
+				} elseif (
3434
+					$query_param_type === 0 // ie WHERE
3435
+					&& is_array($possibly_array_of_params) // need is_array() check so we don't try to explode a string
3436
+					&& isset($possibly_array_of_params[2])
3437
+					&& $possibly_array_of_params[2]
3438
+				) {
3439
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3440
+					// indicating that $possible_array_of_params[1] is actually a field name,
3441
+					// from which we should extract query parameters!
3442
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3443
+						throw new EE_Error(
3444
+							sprintf(
3445
+								esc_html__(
3446
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3447
+									"event_espresso"
3448
+								),
3449
+								$query_param_type,
3450
+								implode(",", $possibly_array_of_params)
3451
+							)
3452
+						);
3453
+					}
3454
+					$this->_extract_related_model_info_from_query_param(
3455
+						$possibly_array_of_params[1],
3456
+						$model_query_info_carrier,
3457
+						$query_param_type
3458
+					);
3459
+				}
3460
+			}
3461
+		}
3462
+		return $model_query_info_carrier;
3463
+	}
3464
+
3465
+
3466
+	/**
3467
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3468
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3469
+	 *
3470
+	 * @param array                       $sub_query_params @see
3471
+	 *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3472
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3473
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3474
+	 * @return EE_Model_Query_Info_Carrier
3475
+	 * @throws EE_Error
3476
+	 */
3477
+	private function _extract_related_models_from_sub_params_array_values(
3478
+		$sub_query_params,
3479
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3480
+		$query_param_type
3481
+	) {
3482
+		if (! empty($sub_query_params)) {
3483
+			if (! is_array($sub_query_params)) {
3484
+				throw new EE_Error(
3485
+					sprintf(
3486
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3487
+						$sub_query_params
3488
+					)
3489
+				);
3490
+			}
3491
+			foreach ($sub_query_params as $param) {
3492
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3493
+				$this->_extract_related_model_info_from_query_param(
3494
+					$param,
3495
+					$model_query_info_carrier,
3496
+					$query_param_type
3497
+				);
3498
+			}
3499
+		}
3500
+		return $model_query_info_carrier;
3501
+	}
3502
+
3503
+
3504
+	/**
3505
+	 * Extract all the query parts from  model query params
3506
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3507
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3508
+	 * but use them in a different order. Eg, we need to know what models we are querying
3509
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3510
+	 * other models before we can finalize the where clause SQL.
3511
+	 *
3512
+	 * @param array $query_params
3513
+	 * @return EE_Model_Query_Info_Carrier
3514
+	 * @throws EE_Error
3515
+	 * @throws ModelConfigurationException
3516
+	 * @throws ReflectionException
3517
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3518
+	 */
3519
+	public function _create_model_query_info_carrier($query_params)
3520
+	{
3521
+		if (! is_array($query_params)) {
3522
+			EE_Error::doing_it_wrong(
3523
+				'EEM_Base::_create_model_query_info_carrier',
3524
+				sprintf(
3525
+					esc_html__(
3526
+						'$query_params should be an array, you passed a variable of type %s',
3527
+						'event_espresso'
3528
+					),
3529
+					gettype($query_params)
3530
+				),
3531
+				'4.6.0'
3532
+			);
3533
+			$query_params = [];
3534
+		}
3535
+		$query_params[0] = $query_params[0] ?? [];
3536
+		// first check if we should alter the query to account for caps or not
3537
+		// because the caps might require us to do extra joins
3538
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3539
+			$query_params[0] = array_replace_recursive(
3540
+				$query_params[0],
3541
+				$this->caps_where_conditions($query_params['caps'])
3542
+			);
3543
+		}
3544
+
3545
+		// check if we should alter the query to remove data related to protected
3546
+		// custom post types
3547
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3548
+			$where_param_key_for_password = $this->modelChainAndPassword();
3549
+			// only include if related to a cpt where no password has been set
3550
+			$query_params[0]['OR*nopassword'] = [
3551
+				$where_param_key_for_password       => '',
3552
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3553
+			];
3554
+		}
3555
+		$query_object = $this->_extract_related_models_from_query($query_params);
3556
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3557
+		foreach ($query_params[0] as $key => $value) {
3558
+			if (is_int($key)) {
3559
+				throw new EE_Error(
3560
+					sprintf(
3561
+						esc_html__(
3562
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3563
+							"event_espresso"
3564
+						),
3565
+						$key,
3566
+						var_export($value, true),
3567
+						var_export($query_params, true),
3568
+						get_class($this)
3569
+					)
3570
+				);
3571
+			}
3572
+		}
3573
+		if (
3574
+			array_key_exists('default_where_conditions', $query_params)
3575
+			&& ! empty($query_params['default_where_conditions'])
3576
+		) {
3577
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3578
+		} else {
3579
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3580
+		}
3581
+		$query_params[0] = array_merge(
3582
+			$this->_get_default_where_conditions_for_models_in_query(
3583
+				$query_object,
3584
+				$use_default_where_conditions,
3585
+				$query_params[0]
3586
+			),
3587
+			$query_params[0]
3588
+		);
3589
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3590
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3591
+		// So we need to setup a subquery and use that for the main join.
3592
+		// Note for now this only works on the primary table for the model.
3593
+		// So for instance, you could set the limit array like this:
3594
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3595
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3596
+			$query_object->set_main_model_join_sql(
3597
+				$this->_construct_limit_join_select(
3598
+					$query_params['on_join_limit'][0],
3599
+					$query_params['on_join_limit'][1]
3600
+				)
3601
+			);
3602
+		}
3603
+		// set limit
3604
+		if (array_key_exists('limit', $query_params)) {
3605
+			if (is_array($query_params['limit'])) {
3606
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3607
+					$e = sprintf(
3608
+						esc_html__(
3609
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3610
+							"event_espresso"
3611
+						),
3612
+						http_build_query($query_params['limit'])
3613
+					);
3614
+					throw new EE_Error($e . "|" . $e);
3615
+				}
3616
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3617
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3618
+			} elseif (! empty($query_params['limit'])) {
3619
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3620
+			}
3621
+		}
3622
+		// set order by
3623
+		if (array_key_exists('order_by', $query_params)) {
3624
+			if (is_array($query_params['order_by'])) {
3625
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3626
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3627
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3628
+				if (array_key_exists('order', $query_params)) {
3629
+					throw new EE_Error(
3630
+						sprintf(
3631
+							esc_html__(
3632
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3633
+								"event_espresso"
3634
+							),
3635
+							get_class($this),
3636
+							implode(", ", array_keys($query_params['order_by'])),
3637
+							implode(", ", $query_params['order_by']),
3638
+							$query_params['order']
3639
+						)
3640
+					);
3641
+				}
3642
+				$this->_extract_related_models_from_sub_params_array_keys(
3643
+					$query_params['order_by'],
3644
+					$query_object,
3645
+					'order_by'
3646
+				);
3647
+				// assume it's an array of fields to order by
3648
+				$order_array = [];
3649
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3650
+					$order         = $this->_extract_order($order);
3651
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3652
+				}
3653
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3654
+			} elseif (! empty($query_params['order_by'])) {
3655
+				$this->_extract_related_model_info_from_query_param(
3656
+					$query_params['order_by'],
3657
+					$query_object,
3658
+					'order',
3659
+					$query_params['order_by']
3660
+				);
3661
+				$order = isset($query_params['order'])
3662
+					? $this->_extract_order($query_params['order'])
3663
+					: 'DESC';
3664
+				$query_object->set_order_by_sql(
3665
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3666
+				);
3667
+			}
3668
+		}
3669
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3670
+		if (
3671
+			! array_key_exists('order_by', $query_params)
3672
+			&& array_key_exists('order', $query_params)
3673
+			&& ! empty($query_params['order'])
3674
+		) {
3675
+			$pk_field = $this->get_primary_key_field();
3676
+			$order    = $this->_extract_order($query_params['order']);
3677
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3678
+		}
3679
+		// set group by
3680
+		if (array_key_exists('group_by', $query_params)) {
3681
+			if (is_array($query_params['group_by'])) {
3682
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3683
+				$group_by_array = [];
3684
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3685
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3686
+				}
3687
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3688
+			} elseif (! empty($query_params['group_by'])) {
3689
+				$query_object->set_group_by_sql(
3690
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3691
+				);
3692
+			}
3693
+		}
3694
+		// set having
3695
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3696
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3697
+		}
3698
+		// now, just verify they didn't pass anything wack
3699
+		foreach ($query_params as $query_key => $query_value) {
3700
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3701
+				throw new EE_Error(
3702
+					sprintf(
3703
+						esc_html__(
3704
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3705
+							'event_espresso'
3706
+						),
3707
+						$query_key,
3708
+						get_class($this),
3709
+						//                      print_r( $this->_allowed_query_params, TRUE )
3710
+						implode(',', $this->_allowed_query_params)
3711
+					)
3712
+				);
3713
+			}
3714
+		}
3715
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3716
+		if (empty($main_model_join_sql)) {
3717
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3718
+		}
3719
+		return $query_object;
3720
+	}
3721
+
3722
+
3723
+	/**
3724
+	 * Gets the where conditions that should be imposed on the query based on the
3725
+	 * context (eg reading frontend, backend, edit or delete).
3726
+	 *
3727
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3728
+	 * @return array @see
3729
+	 *                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3730
+	 * @throws EE_Error
3731
+	 */
3732
+	public function caps_where_conditions($context = self::caps_read)
3733
+	{
3734
+		EEM_Base::verify_is_valid_cap_context($context);
3735
+		$cap_where_conditions = [];
3736
+		$cap_restrictions     = $this->caps_missing($context);
3737
+		foreach ($cap_restrictions as $restriction_if_no_cap) {
3738
+			$cap_where_conditions = array_replace_recursive(
3739
+				$cap_where_conditions,
3740
+				$restriction_if_no_cap->get_default_where_conditions()
3741
+			);
3742
+		}
3743
+		return apply_filters(
3744
+			'FHEE__EEM_Base__caps_where_conditions__return',
3745
+			$cap_where_conditions,
3746
+			$this,
3747
+			$context,
3748
+			$cap_restrictions
3749
+		);
3750
+	}
3751
+
3752
+
3753
+	/**
3754
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3755
+	 * otherwise throws an exception
3756
+	 *
3757
+	 * @param string $should_be_order_string
3758
+	 * @return string either ASC, asc, DESC or desc
3759
+	 * @throws EE_Error
3760
+	 */
3761
+	private function _extract_order($should_be_order_string)
3762
+	{
3763
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3764
+			return $should_be_order_string;
3765
+		}
3766
+		throw new EE_Error(
3767
+			sprintf(
3768
+				esc_html__(
3769
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3770
+					"event_espresso"
3771
+				),
3772
+				get_class($this),
3773
+				$should_be_order_string
3774
+			)
3775
+		);
3776
+	}
3777
+
3778
+
3779
+	/**
3780
+	 * Looks at all the models which are included in this query, and asks each
3781
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3782
+	 * so they can be merged
3783
+	 *
3784
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3785
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3786
+	 *                                                                  'none' means NO default where conditions will
3787
+	 *                                                                  be used AT ALL during this query.
3788
+	 *                                                                  'other_models_only' means default where
3789
+	 *                                                                  conditions from other models will be used, but
3790
+	 *                                                                  not for this primary model. 'all', the default,
3791
+	 *                                                                  means default where conditions will apply as
3792
+	 *                                                                  normal
3793
+	 * @param array                       $where_query_params
3794
+	 * @return array
3795
+	 * @throws EE_Error
3796
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params
3797
+	 *                                                                  .md#0-where-conditions
3798
+	 */
3799
+	private function _get_default_where_conditions_for_models_in_query(
3800
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3801
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3802
+		$where_query_params = []
3803
+	) {
3804
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3805
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3806
+			throw new EE_Error(
3807
+				sprintf(
3808
+					esc_html__(
3809
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3810
+						"event_espresso"
3811
+					),
3812
+					$use_default_where_conditions,
3813
+					implode(", ", $allowed_used_default_where_conditions_values)
3814
+				)
3815
+			);
3816
+		}
3817
+		$universal_query_params = [];
3818
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3819
+			$universal_query_params = $this->_get_default_where_conditions();
3820
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3821
+			$universal_query_params = $this->_get_minimum_where_conditions();
3822
+		}
3823
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3824
+			$related_model = $this->get_related_model_obj($model_name);
3825
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3826
+				$related_model_universal_where_params =
3827
+					$related_model->_get_default_where_conditions($model_relation_path);
3828
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3829
+				$related_model_universal_where_params =
3830
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3831
+			} else {
3832
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3833
+				continue;
3834
+			}
3835
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3836
+				$related_model_universal_where_params,
3837
+				$where_query_params,
3838
+				$related_model,
3839
+				$model_relation_path
3840
+			);
3841
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3842
+				$universal_query_params,
3843
+				$overrides
3844
+			);
3845
+		}
3846
+		return $universal_query_params;
3847
+	}
3848
+
3849
+
3850
+	/**
3851
+	 * Determines whether or not we should use default where conditions for the model in question
3852
+	 * (this model, or other related models).
3853
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3854
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3855
+	 * We should use default where conditions on related models when they requested to use default where conditions
3856
+	 * on all models, or specifically just on other related models
3857
+	 *
3858
+	 * @param      $default_where_conditions_value
3859
+	 * @param bool $for_this_model false means this is for OTHER related models
3860
+	 * @return bool
3861
+	 */
3862
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3863
+	{
3864
+		return (
3865
+				   $for_this_model
3866
+				   && in_array(
3867
+					   $default_where_conditions_value,
3868
+					   [
3869
+						   EEM_Base::default_where_conditions_all,
3870
+						   EEM_Base::default_where_conditions_this_only,
3871
+						   EEM_Base::default_where_conditions_minimum_others,
3872
+					   ],
3873
+					   true
3874
+				   )
3875
+			   )
3876
+			   || (
3877
+				   ! $for_this_model
3878
+				   && in_array(
3879
+					   $default_where_conditions_value,
3880
+					   [
3881
+						   EEM_Base::default_where_conditions_all,
3882
+						   EEM_Base::default_where_conditions_others_only,
3883
+					   ],
3884
+					   true
3885
+				   )
3886
+			   );
3887
+	}
3888
+
3889
+
3890
+	/**
3891
+	 * Determines whether or not we should use default minimum conditions for the model in question
3892
+	 * (this model, or other related models).
3893
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3894
+	 * where conditions.
3895
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3896
+	 * on this model or others
3897
+	 *
3898
+	 * @param      $default_where_conditions_value
3899
+	 * @param bool $for_this_model false means this is for OTHER related models
3900
+	 * @return bool
3901
+	 */
3902
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3903
+	{
3904
+		return (
3905
+				   $for_this_model
3906
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3907
+			   )
3908
+			   || (
3909
+				   ! $for_this_model
3910
+				   && in_array(
3911
+					   $default_where_conditions_value,
3912
+					   [
3913
+						   EEM_Base::default_where_conditions_minimum_others,
3914
+						   EEM_Base::default_where_conditions_minimum_all,
3915
+					   ],
3916
+					   true
3917
+				   )
3918
+			   );
3919
+	}
3920
+
3921
+
3922
+	/**
3923
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3924
+	 * then we also add a special where condition which allows for that model's primary key
3925
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3926
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3927
+	 *
3928
+	 * @param array    $default_where_conditions
3929
+	 * @param array    $provided_where_conditions
3930
+	 * @param EEM_Base $model
3931
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3932
+	 * @return array @see
3933
+	 *                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3934
+	 * @throws EE_Error
3935
+	 */
3936
+	private function _override_defaults_or_make_null_friendly(
3937
+		$default_where_conditions,
3938
+		$provided_where_conditions,
3939
+		$model,
3940
+		$model_relation_path
3941
+	) {
3942
+		$null_friendly_where_conditions = [];
3943
+		$none_overridden                = true;
3944
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3945
+		foreach ($default_where_conditions as $key => $val) {
3946
+			if (isset($provided_where_conditions[ $key ])) {
3947
+				$none_overridden = false;
3948
+			} else {
3949
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3950
+			}
3951
+		}
3952
+		if ($none_overridden && $default_where_conditions) {
3953
+			if ($model->has_primary_key_field()) {
3954
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3955
+																				   . "."
3956
+																				   . $model->primary_key_name() ] =
3957
+					['IS NULL'];
3958
+			}/*else{
3959 3959
                 //@todo NO PK, use other defaults
3960 3960
             }*/
3961
-        }
3962
-        return $null_friendly_where_conditions;
3963
-    }
3964
-
3965
-
3966
-    /**
3967
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3968
-     * default where conditions on all get_all, update, and delete queries done by this model.
3969
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3970
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3971
-     *
3972
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3973
-     * @return array @see
3974
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3975
-     * @throws EE_Error
3976
-     * @throws EE_Error
3977
-     */
3978
-    private function _get_default_where_conditions($model_relation_path = '')
3979
-    {
3980
-        if ($this->_ignore_where_strategy) {
3981
-            return [];
3982
-        }
3983
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3984
-    }
3985
-
3986
-
3987
-    /**
3988
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3989
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3990
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3991
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3992
-     * Similar to _get_default_where_conditions
3993
-     *
3994
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3995
-     * @return array @see
3996
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3997
-     * @throws EE_Error
3998
-     * @throws EE_Error
3999
-     */
4000
-    protected function _get_minimum_where_conditions($model_relation_path = '')
4001
-    {
4002
-        if ($this->_ignore_where_strategy) {
4003
-            return [];
4004
-        }
4005
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
4006
-    }
4007
-
4008
-
4009
-    /**
4010
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
4011
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
4012
-     *
4013
-     * @param EE_Model_Query_Info_Carrier $model_query_info
4014
-     * @return string
4015
-     * @throws EE_Error
4016
-     */
4017
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
4018
-    {
4019
-        $selects = $this->_get_columns_to_select_for_this_model();
4020
-        foreach (
4021
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
4022
-        ) {
4023
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
4024
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
4025
-            foreach ($other_model_selects as $key => $value) {
4026
-                $selects[] = $value;
4027
-            }
4028
-        }
4029
-        return implode(", ", $selects);
4030
-    }
4031
-
4032
-
4033
-    /**
4034
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
4035
-     * So that's going to be the columns for all the fields on the model
4036
-     *
4037
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
4038
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
4039
-     */
4040
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
4041
-    {
4042
-        $fields                                       = $this->field_settings();
4043
-        $selects                                      = [];
4044
-        $table_alias_with_model_relation_chain_prefix =
4045
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
4046
-                $model_relation_chain,
4047
-                $this->get_this_model_name()
4048
-            );
4049
-        foreach ($fields as $field_obj) {
4050
-            $selects[] = $table_alias_with_model_relation_chain_prefix
4051
-                         . $field_obj->get_table_alias()
4052
-                         . "."
4053
-                         . $field_obj->get_table_column()
4054
-                         . " AS '"
4055
-                         . $table_alias_with_model_relation_chain_prefix
4056
-                         . $field_obj->get_table_alias()
4057
-                         . "."
4058
-                         . $field_obj->get_table_column()
4059
-                         . "'";
4060
-        }
4061
-        // make sure we are also getting the PKs of each table
4062
-        $tables = $this->get_tables();
4063
-        if (count($tables) > 1) {
4064
-            foreach ($tables as $table_obj) {
4065
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4066
-                                       . $table_obj->get_fully_qualified_pk_column();
4067
-                if (! in_array($qualified_pk_column, $selects)) {
4068
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4069
-                }
4070
-            }
4071
-        }
4072
-        return $selects;
4073
-    }
4074
-
4075
-
4076
-    /**
4077
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4078
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4079
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4080
-     * SQL for joining, and the data types
4081
-     *
4082
-     * @param null|string                 $original_query_param
4083
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
4084
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4085
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4086
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4087
-     *                                                          column name. We only want model names, eg 'Event.Venue'
4088
-     *                                                          or 'Registration's
4089
-     * @param string                      $original_query_param what it originally was (eg
4090
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4091
-     *                                                          matches $query_param
4092
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4093
-     * @throws EE_Error
4094
-     */
4095
-    private function _extract_related_model_info_from_query_param(
4096
-        $query_param,
4097
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4098
-        $query_param_type,
4099
-        $original_query_param = null
4100
-    ) {
4101
-        if ($original_query_param === null) {
4102
-            $original_query_param = $query_param;
4103
-        }
4104
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4105
-        // check to see if we have a field on this model
4106
-        $this_model_fields = $this->field_settings(true);
4107
-        if (array_key_exists($query_param, $this_model_fields)) {
4108
-            $field_is_allowed = in_array(
4109
-                $query_param_type,
4110
-                [0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4111
-                true
4112
-            );
4113
-            if ($field_is_allowed) {
4114
-                return;
4115
-            }
4116
-            throw new EE_Error(
4117
-                sprintf(
4118
-                    esc_html__(
4119
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4120
-                        "event_espresso"
4121
-                    ),
4122
-                    $query_param,
4123
-                    get_class($this),
4124
-                    $query_param_type,
4125
-                    $original_query_param
4126
-                )
4127
-            );
4128
-        }
4129
-        // check if this is a special logic query param
4130
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4131
-            $operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4132
-            if ($operator_is_allowed) {
4133
-                return;
4134
-            }
4135
-            throw new EE_Error(
4136
-                sprintf(
4137
-                    esc_html__(
4138
-                        'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4139
-                        'event_espresso'
4140
-                    ),
4141
-                    implode('", "', $this->_logic_query_param_keys),
4142
-                    $query_param,
4143
-                    get_class($this),
4144
-                    '<br />',
4145
-                    "\t"
4146
-                    . ' $passed_in_query_info = <pre>'
4147
-                    . print_r($passed_in_query_info, true)
4148
-                    . '</pre>'
4149
-                    . "\n\t"
4150
-                    . ' $query_param_type = '
4151
-                    . $query_param_type
4152
-                    . "\n\t"
4153
-                    . ' $original_query_param = '
4154
-                    . $original_query_param
4155
-                )
4156
-            );
4157
-        }
4158
-        // check if it's a custom selection
4159
-        if (
4160
-            $this->_custom_selections instanceof CustomSelects
4161
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4162
-        ) {
4163
-            return;
4164
-        }
4165
-        // check if has a model name at the beginning
4166
-        // and
4167
-        // check if it's a field on a related model
4168
-        if (
4169
-            $this->extractJoinModelFromQueryParams(
4170
-                $passed_in_query_info,
4171
-                $query_param,
4172
-                $original_query_param,
4173
-                $query_param_type
4174
-            )
4175
-        ) {
4176
-            return;
4177
-        }
4178
-
4179
-        // ok so $query_param didn't start with a model name
4180
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4181
-        // it's wack, that's what it is
4182
-        throw new EE_Error(
4183
-            sprintf(
4184
-                esc_html__(
4185
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4186
-                    "event_espresso"
4187
-                ),
4188
-                $query_param,
4189
-                get_class($this),
4190
-                $query_param_type,
4191
-                $original_query_param
4192
-            )
4193
-        );
4194
-    }
4195
-
4196
-
4197
-    /**
4198
-     * Extracts any possible join model information from the provided possible_join_string.
4199
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4200
-     * join
4201
-     * parts that should be added to the query.
4202
-     *
4203
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4204
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4205
-     * @param null|string                 $original_query_param
4206
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4207
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4208
-     *                                                           etc.)
4209
-     * @return bool  returns true if a join was added and false if not.
4210
-     * @throws EE_Error
4211
-     */
4212
-    private function extractJoinModelFromQueryParams(
4213
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4214
-        $possible_join_string,
4215
-        $original_query_param,
4216
-        $query_parameter_type
4217
-    ) {
4218
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4219
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4220
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4221
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4222
-                if ($possible_join_string === '') {
4223
-                    // nothing left to $query_param
4224
-                    // we should actually end in a field name, not a model like this!
4225
-                    throw new EE_Error(
4226
-                        sprintf(
4227
-                            esc_html__(
4228
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4229
-                                "event_espresso"
4230
-                            ),
4231
-                            $possible_join_string,
4232
-                            $query_parameter_type,
4233
-                            get_class($this),
4234
-                            $valid_related_model_name
4235
-                        )
4236
-                    );
4237
-                }
4238
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4239
-                $related_model_obj->_extract_related_model_info_from_query_param(
4240
-                    $possible_join_string,
4241
-                    $query_info_carrier,
4242
-                    $query_parameter_type,
4243
-                    $original_query_param
4244
-                );
4245
-                return true;
4246
-            }
4247
-            if ($possible_join_string === $valid_related_model_name) {
4248
-                $this->_add_join_to_model(
4249
-                    $valid_related_model_name,
4250
-                    $query_info_carrier,
4251
-                    $original_query_param
4252
-                );
4253
-                return true;
4254
-            }
4255
-        }
4256
-        return false;
4257
-    }
4258
-
4259
-
4260
-    /**
4261
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4262
-     *
4263
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4264
-     * @throws EE_Error
4265
-     */
4266
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4267
-    {
4268
-        if (
4269
-            $this->_custom_selections instanceof CustomSelects
4270
-            && (
4271
-                $this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4272
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4273
-            )
4274
-        ) {
4275
-            $original_selects = $this->_custom_selections->originalSelects();
4276
-            foreach ($original_selects as $alias => $select_configuration) {
4277
-                $this->extractJoinModelFromQueryParams(
4278
-                    $query_info_carrier,
4279
-                    $select_configuration[0],
4280
-                    $select_configuration[0],
4281
-                    'custom_selects'
4282
-                );
4283
-            }
4284
-        }
4285
-    }
4286
-
4287
-
4288
-    /**
4289
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4290
-     * and store it on $passed_in_query_info
4291
-     *
4292
-     * @param string                      $model_name
4293
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4294
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4295
-     *                                                          model and $model_name. Eg, if we are querying Event,
4296
-     *                                                          and are adding a join to 'Payment' with the original
4297
-     *                                                          query param key
4298
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4299
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4300
-     *                                                          Payment wants to add default query params so that it
4301
-     *                                                          will know what models to prepend onto its default query
4302
-     *                                                          params or in case it wants to rename tables (in case
4303
-     *                                                          there are multiple joins to the same table)
4304
-     * @return void
4305
-     * @throws EE_Error
4306
-     */
4307
-    private function _add_join_to_model(
4308
-        $model_name,
4309
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4310
-        $original_query_param
4311
-    ) {
4312
-        $relation_obj         = $this->related_settings_for($model_name);
4313
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4314
-        // check if the relation is HABTM, because then we're essentially doing two joins
4315
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4316
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4317
-            $join_model_obj = $relation_obj->get_join_model();
4318
-            // replace the model specified with the join model for this relation chain, whi
4319
-            $relation_chain_to_join_model =
4320
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4321
-                    $model_name,
4322
-                    $join_model_obj->get_this_model_name(),
4323
-                    $model_relation_chain
4324
-                );
4325
-            $passed_in_query_info->merge(
4326
-                new EE_Model_Query_Info_Carrier(
4327
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4328
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4329
-                )
4330
-            );
4331
-        }
4332
-        // now just join to the other table pointed to by the relation object, and add its data types
4333
-        $passed_in_query_info->merge(
4334
-            new EE_Model_Query_Info_Carrier(
4335
-                [$model_relation_chain => $model_name],
4336
-                $relation_obj->get_join_statement($model_relation_chain)
4337
-            )
4338
-        );
4339
-    }
4340
-
4341
-
4342
-    /**
4343
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4344
-     *
4345
-     * @param array $where_params @see
4346
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4347
-     * @return string of SQL
4348
-     * @throws EE_Error
4349
-     */
4350
-    private function _construct_where_clause($where_params)
4351
-    {
4352
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4353
-        if ($SQL) {
4354
-            return " WHERE " . $SQL;
4355
-        }
4356
-        return '';
4357
-    }
4358
-
4359
-
4360
-    /**
4361
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4362
-     * and should be passed HAVING parameters, not WHERE parameters
4363
-     *
4364
-     * @param array $having_params
4365
-     * @return string
4366
-     * @throws EE_Error
4367
-     */
4368
-    private function _construct_having_clause($having_params)
4369
-    {
4370
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4371
-        if ($SQL) {
4372
-            return " HAVING " . $SQL;
4373
-        }
4374
-        return '';
4375
-    }
4376
-
4377
-
4378
-    /**
4379
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4380
-     * Event_Meta.meta_value = 'foo'))"
4381
-     *
4382
-     * @param array  $where_params @see
4383
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4384
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4385
-     * @return string of SQL
4386
-     * @throws EE_Error
4387
-     */
4388
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4389
-    {
4390
-        $where_clauses = [];
4391
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4392
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4393
-            if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4394
-                switch ($query_param) {
4395
-                    case 'not':
4396
-                    case 'NOT':
4397
-                        $where_clauses[] = "! ("
4398
-                                           . $this->_construct_condition_clause_recursive(
4399
-                                               $op_and_value_or_sub_condition,
4400
-                                               $glue
4401
-                                           )
4402
-                                           . ")";
4403
-                        break;
4404
-                    case 'and':
4405
-                    case 'AND':
4406
-                        $where_clauses[] = " ("
4407
-                                           . $this->_construct_condition_clause_recursive(
4408
-                                               $op_and_value_or_sub_condition,
4409
-                                               ' AND '
4410
-                                           )
4411
-                                           . ")";
4412
-                        break;
4413
-                    case 'or':
4414
-                    case 'OR':
4415
-                        $where_clauses[] = " ("
4416
-                                           . $this->_construct_condition_clause_recursive(
4417
-                                               $op_and_value_or_sub_condition,
4418
-                                               ' OR '
4419
-                                           )
4420
-                                           . ")";
4421
-                        break;
4422
-                }
4423
-            } else {
4424
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4425
-                // if it's not a normal field, maybe it's a custom selection?
4426
-                if (! $field_obj) {
4427
-                    if ($this->_custom_selections instanceof CustomSelects) {
4428
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4429
-                    } else {
4430
-                        throw new EE_Error(
4431
-                            sprintf(
4432
-                                esc_html__(
4433
-                                    "%s is neither a valid model field name, nor a custom selection",
4434
-                                    "event_espresso"
4435
-                                ),
4436
-                                $query_param
4437
-                            )
4438
-                        );
4439
-                    }
4440
-                }
4441
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4442
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4443
-            }
4444
-        }
4445
-        return $where_clauses
4446
-            ? implode($glue, $where_clauses)
4447
-            : '';
4448
-    }
4449
-
4450
-
4451
-    /**
4452
-     * Takes the input parameter and extract the table name (alias) and column name
4453
-     *
4454
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4455
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4456
-     * @throws EE_Error
4457
-     */
4458
-    private function _deduce_column_name_from_query_param($query_param)
4459
-    {
4460
-        $field = $this->_deduce_field_from_query_param($query_param);
4461
-        if ($field) {
4462
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4463
-                $field->get_model_name(),
4464
-                $query_param
4465
-            );
4466
-            return $table_alias_prefix . $field->get_qualified_column();
4467
-        }
4468
-        if (
4469
-            $this->_custom_selections instanceof CustomSelects
4470
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4471
-        ) {
4472
-            // maybe it's custom selection item?
4473
-            // if so, just use it as the "column name"
4474
-            return $query_param;
4475
-        }
4476
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4477
-            ? implode(',', $this->_custom_selections->columnAliases())
4478
-            : '';
4479
-        throw new EE_Error(
4480
-            sprintf(
4481
-                esc_html__(
4482
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4483
-                    "event_espresso"
4484
-                ),
4485
-                $query_param,
4486
-                $custom_select_aliases
4487
-            )
4488
-        );
4489
-    }
4490
-
4491
-
4492
-    /**
4493
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4494
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4495
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4496
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4497
-     *
4498
-     * @param string $condition_query_param_key
4499
-     * @return string
4500
-     */
4501
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4502
-    {
4503
-        $pos_of_star = strpos($condition_query_param_key, '*');
4504
-        if ($pos_of_star === false) {
4505
-            return $condition_query_param_key;
4506
-        }
4507
-        return substr($condition_query_param_key, 0, $pos_of_star);
4508
-    }
4509
-
4510
-
4511
-    /**
4512
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4513
-     *
4514
-     * @param array|string               $op_and_value
4515
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4516
-     * @return string
4517
-     * @throws EE_Error
4518
-     */
4519
-    private function _construct_op_and_value($op_and_value, $field_obj)
4520
-    {
4521
-        $operator = '=';
4522
-        $value    = $op_and_value;
4523
-        if (is_array($op_and_value)) {
4524
-            $operator = isset($op_and_value[0])
4525
-                ? $this->_prepare_operator_for_sql($op_and_value[0])
4526
-                : null;
4527
-            if (! $operator) {
4528
-                $php_array_like_string = [];
4529
-                foreach ($op_and_value as $key => $value) {
4530
-                    $php_array_like_string[] = "$key=>$value";
4531
-                }
4532
-                throw new EE_Error(
4533
-                    sprintf(
4534
-                        esc_html__(
4535
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4536
-                            "event_espresso"
4537
-                        ),
4538
-                        implode(",", $php_array_like_string)
4539
-                    )
4540
-                );
4541
-            }
4542
-            $value = $op_and_value[1] ?? null;
4543
-        }
4544
-
4545
-        // check to see if the value is actually another field
4546
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4547
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4548
-        }
4549
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4550
-            // in this case, the value should be an array, or at least a comma-separated list
4551
-            // it will need to handle a little differently
4552
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4553
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4554
-            return $operator . SP . $cleaned_value;
4555
-        }
4556
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4557
-            // the value should be an array with count of two.
4558
-            if (count($value) !== 2) {
4559
-                throw new EE_Error(
4560
-                    sprintf(
4561
-                        esc_html__(
4562
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4563
-                            'event_espresso'
4564
-                        ),
4565
-                        "BETWEEN"
4566
-                    )
4567
-                );
4568
-            }
4569
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4570
-            return $operator . SP . $cleaned_value;
4571
-        }
4572
-        if (in_array($operator, $this->valid_null_style_operators())) {
4573
-            if ($value !== null) {
4574
-                throw new EE_Error(
4575
-                    sprintf(
4576
-                        esc_html__(
4577
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4578
-                            "event_espresso"
4579
-                        ),
4580
-                        $value,
4581
-                        $operator
4582
-                    )
4583
-                );
4584
-            }
4585
-            return $operator;
4586
-        }
4587
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4588
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4589
-            // remove other junk. So just treat it as a string.
4590
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4591
-        }
4592
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4593
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4594
-        }
4595
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4596
-            throw new EE_Error(
4597
-                sprintf(
4598
-                    esc_html__(
4599
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4600
-                        'event_espresso'
4601
-                    ),
4602
-                    $operator,
4603
-                    $operator
4604
-                )
4605
-            );
4606
-        }
4607
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4608
-            throw new EE_Error(
4609
-                sprintf(
4610
-                    esc_html__(
4611
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4612
-                        'event_espresso'
4613
-                    ),
4614
-                    $operator,
4615
-                    $operator
4616
-                )
4617
-            );
4618
-        }
4619
-        throw new EE_Error(
4620
-            sprintf(
4621
-                esc_html__(
4622
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4623
-                    "event_espresso"
4624
-                ),
4625
-                http_build_query($op_and_value)
4626
-            )
4627
-        );
4628
-    }
4629
-
4630
-
4631
-    /**
4632
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4633
-     *
4634
-     * @param array                      $values
4635
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4636
-     *                                              '%s'
4637
-     * @return string
4638
-     * @throws EE_Error
4639
-     */
4640
-    public function _construct_between_value($values, $field_obj)
4641
-    {
4642
-        $cleaned_values = [];
4643
-        foreach ($values as $value) {
4644
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4645
-        }
4646
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4647
-    }
4648
-
4649
-
4650
-    /**
4651
-     * Takes an array or a comma-separated list of $values and cleans them
4652
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4653
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4654
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4655
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4656
-     *
4657
-     * @param mixed                      $values    array or comma-separated string
4658
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4659
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4660
-     * @throws EE_Error
4661
-     */
4662
-    public function _construct_in_value($values, $field_obj)
4663
-    {
4664
-        $prepped = [];
4665
-        // check if the value is a CSV list
4666
-        if (is_string($values)) {
4667
-            // in which case, turn it into an array
4668
-            $values = explode(',', $values);
4669
-        }
4670
-        // make sure we only have one of each value in the list
4671
-        $values = array_unique($values);
4672
-        foreach ($values as $value) {
4673
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4674
-        }
4675
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4676
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4677
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4678
-        if (empty($prepped)) {
4679
-            $all_fields  = $this->field_settings();
4680
-            $first_field = reset($all_fields);
4681
-            $main_table  = $this->_get_main_table();
4682
-            $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4683
-        }
4684
-        return '(' . implode(',', $prepped) . ')';
4685
-    }
4686
-
4687
-
4688
-    /**
4689
-     * @param mixed                      $value
4690
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4691
-     * @return false|null|string
4692
-     * @throws EE_Error
4693
-     */
4694
-    private function _wpdb_prepare_using_field($value, $field_obj)
4695
-    {
4696
-        /** @type WPDB $wpdb */
4697
-        global $wpdb;
4698
-        if ($field_obj instanceof EE_Model_Field_Base) {
4699
-            return $wpdb->prepare(
4700
-                $field_obj->get_wpdb_data_type(),
4701
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4702
-            );
4703
-        } //$field_obj should really just be a data type
4704
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4705
-            throw new EE_Error(
4706
-                sprintf(
4707
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4708
-                    $field_obj,
4709
-                    implode(",", $this->_valid_wpdb_data_types)
4710
-                )
4711
-            );
4712
-        }
4713
-        return $wpdb->prepare($field_obj, $value);
4714
-    }
4715
-
4716
-
4717
-    /**
4718
-     * Takes the input parameter and finds the model field that it indicates.
4719
-     *
4720
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4721
-     * @return EE_Model_Field_Base
4722
-     * @throws EE_Error
4723
-     */
4724
-    protected function _deduce_field_from_query_param($query_param_name)
4725
-    {
4726
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4727
-        // which will help us find the database table and column
4728
-        $query_param_parts = explode(".", $query_param_name);
4729
-        if (empty($query_param_parts)) {
4730
-            throw new EE_Error(
4731
-                sprintf(
4732
-                    esc_html__(
4733
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4734
-                        'event_espresso'
4735
-                    ),
4736
-                    $query_param_name
4737
-                )
4738
-            );
4739
-        }
4740
-        $number_of_parts       = count($query_param_parts);
4741
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4742
-        if ($number_of_parts === 1) {
4743
-            $field_name = $last_query_param_part;
4744
-            $model_obj  = $this;
4745
-        } else {// $number_of_parts >= 2
4746
-            // the last part is the column name, and there are only 2parts. therefore...
4747
-            $field_name = $last_query_param_part;
4748
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4749
-        }
4750
-        try {
4751
-            return $model_obj->field_settings_for($field_name);
4752
-        } catch (EE_Error $e) {
4753
-            return null;
4754
-        }
4755
-    }
4756
-
4757
-
4758
-    /**
4759
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4760
-     * alias and column which corresponds to it
4761
-     *
4762
-     * @param string $field_name
4763
-     * @return string
4764
-     * @throws EE_Error
4765
-     */
4766
-    public function _get_qualified_column_for_field($field_name)
4767
-    {
4768
-        $all_fields = $this->field_settings();
4769
-        $field      = $all_fields[ $field_name ] ?? false;
4770
-        if ($field) {
4771
-            return $field->get_qualified_column();
4772
-        }
4773
-        throw new EE_Error(
4774
-            sprintf(
4775
-                esc_html__(
4776
-                    "There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4777
-                    'event_espresso'
4778
-                ),
4779
-                $field_name,
4780
-                get_class($this)
4781
-            )
4782
-        );
4783
-    }
4784
-
4785
-
4786
-    /**
4787
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4788
-     * Example usage:
4789
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4790
-     *      array(),
4791
-     *      ARRAY_A,
4792
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4793
-     *  );
4794
-     * is equivalent to
4795
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4796
-     * and
4797
-     *  EEM_Event::instance()->get_all_wpdb_results(
4798
-     *      array(
4799
-     *          array(
4800
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4801
-     *          ),
4802
-     *          ARRAY_A,
4803
-     *          implode(
4804
-     *              ', ',
4805
-     *              array_merge(
4806
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4807
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4808
-     *              )
4809
-     *          )
4810
-     *      )
4811
-     *  );
4812
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4813
-     *
4814
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4815
-     *                                            and the one whose fields you are selecting for example: when querying
4816
-     *                                            tickets model and selecting fields from the tickets model you would
4817
-     *                                            leave this parameter empty, because no models are needed to join
4818
-     *                                            between the queried model and the selected one. Likewise when
4819
-     *                                            querying the datetime model and selecting fields from the tickets
4820
-     *                                            model, it would also be left empty, because there is a direct
4821
-     *                                            relation from datetimes to tickets, so no model is needed to join
4822
-     *                                            them together. However, when querying from the event model and
4823
-     *                                            selecting fields from the ticket model, you should provide the string
4824
-     *                                            'Datetime', indicating that the event model must first join to the
4825
-     *                                            datetime model in order to find its relation to ticket model.
4826
-     *                                            Also, when querying from the venue model and selecting fields from
4827
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4828
-     *                                            indicating you need to join the venue model to the event model,
4829
-     *                                            to the datetime model, in order to find its relation to the ticket
4830
-     *                                            model. This string is used to deduce the prefix that gets added onto
4831
-     *                                            the models' tables qualified columns
4832
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4833
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4834
-     *                                            qualified column names
4835
-     * @return array|string
4836
-     */
4837
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4838
-    {
4839
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4840
-                ? ''
4841
-                : '__');
4842
-        $qualified_columns = [];
4843
-        foreach ($this->field_settings() as $field_name => $field) {
4844
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4845
-        }
4846
-        return $return_string
4847
-            ? implode(', ', $qualified_columns)
4848
-            : $qualified_columns;
4849
-    }
4850
-
4851
-
4852
-    /**
4853
-     * constructs the select use on special limit joins
4854
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4855
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4856
-     * (as that is typically where the limits would be set).
4857
-     *
4858
-     * @param string       $table_alias The table the select is being built for
4859
-     * @param mixed|string $limit       The limit for this select
4860
-     * @return string                The final select join element for the query.
4861
-     * @throws EE_Error
4862
-     * @throws EE_Error
4863
-     */
4864
-    public function _construct_limit_join_select($table_alias, $limit)
4865
-    {
4866
-        $SQL = '';
4867
-        foreach ($this->_tables as $table_obj) {
4868
-            if ($table_obj instanceof EE_Primary_Table) {
4869
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4870
-                    ? $table_obj->get_select_join_limit($limit)
4871
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4872
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4873
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4874
-                    ? $table_obj->get_select_join_limit_join($limit)
4875
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4876
-            }
4877
-        }
4878
-        return $SQL;
4879
-    }
4880
-
4881
-
4882
-    /**
4883
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4884
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4885
-     *
4886
-     * @return string SQL
4887
-     * @throws EE_Error
4888
-     */
4889
-    public function _construct_internal_join()
4890
-    {
4891
-        $SQL = $this->_get_main_table()->get_table_sql();
4892
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4893
-        return $SQL;
4894
-    }
4895
-
4896
-
4897
-    /**
4898
-     * Constructs the SQL for joining all the tables on this model.
4899
-     * Normally $alias should be the primary table's alias, but in cases where
4900
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4901
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4902
-     * alias, this will construct SQL like:
4903
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4904
-     * With $alias being a secondary table's alias, this will construct SQL like:
4905
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4906
-     *
4907
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4908
-     * @return string
4909
-     * @throws EE_Error
4910
-     * @throws EE_Error
4911
-     */
4912
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4913
-    {
4914
-        $SQL               = '';
4915
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4916
-        foreach ($this->_tables as $table_obj) {
4917
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4918
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4919
-                    // so we're joining to this table, meaning the table is already in
4920
-                    // the FROM statement, BUT the primary table isn't. So we want
4921
-                    // to add the inverse join sql
4922
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4923
-                } else {
4924
-                    // just add a regular JOIN to this table from the primary table
4925
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4926
-                }
4927
-            }// if it's a primary table, dont add any SQL. it should already be in the FROM statement
4928
-        }
4929
-        return $SQL;
4930
-    }
4931
-
4932
-
4933
-    /**
4934
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4935
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4936
-     * their data type (eg, '%s', '%d', etc)
4937
-     *
4938
-     * @return array
4939
-     */
4940
-    public function _get_data_types()
4941
-    {
4942
-        $data_types = [];
4943
-        foreach ($this->field_settings() as $field_obj) {
4944
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4945
-            /** @var $field_obj EE_Model_Field_Base */
4946
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4947
-        }
4948
-        return $data_types;
4949
-    }
4950
-
4951
-
4952
-    /**
4953
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4954
-     *
4955
-     * @param string $model_name
4956
-     * @return EEM_Base
4957
-     * @throws EE_Error
4958
-     */
4959
-    public function get_related_model_obj($model_name)
4960
-    {
4961
-        $model_classname = "EEM_" . $model_name;
4962
-        if (! class_exists($model_classname)) {
4963
-            throw new EE_Error(
4964
-                sprintf(
4965
-                    esc_html__(
4966
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4967
-                        'event_espresso'
4968
-                    ),
4969
-                    $model_name,
4970
-                    $model_classname
4971
-                )
4972
-            );
4973
-        }
4974
-        return call_user_func($model_classname . "::instance");
4975
-    }
4976
-
4977
-
4978
-    /**
4979
-     * Returns the array of EE_ModelRelations for this model.
4980
-     *
4981
-     * @return EE_Model_Relation_Base[]
4982
-     */
4983
-    public function relation_settings()
4984
-    {
4985
-        return $this->_model_relations;
4986
-    }
4987
-
4988
-
4989
-    /**
4990
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4991
-     * because without THOSE models, this model probably doesn't have much purpose.
4992
-     * (Eg, without an event, datetimes have little purpose.)
4993
-     *
4994
-     * @return EE_Belongs_To_Relation[]
4995
-     */
4996
-    public function belongs_to_relations()
4997
-    {
4998
-        $belongs_to_relations = [];
4999
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
5000
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
5001
-                $belongs_to_relations[ $model_name ] = $relation_obj;
5002
-            }
5003
-        }
5004
-        return $belongs_to_relations;
5005
-    }
5006
-
5007
-
5008
-    /**
5009
-     * Returns the specified EE_Model_Relation, or throws an exception
5010
-     *
5011
-     * @param string $relation_name name of relation, key in $this->_relatedModels
5012
-     * @return EE_Model_Relation_Base
5013
-     * @throws EE_Error
5014
-     */
5015
-    public function related_settings_for($relation_name)
5016
-    {
5017
-        $relatedModels = $this->relation_settings();
5018
-        if (! array_key_exists($relation_name, $relatedModels)) {
5019
-            throw new EE_Error(
5020
-                sprintf(
5021
-                    esc_html__(
5022
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
5023
-                        'event_espresso'
5024
-                    ),
5025
-                    $relation_name,
5026
-                    $this->_get_class_name(),
5027
-                    implode(', ', array_keys($relatedModels))
5028
-                )
5029
-            );
5030
-        }
5031
-        return $relatedModels[ $relation_name ];
5032
-    }
5033
-
5034
-
5035
-    /**
5036
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
5037
-     * fields
5038
-     *
5039
-     * @param string  $fieldName
5040
-     * @param boolean $include_db_only_fields
5041
-     * @return EE_Model_Field_Base
5042
-     * @throws EE_Error
5043
-     */
5044
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
5045
-    {
5046
-        $fieldSettings = $this->field_settings($include_db_only_fields);
5047
-        if (! array_key_exists($fieldName, $fieldSettings)) {
5048
-            throw new EE_Error(
5049
-                sprintf(
5050
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
5051
-                    $fieldName,
5052
-                    get_class($this)
5053
-                )
5054
-            );
5055
-        }
5056
-        return $fieldSettings[ $fieldName ];
5057
-    }
5058
-
5059
-
5060
-    /**
5061
-     * Checks if this field exists on this model
5062
-     *
5063
-     * @param string $fieldName a key in the model's _field_settings array
5064
-     * @return boolean
5065
-     */
5066
-    public function has_field($fieldName)
5067
-    {
5068
-        $fieldSettings = $this->field_settings(true);
5069
-        if (isset($fieldSettings[ $fieldName ])) {
5070
-            return true;
5071
-        }
5072
-        return false;
5073
-    }
5074
-
5075
-
5076
-    /**
5077
-     * Returns whether or not this model has a relation to the specified model
5078
-     *
5079
-     * @param string $relation_name possibly one of the keys in the relation_settings array
5080
-     * @return boolean
5081
-     */
5082
-    public function has_relation($relation_name)
5083
-    {
5084
-        $relations = $this->relation_settings();
5085
-        if (isset($relations[ $relation_name ])) {
5086
-            return true;
5087
-        }
5088
-        return false;
5089
-    }
5090
-
5091
-
5092
-    /**
5093
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5094
-     * Eg, on EE_Answer that would be ANS_ID field object
5095
-     *
5096
-     * @param $field_obj
5097
-     * @return boolean
5098
-     */
5099
-    public function is_primary_key_field($field_obj): bool
5100
-    {
5101
-        return $field_obj instanceof EE_Primary_Key_Field_Base;
5102
-    }
5103
-
5104
-
5105
-    /**
5106
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5107
-     * Eg, on EE_Answer that would be ANS_ID field object
5108
-     *
5109
-     * @return EE_Primary_Key_Field_Base
5110
-     * @throws EE_Error
5111
-     */
5112
-    public function get_primary_key_field()
5113
-    {
5114
-        if ($this->_primary_key_field === null) {
5115
-            foreach ($this->field_settings(true) as $field_obj) {
5116
-                if ($this->is_primary_key_field($field_obj)) {
5117
-                    $this->_primary_key_field = $field_obj;
5118
-                    break;
5119
-                }
5120
-            }
5121
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5122
-                throw new EE_Error(
5123
-                    sprintf(
5124
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5125
-                        get_class($this)
5126
-                    )
5127
-                );
5128
-            }
5129
-        }
5130
-        return $this->_primary_key_field;
5131
-    }
5132
-
5133
-
5134
-    /**
5135
-     * Returns whether or not not there is a primary key on this model.
5136
-     * Internally does some caching.
5137
-     *
5138
-     * @return boolean
5139
-     */
5140
-    public function has_primary_key_field()
5141
-    {
5142
-        if ($this->_has_primary_key_field === null) {
5143
-            try {
5144
-                $this->get_primary_key_field();
5145
-                $this->_has_primary_key_field = true;
5146
-            } catch (EE_Error $e) {
5147
-                $this->_has_primary_key_field = false;
5148
-            }
5149
-        }
5150
-        return $this->_has_primary_key_field;
5151
-    }
5152
-
5153
-
5154
-    /**
5155
-     * Finds the first field of type $field_class_name.
5156
-     *
5157
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5158
-     *                                 EE_Foreign_Key_Field, etc
5159
-     * @return EE_Model_Field_Base or null if none is found
5160
-     */
5161
-    public function get_a_field_of_type($field_class_name)
5162
-    {
5163
-        foreach ($this->field_settings() as $field) {
5164
-            if ($field instanceof $field_class_name) {
5165
-                return $field;
5166
-            }
5167
-        }
5168
-        return null;
5169
-    }
5170
-
5171
-
5172
-    /**
5173
-     * Gets a foreign key field pointing to model.
5174
-     *
5175
-     * @param string $model_name eg Event, Registration, not EEM_Event
5176
-     * @return EE_Foreign_Key_Field_Base
5177
-     * @throws EE_Error
5178
-     */
5179
-    public function get_foreign_key_to($model_name)
5180
-    {
5181
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5182
-            foreach ($this->field_settings() as $field) {
5183
-                if (
5184
-                    $field instanceof EE_Foreign_Key_Field_Base
5185
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5186
-                ) {
5187
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5188
-                    break;
5189
-                }
5190
-            }
5191
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5192
-                throw new EE_Error(
5193
-                    sprintf(
5194
-                        esc_html__(
5195
-                            "There is no foreign key field pointing to model %s on model %s",
5196
-                            'event_espresso'
5197
-                        ),
5198
-                        $model_name,
5199
-                        get_class($this)
5200
-                    )
5201
-                );
5202
-            }
5203
-        }
5204
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5205
-    }
5206
-
5207
-
5208
-    /**
5209
-     * Gets the table name (including $wpdb->prefix) for the table alias
5210
-     *
5211
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5212
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5213
-     *                            Either one works
5214
-     * @return string
5215
-     */
5216
-    public function get_table_for_alias($table_alias)
5217
-    {
5218
-        $table_alias_sans_model_relation_chain_prefix =
5219
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5220
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5221
-    }
5222
-
5223
-
5224
-    /**
5225
-     * Returns a flat array of all field son this model, instead of organizing them
5226
-     * by table_alias as they are in the constructor.
5227
-     *
5228
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5229
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5230
-     */
5231
-    public function field_settings($include_db_only_fields = false)
5232
-    {
5233
-        if ($include_db_only_fields) {
5234
-            if ($this->_cached_fields === null) {
5235
-                $this->_cached_fields = [];
5236
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5237
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5238
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5239
-                    }
5240
-                }
5241
-            }
5242
-            return $this->_cached_fields;
5243
-        }
5244
-        if ($this->_cached_fields_non_db_only === null) {
5245
-            $this->_cached_fields_non_db_only = [];
5246
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5247
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5248
-                    /** @var $field_obj EE_Model_Field_Base */
5249
-                    if (! $field_obj->is_db_only_field()) {
5250
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5251
-                    }
5252
-                }
5253
-            }
5254
-        }
5255
-        return $this->_cached_fields_non_db_only;
5256
-    }
5257
-
5258
-
5259
-    /**
5260
-     *        cycle though array of attendees and create objects out of each item
5261
-     *
5262
-     * @access        private
5263
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5264
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5265
-     *                           numerically indexed)
5266
-     * @throws EE_Error
5267
-     * @throws ReflectionException
5268
-     */
5269
-    protected function _create_objects($rows = [])
5270
-    {
5271
-        $array_of_objects = [];
5272
-        if (empty($rows)) {
5273
-            return [];
5274
-        }
5275
-        $count_if_model_has_no_primary_key = 0;
5276
-        $has_primary_key                   = $this->has_primary_key_field();
5277
-        $primary_key_field                 = $has_primary_key
5278
-            ? $this->get_primary_key_field()
5279
-            : null;
5280
-        foreach ((array) $rows as $row) {
5281
-            if (empty($row)) {
5282
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5283
-                return [];
5284
-            }
5285
-            // check if we've already set this object in the results array,
5286
-            // in which case there's no need to process it further (again)
5287
-            if ($has_primary_key) {
5288
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5289
-                    $row,
5290
-                    $primary_key_field->get_qualified_column(),
5291
-                    $primary_key_field->get_table_column()
5292
-                );
5293
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5294
-                    continue;
5295
-                }
5296
-            }
5297
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5298
-            if (! $classInstance) {
5299
-                throw new EE_Error(
5300
-                    sprintf(
5301
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5302
-                        $this->get_this_model_name(),
5303
-                        http_build_query($row)
5304
-                    )
5305
-                );
5306
-            }
5307
-            // set the timezone on the instantiated objects
5308
-            $classInstance->set_timezone($this->_timezone);
5309
-            // make sure if there is any timezone setting present that we set the timezone for the object
5310
-            $key                      = $has_primary_key
5311
-                ? $classInstance->ID()
5312
-                : $count_if_model_has_no_primary_key++;
5313
-            $array_of_objects[ $key ] = $classInstance;
5314
-            // also, for all the relations of type BelongsTo, see if we can cache
5315
-            // those related models
5316
-            // (we could do this for other relations too, but if there are conditions
5317
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5318
-            // so it requires a little more thought than just caching them immediately...)
5319
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5320
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5321
-                    // check if this model's INFO is present. If so, cache it on the model
5322
-                    $other_model           = $relation_obj->get_other_model();
5323
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5324
-                    // if we managed to make a model object from the results, cache it on the main model object
5325
-                    if ($other_model_obj_maybe) {
5326
-                        // set timezone on these other model objects if they are present
5327
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5328
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5329
-                    }
5330
-                }
5331
-            }
5332
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5333
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5334
-            // the field in the CustomSelects object
5335
-            if ($this->_custom_selections instanceof CustomSelects) {
5336
-                $classInstance->setCustomSelectsValues(
5337
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5338
-                );
5339
-            }
5340
-        }
5341
-        return $array_of_objects;
5342
-    }
5343
-
5344
-
5345
-    /**
5346
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5347
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5348
-     *
5349
-     * @param array $db_results_row
5350
-     * @return array
5351
-     */
5352
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5353
-    {
5354
-        $results = [];
5355
-        if ($this->_custom_selections instanceof CustomSelects) {
5356
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5357
-                if (isset($db_results_row[ $alias ])) {
5358
-                    $results[ $alias ] = $this->convertValueToDataType(
5359
-                        $db_results_row[ $alias ],
5360
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5361
-                    );
5362
-                }
5363
-            }
5364
-        }
5365
-        return $results;
5366
-    }
5367
-
5368
-
5369
-    /**
5370
-     * This will set the value for the given alias
5371
-     *
5372
-     * @param string $value
5373
-     * @param string $datatype (one of %d, %s, %f)
5374
-     * @return int|string|float (int for %d, string for %s, float for %f)
5375
-     */
5376
-    protected function convertValueToDataType($value, $datatype)
5377
-    {
5378
-        switch ($datatype) {
5379
-            case '%f':
5380
-                return (float) $value;
5381
-            case '%d':
5382
-                return (int) $value;
5383
-            default:
5384
-                return (string) $value;
5385
-        }
5386
-    }
5387
-
5388
-
5389
-    /**
5390
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5391
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5392
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5393
-     * object (as set in the model_field!).
5394
-     *
5395
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5396
-     * @throws EE_Error
5397
-     * @throws ReflectionException
5398
-     */
5399
-    public function create_default_object()
5400
-    {
5401
-        $this_model_fields_and_values = [];
5402
-        // setup the row using default values;
5403
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5404
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5405
-        }
5406
-        $className = $this->_get_class_name();
5407
-        return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5408
-    }
5409
-
5410
-
5411
-    /**
5412
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5413
-     *                             or an stdClass where each property is the name of a column,
5414
-     * @return EE_Base_Class
5415
-     * @throws EE_Error
5416
-     * @throws ReflectionException
5417
-     */
5418
-    public function instantiate_class_from_array_or_object($cols_n_values)
5419
-    {
5420
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5421
-            $cols_n_values = get_object_vars($cols_n_values);
5422
-        }
5423
-        $primary_key = null;
5424
-        // make sure the array only has keys that are fields/columns on this model
5425
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5426
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5427
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5428
-        }
5429
-        $className = $this->_get_class_name();
5430
-        // check we actually found results that we can use to build our model object
5431
-        // if not, return null
5432
-        if ($this->has_primary_key_field()) {
5433
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5434
-                return null;
5435
-            }
5436
-        } elseif ($this->unique_indexes()) {
5437
-            $first_column = reset($this_model_fields_n_values);
5438
-            if (empty($first_column)) {
5439
-                return null;
5440
-            }
5441
-        }
5442
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5443
-        if ($primary_key) {
5444
-            $classInstance = $this->get_from_entity_map($primary_key);
5445
-            if (! $classInstance) {
5446
-                $classInstance = EE_Registry::instance()
5447
-                                            ->load_class(
5448
-                                                $className,
5449
-                                                [$this_model_fields_n_values, $this->_timezone],
5450
-                                                true,
5451
-                                                false
5452
-                                            );
5453
-                // add this new object to the entity map
5454
-                $classInstance = $this->add_to_entity_map($classInstance);
5455
-            }
5456
-        } else {
5457
-            $classInstance = EE_Registry::instance()->load_class(
5458
-                $className,
5459
-                [$this_model_fields_n_values, $this->_timezone],
5460
-                true,
5461
-                false
5462
-            );
5463
-        }
5464
-        return $classInstance;
5465
-    }
5466
-
5467
-
5468
-    /**
5469
-     * Gets the model object from the  entity map if it exists
5470
-     *
5471
-     * @param int|string $id the ID of the model object
5472
-     * @return EE_Base_Class
5473
-     */
5474
-    public function get_from_entity_map($id)
5475
-    {
5476
-        return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5477
-    }
5478
-
5479
-
5480
-    /**
5481
-     * add_to_entity_map
5482
-     * Adds the object to the model's entity mappings
5483
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5484
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5485
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5486
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5487
-     *        then this method should be called immediately after the update query
5488
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5489
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5490
-     *
5491
-     * @param EE_Base_Class $object
5492
-     * @return EE_Base_Class
5493
-     * @throws EE_Error
5494
-     * @throws ReflectionException
5495
-     */
5496
-    public function add_to_entity_map(EE_Base_Class $object)
5497
-    {
5498
-        $className = $this->_get_class_name();
5499
-        if (! $object instanceof $className) {
5500
-            throw new EE_Error(
5501
-                sprintf(
5502
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5503
-                    is_object($object)
5504
-                        ? get_class($object)
5505
-                        : $object,
5506
-                    $className
5507
-                )
5508
-            );
5509
-        }
5510
-
5511
-        if (! $object->ID()) {
5512
-            throw new EE_Error(
5513
-                sprintf(
5514
-                    esc_html__(
5515
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5516
-                        "event_espresso"
5517
-                    ),
5518
-                    get_class($this)
5519
-                )
5520
-            );
5521
-        }
5522
-        // double check it's not already there
5523
-        $classInstance = $this->get_from_entity_map($object->ID());
5524
-        if ($classInstance) {
5525
-            return $classInstance;
5526
-        }
5527
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5528
-        return $object;
5529
-    }
5530
-
5531
-
5532
-    /**
5533
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5534
-     * if no identifier is provided, then the entire entity map is emptied
5535
-     *
5536
-     * @param int|string $id the ID of the model object
5537
-     * @return boolean
5538
-     */
5539
-    public function clear_entity_map($id = null)
5540
-    {
5541
-        if (empty($id)) {
5542
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5543
-            return true;
5544
-        }
5545
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5546
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5547
-            return true;
5548
-        }
5549
-        return false;
5550
-    }
5551
-
5552
-
5553
-    /**
5554
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5555
-     * Given an array where keys are column (or column alias) names and values,
5556
-     * returns an array of their corresponding field names and database values
5557
-     *
5558
-     * @param array $cols_n_values
5559
-     * @return array
5560
-     * @throws EE_Error
5561
-     * @throws ReflectionException
5562
-     */
5563
-    public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5564
-    {
5565
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5566
-    }
5567
-
5568
-
5569
-    /**
5570
-     * _deduce_fields_n_values_from_cols_n_values
5571
-     * Given an array where keys are column (or column alias) names and values,
5572
-     * returns an array of their corresponding field names and database values
5573
-     *
5574
-     * @param array|stdClass $cols_n_values
5575
-     * @return array
5576
-     * @throws EE_Error
5577
-     * @throws ReflectionException
5578
-     */
5579
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5580
-    {
5581
-        if ($cols_n_values instanceof stdClass) {
5582
-            $cols_n_values = get_object_vars($cols_n_values);
5583
-        }
5584
-        $this_model_fields_n_values = [];
5585
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5586
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5587
-                $cols_n_values,
5588
-                $table_obj->get_fully_qualified_pk_column(),
5589
-                $table_obj->get_pk_column()
5590
-            );
5591
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5592
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5593
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5594
-                    if (! $field_obj->is_db_only_field()) {
5595
-                        // prepare field as if its coming from db
5596
-                        $prepared_value                            =
5597
-                            $field_obj->prepare_for_set($field_obj->get_default_value());
5598
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5599
-                    }
5600
-                }
5601
-            } else {
5602
-                // the table's rows existed. Use their values
5603
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5604
-                    if (! $field_obj->is_db_only_field()) {
5605
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5606
-                            $cols_n_values,
5607
-                            $field_obj->get_qualified_column(),
5608
-                            $field_obj->get_table_column()
5609
-                        );
5610
-                    }
5611
-                }
5612
-            }
5613
-        }
5614
-        return $this_model_fields_n_values;
5615
-    }
5616
-
5617
-
5618
-    /**
5619
-     * @param $cols_n_values
5620
-     * @param $qualified_column
5621
-     * @param $regular_column
5622
-     * @return null
5623
-     * @throws EE_Error
5624
-     * @throws ReflectionException
5625
-     */
5626
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5627
-    {
5628
-        $value = null;
5629
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5630
-        // does the field on the model relate to this column retrieved from the db?
5631
-        // or is it a db-only field? (not relating to the model)
5632
-        if (isset($cols_n_values[ $qualified_column ])) {
5633
-            $value = $cols_n_values[ $qualified_column ];
5634
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5635
-            $value = $cols_n_values[ $regular_column ];
5636
-        } elseif (! empty($this->foreign_key_aliases)) {
5637
-            // no PK?  ok check if there is a foreign key alias set for this table
5638
-            // then check if that alias exists in the incoming data
5639
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5640
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5641
-                if ($PK_column === $qualified_column && !empty($cols_n_values[ $FK_alias ])) {
5642
-                    $value = $cols_n_values[ $FK_alias ];
5643
-                    [$pk_class] = explode('.', $PK_column);
5644
-                    $pk_model_name = "EEM_{$pk_class}";
5645
-                    /** @var EEM_Base $pk_model */
5646
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5647
-                    if ($pk_model instanceof EEM_Base) {
5648
-                        // make sure object is pulled from db and added to entity map
5649
-                        $pk_model->get_one_by_ID($value);
5650
-                    }
5651
-                    break;
5652
-                }
5653
-            }
5654
-        }
5655
-        return $value;
5656
-    }
5657
-
5658
-
5659
-    /**
5660
-     * refresh_entity_map_from_db
5661
-     * Makes sure the model object in the entity map at $id assumes the values
5662
-     * of the database (opposite of EE_base_Class::save())
5663
-     *
5664
-     * @param int|string $id
5665
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5666
-     * @throws EE_Error
5667
-     * @throws ReflectionException
5668
-     */
5669
-    public function refresh_entity_map_from_db($id)
5670
-    {
5671
-        $obj_in_map = $this->get_from_entity_map($id);
5672
-        if ($obj_in_map) {
5673
-            $wpdb_results = $this->_get_all_wpdb_results(
5674
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5675
-            );
5676
-            if ($wpdb_results && is_array($wpdb_results)) {
5677
-                $one_row = reset($wpdb_results);
5678
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5679
-                    $obj_in_map->set_from_db($field_name, $db_value);
5680
-                }
5681
-                // clear the cache of related model objects
5682
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5683
-                    $obj_in_map->clear_cache($relation_name, null, true);
5684
-                }
5685
-            }
5686
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5687
-            return $obj_in_map;
5688
-        }
5689
-        return $this->get_one_by_ID($id);
5690
-    }
5691
-
5692
-
5693
-    /**
5694
-     * refresh_entity_map_with
5695
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5696
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5697
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5698
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5699
-     *
5700
-     * @param int|string    $id
5701
-     * @param EE_Base_Class $replacing_model_obj
5702
-     * @return EE_Base_Class
5703
-     * @throws EE_Error
5704
-     * @throws ReflectionException
5705
-     */
5706
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5707
-    {
5708
-        $obj_in_map = $this->get_from_entity_map($id);
5709
-        if ($obj_in_map) {
5710
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5711
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5712
-                    $obj_in_map->set($field_name, $value);
5713
-                }
5714
-                // make the model object in the entity map's cache match the $replacing_model_obj
5715
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5716
-                    $obj_in_map->clear_cache($relation_name, null, true);
5717
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5718
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5719
-                    }
5720
-                }
5721
-            }
5722
-            return $obj_in_map;
5723
-        }
5724
-        $this->add_to_entity_map($replacing_model_obj);
5725
-        return $replacing_model_obj;
5726
-    }
5727
-
5728
-
5729
-    /**
5730
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5731
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5732
-     * require_once($this->_getClassName().".class.php");
5733
-     *
5734
-     * @return string
5735
-     */
5736
-    private function _get_class_name()
5737
-    {
5738
-        return "EE_" . $this->get_this_model_name();
5739
-    }
5740
-
5741
-
5742
-    /**
5743
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5744
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5745
-     * it would be 'Events'.
5746
-     *
5747
-     * @param int|float|null $quantity
5748
-     * @return string
5749
-     */
5750
-    public function item_name($quantity = 1): string
5751
-    {
5752
-        $quantity = floor($quantity);
5753
-        return apply_filters(
5754
-            'FHEE__EEM_Base__item_name__plural_or_singular',
5755
-            $quantity > 1
5756
-                ? $this->plural_item
5757
-                : $this->singular_item,
5758
-            $quantity,
5759
-            $this->plural_item,
5760
-            $this->singular_item
5761
-        );
5762
-    }
5763
-
5764
-
5765
-    /**
5766
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5767
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5768
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5769
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5770
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5771
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5772
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5773
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5774
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5775
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5776
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5777
-     *        return $previousReturnValue.$returnString;
5778
-     * }
5779
-     * require('EEM_Answer.model.php');
5780
-     * echo EEM_Answer::instance()->my_callback('monkeys',100);
5781
-     * // will output "you called my_callback! and passed args:monkeys,100"
5782
-     *
5783
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5784
-     * @param array  $args       array of original arguments passed to the function
5785
-     * @return mixed whatever the plugin which calls add_filter decides
5786
-     * @throws EE_Error
5787
-     */
5788
-    public function __call($methodName, $args)
5789
-    {
5790
-        $className = get_class($this);
5791
-        $tagName   = "FHEE__{$className}__{$methodName}";
5792
-        if (! has_filter($tagName)) {
5793
-            throw new EE_Error(
5794
-                sprintf(
5795
-                    esc_html__(
5796
-                        'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5797
-                        'event_espresso'
5798
-                    ),
5799
-                    $methodName,
5800
-                    $className,
5801
-                    $tagName,
5802
-                    '<br />'
5803
-                )
5804
-            );
5805
-        }
5806
-        return apply_filters($tagName, null, $this, $args);
5807
-    }
5808
-
5809
-
5810
-    /**
5811
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5812
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5813
-     *
5814
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5815
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5816
-     *                                                       the object's class name
5817
-     *                                                       or object's ID
5818
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5819
-     *                                                       exists in the database. If it does not, we add it
5820
-     * @return EE_Base_Class
5821
-     * @throws EE_Error
5822
-     * @throws ReflectionException
5823
-     */
5824
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5825
-    {
5826
-        $className = $this->_get_class_name();
5827
-        if ($base_class_obj_or_id instanceof $className) {
5828
-            $model_object = $base_class_obj_or_id;
5829
-        } else {
5830
-            $primary_key_field = $this->get_primary_key_field();
5831
-            if (
5832
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5833
-                && (
5834
-                    is_int($base_class_obj_or_id)
5835
-                    || is_string($base_class_obj_or_id)
5836
-                )
5837
-            ) {
5838
-                // assume it's an ID.
5839
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5840
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5841
-            } elseif (
5842
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5843
-                && is_string($base_class_obj_or_id)
5844
-            ) {
5845
-                // assume it's a string representation of the object
5846
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5847
-            } else {
5848
-                throw new EE_Error(
5849
-                    sprintf(
5850
-                        esc_html__(
5851
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5852
-                            'event_espresso'
5853
-                        ),
5854
-                        $base_class_obj_or_id,
5855
-                        $this->_get_class_name(),
5856
-                        print_r($base_class_obj_or_id, true)
5857
-                    )
5858
-                );
5859
-            }
5860
-        }
5861
-        if ($ensure_is_in_db && $model_object instanceof EE_Base_Class && $model_object->ID() !== null) {
5862
-            $model_object->save();
5863
-        }
5864
-        return $model_object;
5865
-    }
5866
-
5867
-
5868
-    /**
5869
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5870
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5871
-     * returns it ID.
5872
-     *
5873
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5874
-     * @return int|string depending on the type of this model object's ID
5875
-     * @throws EE_Error
5876
-     * @throws ReflectionException
5877
-     */
5878
-    public function ensure_is_ID($base_class_obj_or_id)
5879
-    {
5880
-        $className = $this->_get_class_name();
5881
-        if ($base_class_obj_or_id instanceof $className) {
5882
-            /** @var $base_class_obj_or_id EE_Base_Class */
5883
-            $id = $base_class_obj_or_id->ID();
5884
-        } elseif (is_int($base_class_obj_or_id)) {
5885
-            // assume it's an ID
5886
-            $id = $base_class_obj_or_id;
5887
-        } elseif (is_string($base_class_obj_or_id)) {
5888
-            // assume its a string representation of the object
5889
-            $id = $base_class_obj_or_id;
5890
-        } else {
5891
-            throw new EE_Error(
5892
-                sprintf(
5893
-                    esc_html__(
5894
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5895
-                        'event_espresso'
5896
-                    ),
5897
-                    $base_class_obj_or_id,
5898
-                    $this->_get_class_name(),
5899
-                    print_r($base_class_obj_or_id, true)
5900
-                )
5901
-            );
5902
-        }
5903
-        return $id;
5904
-    }
5905
-
5906
-
5907
-    /**
5908
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5909
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5910
-     * been sanitized and converted into the appropriate domain.
5911
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5912
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5913
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5914
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5915
-     * $EVT = EEM_Event::instance(); $old_setting =
5916
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5917
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5918
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5919
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5920
-     *
5921
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5922
-     * @return void
5923
-     */
5924
-    public function assume_values_already_prepared_by_model_object(
5925
-        $values_already_prepared = self::not_prepared_by_model_object
5926
-    ) {
5927
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5928
-    }
5929
-
5930
-
5931
-    /**
5932
-     * Read comments for assume_values_already_prepared_by_model_object()
5933
-     *
5934
-     * @return int
5935
-     */
5936
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5937
-    {
5938
-        return $this->_values_already_prepared_by_model_object;
5939
-    }
5940
-
5941
-
5942
-    /**
5943
-     * Gets all the indexes on this model
5944
-     *
5945
-     * @return EE_Index[]
5946
-     */
5947
-    public function indexes()
5948
-    {
5949
-        return $this->_indexes;
5950
-    }
5951
-
5952
-
5953
-    /**
5954
-     * Gets all the Unique Indexes on this model
5955
-     *
5956
-     * @return EE_Unique_Index[]
5957
-     */
5958
-    public function unique_indexes()
5959
-    {
5960
-        $unique_indexes = [];
5961
-        foreach ($this->_indexes as $name => $index) {
5962
-            if ($index instanceof EE_Unique_Index) {
5963
-                $unique_indexes [ $name ] = $index;
5964
-            }
5965
-        }
5966
-        return $unique_indexes;
5967
-    }
5968
-
5969
-
5970
-    /**
5971
-     * Gets all the fields which, when combined, make the primary key.
5972
-     * This is usually just an array with 1 element (the primary key), but in cases
5973
-     * where there is no primary key, it's a combination of fields as defined
5974
-     * on a primary index
5975
-     *
5976
-     * @return EE_Model_Field_Base[] indexed by the field's name
5977
-     * @throws EE_Error
5978
-     */
5979
-    public function get_combined_primary_key_fields()
5980
-    {
5981
-        foreach ($this->indexes() as $index) {
5982
-            if ($index instanceof EE_Primary_Key_Index) {
5983
-                return $index->fields();
5984
-            }
5985
-        }
5986
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5987
-    }
5988
-
5989
-
5990
-    /**
5991
-     * Used to build a primary key string (when the model has no primary key),
5992
-     * which can be used a unique string to identify this model object.
5993
-     *
5994
-     * @param array $fields_n_values keys are field names, values are their values.
5995
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5996
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5997
-     *                               before passing it to this function (that will convert it from columns-n-values
5998
-     *                               to field-names-n-values).
5999
-     * @return string
6000
-     * @throws EE_Error
6001
-     */
6002
-    public function get_index_primary_key_string($fields_n_values)
6003
-    {
6004
-        $cols_n_values_for_primary_key_index = array_intersect_key(
6005
-            $fields_n_values,
6006
-            $this->get_combined_primary_key_fields()
6007
-        );
6008
-        return http_build_query($cols_n_values_for_primary_key_index);
6009
-    }
6010
-
6011
-
6012
-    /**
6013
-     * Gets the field values from the primary key string
6014
-     *
6015
-     * @param string $index_primary_key_string
6016
-     * @return null|array
6017
-     * @throws EE_Error
6018
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
6019
-     */
6020
-    public function parse_index_primary_key_string($index_primary_key_string)
6021
-    {
6022
-        $key_fields = $this->get_combined_primary_key_fields();
6023
-        // check all of them are in the $id
6024
-        $key_vals_in_combined_pk = [];
6025
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6026
-        foreach ($key_fields as $key_field_name => $field_obj) {
6027
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6028
-                return null;
6029
-            }
6030
-        }
6031
-        return $key_vals_in_combined_pk;
6032
-    }
6033
-
6034
-
6035
-    /**
6036
-     * verifies that an array of key-value pairs for model fields has a key
6037
-     * for each field comprising the primary key index
6038
-     *
6039
-     * @param array $key_vals
6040
-     * @return boolean
6041
-     * @throws EE_Error
6042
-     */
6043
-    public function has_all_combined_primary_key_fields($key_vals)
6044
-    {
6045
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6046
-        foreach ($keys_it_should_have as $key) {
6047
-            if (! isset($key_vals[ $key ])) {
6048
-                return false;
6049
-            }
6050
-        }
6051
-        return true;
6052
-    }
6053
-
6054
-
6055
-    /**
6056
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
6057
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
6058
-     *
6059
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
6060
-     * @param array               $query_params                     @see
6061
-     *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
6062
-     * @throws EE_Error
6063
-     * @throws ReflectionException
6064
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
6065
-     *                                                              indexed)
6066
-     */
6067
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
6068
-    {
6069
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
6070
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
6071
-        } elseif (is_array($model_object_or_attributes_array)) {
6072
-            $attributes_array = $model_object_or_attributes_array;
6073
-        } else {
6074
-            throw new EE_Error(
6075
-                sprintf(
6076
-                    esc_html__(
6077
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
6078
-                        "event_espresso"
6079
-                    ),
6080
-                    $model_object_or_attributes_array
6081
-                )
6082
-            );
6083
-        }
6084
-        // even copies obviously won't have the same ID, so remove the primary key
6085
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
6086
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6087
-            unset($attributes_array[ $this->primary_key_name() ]);
6088
-        }
6089
-        if (isset($query_params[0])) {
6090
-            $query_params[0] = array_merge($attributes_array, $query_params);
6091
-        } else {
6092
-            $query_params[0] = $attributes_array;
6093
-        }
6094
-        return $this->get_all($query_params);
6095
-    }
6096
-
6097
-
6098
-    /**
6099
-     * Gets the first copy we find. See get_all_copies for more details
6100
-     *
6101
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6102
-     * @param array $query_params
6103
-     * @return EE_Base_Class
6104
-     * @throws EE_Error
6105
-     * @throws ReflectionException
6106
-     */
6107
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6108
-    {
6109
-        if (! is_array($query_params)) {
6110
-            EE_Error::doing_it_wrong(
6111
-                'EEM_Base::get_one_copy',
6112
-                sprintf(
6113
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6114
-                    gettype($query_params)
6115
-                ),
6116
-                '4.6.0'
6117
-            );
6118
-            $query_params = [];
6119
-        }
6120
-        $query_params['limit'] = 1;
6121
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6122
-        if (is_array($copies)) {
6123
-            return array_shift($copies);
6124
-        }
6125
-        return null;
6126
-    }
6127
-
6128
-
6129
-    /**
6130
-     * Updates the item with the specified id. Ignores default query parameters because
6131
-     * we have specified the ID, and its assumed we KNOW what we're doing
6132
-     *
6133
-     * @param array      $fields_n_values keys are field names, values are their new values
6134
-     * @param int|string $id              the value of the primary key to update
6135
-     * @return int number of rows updated
6136
-     * @throws EE_Error
6137
-     * @throws ReflectionException
6138
-     */
6139
-    public function update_by_ID($fields_n_values, $id)
6140
-    {
6141
-        $query_params = [
6142
-            0                          => [$this->get_primary_key_field()->get_name() => $id],
6143
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6144
-        ];
6145
-        return $this->update($fields_n_values, $query_params);
6146
-    }
6147
-
6148
-
6149
-    /**
6150
-     * Changes an operator which was supplied to the models into one usable in SQL
6151
-     *
6152
-     * @param string $operator_supplied
6153
-     * @return string an operator which can be used in SQL
6154
-     * @throws EE_Error
6155
-     */
6156
-    private function _prepare_operator_for_sql($operator_supplied)
6157
-    {
6158
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6159
-        if ($sql_operator) {
6160
-            return $sql_operator;
6161
-        }
6162
-        throw new EE_Error(
6163
-            sprintf(
6164
-                esc_html__(
6165
-                    "The operator '%s' is not in the list of valid operators: %s",
6166
-                    "event_espresso"
6167
-                ),
6168
-                $operator_supplied,
6169
-                implode(",", array_keys($this->_valid_operators))
6170
-            )
6171
-        );
6172
-    }
6173
-
6174
-
6175
-    /**
6176
-     * Gets the valid operators
6177
-     *
6178
-     * @return array keys are accepted strings, values are the SQL they are converted to
6179
-     */
6180
-    public function valid_operators()
6181
-    {
6182
-        return $this->_valid_operators;
6183
-    }
6184
-
6185
-
6186
-    /**
6187
-     * Gets the between-style operators (take 2 arguments).
6188
-     *
6189
-     * @return array keys are accepted strings, values are the SQL they are converted to
6190
-     */
6191
-    public function valid_between_style_operators()
6192
-    {
6193
-        return array_intersect(
6194
-            $this->valid_operators(),
6195
-            $this->_between_style_operators
6196
-        );
6197
-    }
6198
-
6199
-
6200
-    /**
6201
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6202
-     *
6203
-     * @return array keys are accepted strings, values are the SQL they are converted to
6204
-     */
6205
-    public function valid_like_style_operators()
6206
-    {
6207
-        return array_intersect(
6208
-            $this->valid_operators(),
6209
-            $this->_like_style_operators
6210
-        );
6211
-    }
6212
-
6213
-
6214
-    /**
6215
-     * Gets the "in"-style operators
6216
-     *
6217
-     * @return array keys are accepted strings, values are the SQL they are converted to
6218
-     */
6219
-    public function valid_in_style_operators()
6220
-    {
6221
-        return array_intersect(
6222
-            $this->valid_operators(),
6223
-            $this->_in_style_operators
6224
-        );
6225
-    }
6226
-
6227
-
6228
-    /**
6229
-     * Gets the "null"-style operators (accept no arguments)
6230
-     *
6231
-     * @return array keys are accepted strings, values are the SQL they are converted to
6232
-     */
6233
-    public function valid_null_style_operators()
6234
-    {
6235
-        return array_intersect(
6236
-            $this->valid_operators(),
6237
-            $this->_null_style_operators
6238
-        );
6239
-    }
6240
-
6241
-
6242
-    /**
6243
-     * Gets an array where keys are the primary keys and values are their 'names'
6244
-     * (as determined by the model object's name() function, which is often overridden)
6245
-     *
6246
-     * @param array $query_params like get_all's
6247
-     * @return string[]
6248
-     * @throws EE_Error
6249
-     * @throws ReflectionException
6250
-     */
6251
-    public function get_all_names($query_params = [])
6252
-    {
6253
-        $objs  = $this->get_all($query_params);
6254
-        $names = [];
6255
-        foreach ($objs as $obj) {
6256
-            $names[ $obj->ID() ] = $obj->name();
6257
-        }
6258
-        return $names;
6259
-    }
6260
-
6261
-
6262
-    /**
6263
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6264
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6265
-     * this is duplicated effort and reduces efficiency) you would be better to use
6266
-     * array_keys() on $model_objects.
6267
-     *
6268
-     * @param \EE_Base_Class[] $model_objects
6269
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6270
-     *                                               in the returned array
6271
-     * @return array
6272
-     * @throws EE_Error
6273
-     * @throws ReflectionException
6274
-     */
6275
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6276
-    {
6277
-        if (! $this->has_primary_key_field()) {
6278
-            if (WP_DEBUG) {
6279
-                EE_Error::add_error(
6280
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6281
-                    __FILE__,
6282
-                    __FUNCTION__,
6283
-                    __LINE__
6284
-                );
6285
-            }
6286
-        }
6287
-        $IDs = [];
6288
-        foreach ($model_objects as $model_object) {
6289
-            $id = $model_object->ID();
6290
-            if (! $id) {
6291
-                if ($filter_out_empty_ids) {
6292
-                    continue;
6293
-                }
6294
-                if (WP_DEBUG) {
6295
-                    EE_Error::add_error(
6296
-                        esc_html__(
6297
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6298
-                            'event_espresso'
6299
-                        ),
6300
-                        __FILE__,
6301
-                        __FUNCTION__,
6302
-                        __LINE__
6303
-                    );
6304
-                }
6305
-            }
6306
-            $IDs[] = $id;
6307
-        }
6308
-        return $IDs;
6309
-    }
6310
-
6311
-
6312
-    /**
6313
-     * Returns the string used in capabilities relating to this model. If there
6314
-     * are no capabilities that relate to this model returns false
6315
-     *
6316
-     * @return string|false
6317
-     */
6318
-    public function cap_slug()
6319
-    {
6320
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6321
-    }
6322
-
6323
-
6324
-    /**
6325
-     * Returns the capability-restrictions array (@param string $context
6326
-     *
6327
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6328
-     * @throws EE_Error
6329
-     * @see EEM_Base::_cap_restrictions).
6330
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6331
-     *      only returns the cap restrictions array in that context (ie, the array
6332
-     *      at that key)
6333
-     */
6334
-    public function cap_restrictions($context = EEM_Base::caps_read)
6335
-    {
6336
-        EEM_Base::verify_is_valid_cap_context($context);
6337
-        // check if we ought to run the restriction generator first
6338
-        if (
6339
-            isset($this->_cap_restriction_generators[ $context ])
6340
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6341
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6342
-        ) {
6343
-            $this->_cap_restrictions[ $context ] = array_merge(
6344
-                $this->_cap_restrictions[ $context ],
6345
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6346
-            );
6347
-        }
6348
-        // and make sure we've finalized the construction of each restriction
6349
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6350
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6351
-                $where_conditions_obj->_finalize_construct($this);
6352
-            }
6353
-        }
6354
-        return $this->_cap_restrictions[ $context ];
6355
-    }
6356
-
6357
-
6358
-    /**
6359
-     * Indicating whether or not this model thinks its a wp core model
6360
-     *
6361
-     * @return boolean
6362
-     */
6363
-    public function is_wp_core_model()
6364
-    {
6365
-        return $this->_wp_core_model;
6366
-    }
6367
-
6368
-
6369
-    /**
6370
-     * Gets all the caps that are missing which impose a restriction on
6371
-     * queries made in this context
6372
-     *
6373
-     * @param string $context one of EEM_Base::caps_ constants
6374
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6375
-     * @throws EE_Error
6376
-     */
6377
-    public function caps_missing($context = EEM_Base::caps_read)
6378
-    {
6379
-        $missing_caps     = [];
6380
-        $cap_restrictions = $this->cap_restrictions($context);
6381
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6382
-            if (
6383
-                ! EE_Capabilities::instance()
6384
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6385
-            ) {
6386
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6387
-            }
6388
-        }
6389
-        return $missing_caps;
6390
-    }
6391
-
6392
-
6393
-    /**
6394
-     * Gets the mapping from capability contexts to action strings used in capability names
6395
-     *
6396
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6397
-     * one of 'read', 'edit', or 'delete'
6398
-     */
6399
-    public function cap_contexts_to_cap_action_map()
6400
-    {
6401
-        return apply_filters(
6402
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6403
-            $this->_cap_contexts_to_cap_action_map,
6404
-            $this
6405
-        );
6406
-    }
6407
-
6408
-
6409
-    /**
6410
-     * Gets the action string for the specified capability context
6411
-     *
6412
-     * @param string $context
6413
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6414
-     * @throws EE_Error
6415
-     */
6416
-    public function cap_action_for_context($context)
6417
-    {
6418
-        $mapping = $this->cap_contexts_to_cap_action_map();
6419
-        if (isset($mapping[ $context ])) {
6420
-            return $mapping[ $context ];
6421
-        }
6422
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6423
-            return $action;
6424
-        }
6425
-        throw new EE_Error(
6426
-            sprintf(
6427
-                esc_html__(
6428
-                    'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6429
-                    'event_espresso'
6430
-                ),
6431
-                $context,
6432
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6433
-            )
6434
-        );
6435
-    }
6436
-
6437
-
6438
-    /**
6439
-     * Returns all the capability contexts which are valid when querying models
6440
-     *
6441
-     * @return array
6442
-     */
6443
-    public static function valid_cap_contexts(): array
6444
-    {
6445
-        return (array) apply_filters(
6446
-            'FHEE__EEM_Base__valid_cap_contexts',
6447
-            [
6448
-                self::caps_read,
6449
-                self::caps_read_admin,
6450
-                self::caps_edit,
6451
-                self::caps_delete,
6452
-            ]
6453
-        );
6454
-    }
6455
-
6456
-
6457
-    /**
6458
-     * Returns all valid options for 'default_where_conditions'
6459
-     *
6460
-     * @return array
6461
-     */
6462
-    public static function valid_default_where_conditions(): array
6463
-    {
6464
-        return [
6465
-            EEM_Base::default_where_conditions_all,
6466
-            EEM_Base::default_where_conditions_this_only,
6467
-            EEM_Base::default_where_conditions_others_only,
6468
-            EEM_Base::default_where_conditions_minimum_all,
6469
-            EEM_Base::default_where_conditions_minimum_others,
6470
-            EEM_Base::default_where_conditions_none,
6471
-        ];
6472
-    }
6473
-
6474
-    // public static function default_where_conditions_full
6475
-
6476
-
6477
-    /**
6478
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6479
-     *
6480
-     * @param string $context
6481
-     * @return bool
6482
-     * @throws EE_Error
6483
-     */
6484
-    public static function verify_is_valid_cap_context($context): bool
6485
-    {
6486
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6487
-        if (in_array($context, $valid_cap_contexts)) {
6488
-            return true;
6489
-        }
6490
-        throw new EE_Error(
6491
-            sprintf(
6492
-                esc_html__(
6493
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6494
-                    'event_espresso'
6495
-                ),
6496
-                $context,
6497
-                'EEM_Base',
6498
-                implode(',', $valid_cap_contexts)
6499
-            )
6500
-        );
6501
-    }
6502
-
6503
-
6504
-    /**
6505
-     * Clears all the models field caches. This is only useful when a sub-class
6506
-     * might have added a field or something and these caches might be invalidated
6507
-     */
6508
-    protected function _invalidate_field_caches()
6509
-    {
6510
-        $this->_cache_foreign_key_to_fields = [];
6511
-        $this->_cached_fields               = null;
6512
-        $this->_cached_fields_non_db_only   = null;
6513
-    }
6514
-
6515
-
6516
-    /**
6517
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6518
-     * (eg "and", "or", "not").
6519
-     *
6520
-     * @return array
6521
-     */
6522
-    public function logic_query_param_keys(): array
6523
-    {
6524
-        return $this->_logic_query_param_keys;
6525
-    }
6526
-
6527
-
6528
-    /**
6529
-     * Determines whether or not the where query param array key is for a logic query param.
6530
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6531
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6532
-     *
6533
-     * @param $query_param_key
6534
-     * @return bool
6535
-     */
6536
-    public function is_logic_query_param_key($query_param_key): bool
6537
-    {
6538
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6539
-            if (
6540
-                $query_param_key === $logic_query_param_key
6541
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6542
-            ) {
6543
-                return true;
6544
-            }
6545
-        }
6546
-        return false;
6547
-    }
6548
-
6549
-
6550
-    /**
6551
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6552
-     *
6553
-     * @return boolean
6554
-     * @since 4.9.74.p
6555
-     */
6556
-    public function hasPassword(): bool
6557
-    {
6558
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6559
-        if ($this->has_password_field === null) {
6560
-            $password_field           = $this->getPasswordField();
6561
-            $this->has_password_field = $password_field instanceof EE_Password_Field;
6562
-        }
6563
-        return $this->has_password_field;
6564
-    }
6565
-
6566
-
6567
-    /**
6568
-     * Returns the password field on this model, if there is one
6569
-     *
6570
-     * @return EE_Password_Field|null
6571
-     * @since 4.9.74.p
6572
-     */
6573
-    public function getPasswordField()
6574
-    {
6575
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6576
-        // there's no need to search for it. If we don't know yet, then find out
6577
-        if ($this->has_password_field === null && $this->password_field === null) {
6578
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6579
-        }
6580
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6581
-        return $this->password_field;
6582
-    }
6583
-
6584
-
6585
-    /**
6586
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6587
-     *
6588
-     * @return EE_Model_Field_Base[]
6589
-     * @throws EE_Error
6590
-     * @since 4.9.74.p
6591
-     */
6592
-    public function getPasswordProtectedFields()
6593
-    {
6594
-        $password_field = $this->getPasswordField();
6595
-        $fields         = [];
6596
-        if ($password_field instanceof EE_Password_Field) {
6597
-            $field_names = $password_field->protectedFields();
6598
-            foreach ($field_names as $field_name) {
6599
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6600
-            }
6601
-        }
6602
-        return $fields;
6603
-    }
6604
-
6605
-
6606
-    /**
6607
-     * Checks if the current user can perform the requested action on this model
6608
-     *
6609
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6610
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6611
-     * @return bool
6612
-     * @throws EE_Error
6613
-     * @throws InvalidArgumentException
6614
-     * @throws InvalidDataTypeException
6615
-     * @throws InvalidInterfaceException
6616
-     * @throws ReflectionException
6617
-     * @throws UnexpectedEntityException
6618
-     * @since 4.9.74.p
6619
-     */
6620
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6621
-    {
6622
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6623
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6624
-        }
6625
-        if (! is_array($model_obj_or_fields_n_values)) {
6626
-            throw new UnexpectedEntityException(
6627
-                $model_obj_or_fields_n_values,
6628
-                'EE_Base_Class',
6629
-                sprintf(
6630
-                    esc_html__(
6631
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6632
-                        'event_espresso'
6633
-                    ),
6634
-                    __FUNCTION__
6635
-                )
6636
-            );
6637
-        }
6638
-        return $this->exists(
6639
-            $this->alter_query_params_to_restrict_by_ID(
6640
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6641
-                [
6642
-                    'default_where_conditions' => 'none',
6643
-                    'caps'                     => $cap_to_check,
6644
-                ]
6645
-            )
6646
-        );
6647
-    }
6648
-
6649
-
6650
-    /**
6651
-     * Returns the query param where conditions key to the password affecting this model.
6652
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6653
-     *
6654
-     * @return null|string
6655
-     * @throws EE_Error
6656
-     * @throws InvalidArgumentException
6657
-     * @throws InvalidDataTypeException
6658
-     * @throws InvalidInterfaceException
6659
-     * @throws ModelConfigurationException
6660
-     * @throws ReflectionException
6661
-     * @since 4.9.74.p
6662
-     */
6663
-    public function modelChainAndPassword()
6664
-    {
6665
-        if ($this->model_chain_to_password === null) {
6666
-            throw new ModelConfigurationException(
6667
-                $this,
6668
-                esc_html_x(
6669
-                // @codingStandardsIgnoreStart
6670
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6671
-                    // @codingStandardsIgnoreEnd
6672
-                    '1: model name',
6673
-                    'event_espresso'
6674
-                )
6675
-            );
6676
-        }
6677
-        if ($this->model_chain_to_password === '') {
6678
-            $model_with_password = $this;
6679
-        } else {
6680
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6681
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6682
-            } else {
6683
-                $last_model_in_chain = $this->model_chain_to_password;
6684
-            }
6685
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6686
-        }
6687
-
6688
-        $password_field = $model_with_password->getPasswordField();
6689
-        if ($password_field instanceof EE_Password_Field) {
6690
-            $password_field_name = $password_field->get_name();
6691
-        } else {
6692
-            throw new ModelConfigurationException(
6693
-                $this,
6694
-                sprintf(
6695
-                    esc_html_x(
6696
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6697
-                        '1: model name, 2: special string',
6698
-                        'event_espresso'
6699
-                    ),
6700
-                    $model_with_password->get_this_model_name(),
6701
-                    $this->model_chain_to_password
6702
-                )
6703
-            );
6704
-        }
6705
-        return (
6706
-               $this->model_chain_to_password
6707
-                   ? $this->model_chain_to_password . '.'
6708
-                   : ''
6709
-               ) . $password_field_name;
6710
-    }
6711
-
6712
-
6713
-    /**
6714
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6715
-     * or if this model itself has a password affecting access to some of its other fields.
6716
-     *
6717
-     * @return boolean
6718
-     * @since 4.9.74.p
6719
-     */
6720
-    public function restrictedByRelatedModelPassword(): bool
6721
-    {
6722
-        return $this->model_chain_to_password !== null;
6723
-    }
3961
+		}
3962
+		return $null_friendly_where_conditions;
3963
+	}
3964
+
3965
+
3966
+	/**
3967
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3968
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3969
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3970
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3971
+	 *
3972
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3973
+	 * @return array @see
3974
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3975
+	 * @throws EE_Error
3976
+	 * @throws EE_Error
3977
+	 */
3978
+	private function _get_default_where_conditions($model_relation_path = '')
3979
+	{
3980
+		if ($this->_ignore_where_strategy) {
3981
+			return [];
3982
+		}
3983
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3984
+	}
3985
+
3986
+
3987
+	/**
3988
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3989
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3990
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3991
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3992
+	 * Similar to _get_default_where_conditions
3993
+	 *
3994
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3995
+	 * @return array @see
3996
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3997
+	 * @throws EE_Error
3998
+	 * @throws EE_Error
3999
+	 */
4000
+	protected function _get_minimum_where_conditions($model_relation_path = '')
4001
+	{
4002
+		if ($this->_ignore_where_strategy) {
4003
+			return [];
4004
+		}
4005
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
4006
+	}
4007
+
4008
+
4009
+	/**
4010
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
4011
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
4012
+	 *
4013
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
4014
+	 * @return string
4015
+	 * @throws EE_Error
4016
+	 */
4017
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
4018
+	{
4019
+		$selects = $this->_get_columns_to_select_for_this_model();
4020
+		foreach (
4021
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
4022
+		) {
4023
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
4024
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
4025
+			foreach ($other_model_selects as $key => $value) {
4026
+				$selects[] = $value;
4027
+			}
4028
+		}
4029
+		return implode(", ", $selects);
4030
+	}
4031
+
4032
+
4033
+	/**
4034
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
4035
+	 * So that's going to be the columns for all the fields on the model
4036
+	 *
4037
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
4038
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
4039
+	 */
4040
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
4041
+	{
4042
+		$fields                                       = $this->field_settings();
4043
+		$selects                                      = [];
4044
+		$table_alias_with_model_relation_chain_prefix =
4045
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
4046
+				$model_relation_chain,
4047
+				$this->get_this_model_name()
4048
+			);
4049
+		foreach ($fields as $field_obj) {
4050
+			$selects[] = $table_alias_with_model_relation_chain_prefix
4051
+						 . $field_obj->get_table_alias()
4052
+						 . "."
4053
+						 . $field_obj->get_table_column()
4054
+						 . " AS '"
4055
+						 . $table_alias_with_model_relation_chain_prefix
4056
+						 . $field_obj->get_table_alias()
4057
+						 . "."
4058
+						 . $field_obj->get_table_column()
4059
+						 . "'";
4060
+		}
4061
+		// make sure we are also getting the PKs of each table
4062
+		$tables = $this->get_tables();
4063
+		if (count($tables) > 1) {
4064
+			foreach ($tables as $table_obj) {
4065
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4066
+									   . $table_obj->get_fully_qualified_pk_column();
4067
+				if (! in_array($qualified_pk_column, $selects)) {
4068
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4069
+				}
4070
+			}
4071
+		}
4072
+		return $selects;
4073
+	}
4074
+
4075
+
4076
+	/**
4077
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4078
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4079
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4080
+	 * SQL for joining, and the data types
4081
+	 *
4082
+	 * @param null|string                 $original_query_param
4083
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
4084
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4085
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4086
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4087
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
4088
+	 *                                                          or 'Registration's
4089
+	 * @param string                      $original_query_param what it originally was (eg
4090
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4091
+	 *                                                          matches $query_param
4092
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4093
+	 * @throws EE_Error
4094
+	 */
4095
+	private function _extract_related_model_info_from_query_param(
4096
+		$query_param,
4097
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4098
+		$query_param_type,
4099
+		$original_query_param = null
4100
+	) {
4101
+		if ($original_query_param === null) {
4102
+			$original_query_param = $query_param;
4103
+		}
4104
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4105
+		// check to see if we have a field on this model
4106
+		$this_model_fields = $this->field_settings(true);
4107
+		if (array_key_exists($query_param, $this_model_fields)) {
4108
+			$field_is_allowed = in_array(
4109
+				$query_param_type,
4110
+				[0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4111
+				true
4112
+			);
4113
+			if ($field_is_allowed) {
4114
+				return;
4115
+			}
4116
+			throw new EE_Error(
4117
+				sprintf(
4118
+					esc_html__(
4119
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4120
+						"event_espresso"
4121
+					),
4122
+					$query_param,
4123
+					get_class($this),
4124
+					$query_param_type,
4125
+					$original_query_param
4126
+				)
4127
+			);
4128
+		}
4129
+		// check if this is a special logic query param
4130
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4131
+			$operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4132
+			if ($operator_is_allowed) {
4133
+				return;
4134
+			}
4135
+			throw new EE_Error(
4136
+				sprintf(
4137
+					esc_html__(
4138
+						'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4139
+						'event_espresso'
4140
+					),
4141
+					implode('", "', $this->_logic_query_param_keys),
4142
+					$query_param,
4143
+					get_class($this),
4144
+					'<br />',
4145
+					"\t"
4146
+					. ' $passed_in_query_info = <pre>'
4147
+					. print_r($passed_in_query_info, true)
4148
+					. '</pre>'
4149
+					. "\n\t"
4150
+					. ' $query_param_type = '
4151
+					. $query_param_type
4152
+					. "\n\t"
4153
+					. ' $original_query_param = '
4154
+					. $original_query_param
4155
+				)
4156
+			);
4157
+		}
4158
+		// check if it's a custom selection
4159
+		if (
4160
+			$this->_custom_selections instanceof CustomSelects
4161
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4162
+		) {
4163
+			return;
4164
+		}
4165
+		// check if has a model name at the beginning
4166
+		// and
4167
+		// check if it's a field on a related model
4168
+		if (
4169
+			$this->extractJoinModelFromQueryParams(
4170
+				$passed_in_query_info,
4171
+				$query_param,
4172
+				$original_query_param,
4173
+				$query_param_type
4174
+			)
4175
+		) {
4176
+			return;
4177
+		}
4178
+
4179
+		// ok so $query_param didn't start with a model name
4180
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4181
+		// it's wack, that's what it is
4182
+		throw new EE_Error(
4183
+			sprintf(
4184
+				esc_html__(
4185
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4186
+					"event_espresso"
4187
+				),
4188
+				$query_param,
4189
+				get_class($this),
4190
+				$query_param_type,
4191
+				$original_query_param
4192
+			)
4193
+		);
4194
+	}
4195
+
4196
+
4197
+	/**
4198
+	 * Extracts any possible join model information from the provided possible_join_string.
4199
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4200
+	 * join
4201
+	 * parts that should be added to the query.
4202
+	 *
4203
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4204
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4205
+	 * @param null|string                 $original_query_param
4206
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4207
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4208
+	 *                                                           etc.)
4209
+	 * @return bool  returns true if a join was added and false if not.
4210
+	 * @throws EE_Error
4211
+	 */
4212
+	private function extractJoinModelFromQueryParams(
4213
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4214
+		$possible_join_string,
4215
+		$original_query_param,
4216
+		$query_parameter_type
4217
+	) {
4218
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4219
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4220
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4221
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4222
+				if ($possible_join_string === '') {
4223
+					// nothing left to $query_param
4224
+					// we should actually end in a field name, not a model like this!
4225
+					throw new EE_Error(
4226
+						sprintf(
4227
+							esc_html__(
4228
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4229
+								"event_espresso"
4230
+							),
4231
+							$possible_join_string,
4232
+							$query_parameter_type,
4233
+							get_class($this),
4234
+							$valid_related_model_name
4235
+						)
4236
+					);
4237
+				}
4238
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4239
+				$related_model_obj->_extract_related_model_info_from_query_param(
4240
+					$possible_join_string,
4241
+					$query_info_carrier,
4242
+					$query_parameter_type,
4243
+					$original_query_param
4244
+				);
4245
+				return true;
4246
+			}
4247
+			if ($possible_join_string === $valid_related_model_name) {
4248
+				$this->_add_join_to_model(
4249
+					$valid_related_model_name,
4250
+					$query_info_carrier,
4251
+					$original_query_param
4252
+				);
4253
+				return true;
4254
+			}
4255
+		}
4256
+		return false;
4257
+	}
4258
+
4259
+
4260
+	/**
4261
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4262
+	 *
4263
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4264
+	 * @throws EE_Error
4265
+	 */
4266
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4267
+	{
4268
+		if (
4269
+			$this->_custom_selections instanceof CustomSelects
4270
+			&& (
4271
+				$this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4272
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4273
+			)
4274
+		) {
4275
+			$original_selects = $this->_custom_selections->originalSelects();
4276
+			foreach ($original_selects as $alias => $select_configuration) {
4277
+				$this->extractJoinModelFromQueryParams(
4278
+					$query_info_carrier,
4279
+					$select_configuration[0],
4280
+					$select_configuration[0],
4281
+					'custom_selects'
4282
+				);
4283
+			}
4284
+		}
4285
+	}
4286
+
4287
+
4288
+	/**
4289
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4290
+	 * and store it on $passed_in_query_info
4291
+	 *
4292
+	 * @param string                      $model_name
4293
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4294
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4295
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4296
+	 *                                                          and are adding a join to 'Payment' with the original
4297
+	 *                                                          query param key
4298
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4299
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4300
+	 *                                                          Payment wants to add default query params so that it
4301
+	 *                                                          will know what models to prepend onto its default query
4302
+	 *                                                          params or in case it wants to rename tables (in case
4303
+	 *                                                          there are multiple joins to the same table)
4304
+	 * @return void
4305
+	 * @throws EE_Error
4306
+	 */
4307
+	private function _add_join_to_model(
4308
+		$model_name,
4309
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4310
+		$original_query_param
4311
+	) {
4312
+		$relation_obj         = $this->related_settings_for($model_name);
4313
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4314
+		// check if the relation is HABTM, because then we're essentially doing two joins
4315
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4316
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4317
+			$join_model_obj = $relation_obj->get_join_model();
4318
+			// replace the model specified with the join model for this relation chain, whi
4319
+			$relation_chain_to_join_model =
4320
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4321
+					$model_name,
4322
+					$join_model_obj->get_this_model_name(),
4323
+					$model_relation_chain
4324
+				);
4325
+			$passed_in_query_info->merge(
4326
+				new EE_Model_Query_Info_Carrier(
4327
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4328
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4329
+				)
4330
+			);
4331
+		}
4332
+		// now just join to the other table pointed to by the relation object, and add its data types
4333
+		$passed_in_query_info->merge(
4334
+			new EE_Model_Query_Info_Carrier(
4335
+				[$model_relation_chain => $model_name],
4336
+				$relation_obj->get_join_statement($model_relation_chain)
4337
+			)
4338
+		);
4339
+	}
4340
+
4341
+
4342
+	/**
4343
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4344
+	 *
4345
+	 * @param array $where_params @see
4346
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4347
+	 * @return string of SQL
4348
+	 * @throws EE_Error
4349
+	 */
4350
+	private function _construct_where_clause($where_params)
4351
+	{
4352
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4353
+		if ($SQL) {
4354
+			return " WHERE " . $SQL;
4355
+		}
4356
+		return '';
4357
+	}
4358
+
4359
+
4360
+	/**
4361
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4362
+	 * and should be passed HAVING parameters, not WHERE parameters
4363
+	 *
4364
+	 * @param array $having_params
4365
+	 * @return string
4366
+	 * @throws EE_Error
4367
+	 */
4368
+	private function _construct_having_clause($having_params)
4369
+	{
4370
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4371
+		if ($SQL) {
4372
+			return " HAVING " . $SQL;
4373
+		}
4374
+		return '';
4375
+	}
4376
+
4377
+
4378
+	/**
4379
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4380
+	 * Event_Meta.meta_value = 'foo'))"
4381
+	 *
4382
+	 * @param array  $where_params @see
4383
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4384
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4385
+	 * @return string of SQL
4386
+	 * @throws EE_Error
4387
+	 */
4388
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4389
+	{
4390
+		$where_clauses = [];
4391
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4392
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4393
+			if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4394
+				switch ($query_param) {
4395
+					case 'not':
4396
+					case 'NOT':
4397
+						$where_clauses[] = "! ("
4398
+										   . $this->_construct_condition_clause_recursive(
4399
+											   $op_and_value_or_sub_condition,
4400
+											   $glue
4401
+										   )
4402
+										   . ")";
4403
+						break;
4404
+					case 'and':
4405
+					case 'AND':
4406
+						$where_clauses[] = " ("
4407
+										   . $this->_construct_condition_clause_recursive(
4408
+											   $op_and_value_or_sub_condition,
4409
+											   ' AND '
4410
+										   )
4411
+										   . ")";
4412
+						break;
4413
+					case 'or':
4414
+					case 'OR':
4415
+						$where_clauses[] = " ("
4416
+										   . $this->_construct_condition_clause_recursive(
4417
+											   $op_and_value_or_sub_condition,
4418
+											   ' OR '
4419
+										   )
4420
+										   . ")";
4421
+						break;
4422
+				}
4423
+			} else {
4424
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4425
+				// if it's not a normal field, maybe it's a custom selection?
4426
+				if (! $field_obj) {
4427
+					if ($this->_custom_selections instanceof CustomSelects) {
4428
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4429
+					} else {
4430
+						throw new EE_Error(
4431
+							sprintf(
4432
+								esc_html__(
4433
+									"%s is neither a valid model field name, nor a custom selection",
4434
+									"event_espresso"
4435
+								),
4436
+								$query_param
4437
+							)
4438
+						);
4439
+					}
4440
+				}
4441
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4442
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4443
+			}
4444
+		}
4445
+		return $where_clauses
4446
+			? implode($glue, $where_clauses)
4447
+			: '';
4448
+	}
4449
+
4450
+
4451
+	/**
4452
+	 * Takes the input parameter and extract the table name (alias) and column name
4453
+	 *
4454
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4455
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4456
+	 * @throws EE_Error
4457
+	 */
4458
+	private function _deduce_column_name_from_query_param($query_param)
4459
+	{
4460
+		$field = $this->_deduce_field_from_query_param($query_param);
4461
+		if ($field) {
4462
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4463
+				$field->get_model_name(),
4464
+				$query_param
4465
+			);
4466
+			return $table_alias_prefix . $field->get_qualified_column();
4467
+		}
4468
+		if (
4469
+			$this->_custom_selections instanceof CustomSelects
4470
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4471
+		) {
4472
+			// maybe it's custom selection item?
4473
+			// if so, just use it as the "column name"
4474
+			return $query_param;
4475
+		}
4476
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4477
+			? implode(',', $this->_custom_selections->columnAliases())
4478
+			: '';
4479
+		throw new EE_Error(
4480
+			sprintf(
4481
+				esc_html__(
4482
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4483
+					"event_espresso"
4484
+				),
4485
+				$query_param,
4486
+				$custom_select_aliases
4487
+			)
4488
+		);
4489
+	}
4490
+
4491
+
4492
+	/**
4493
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4494
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4495
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4496
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4497
+	 *
4498
+	 * @param string $condition_query_param_key
4499
+	 * @return string
4500
+	 */
4501
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4502
+	{
4503
+		$pos_of_star = strpos($condition_query_param_key, '*');
4504
+		if ($pos_of_star === false) {
4505
+			return $condition_query_param_key;
4506
+		}
4507
+		return substr($condition_query_param_key, 0, $pos_of_star);
4508
+	}
4509
+
4510
+
4511
+	/**
4512
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4513
+	 *
4514
+	 * @param array|string               $op_and_value
4515
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4516
+	 * @return string
4517
+	 * @throws EE_Error
4518
+	 */
4519
+	private function _construct_op_and_value($op_and_value, $field_obj)
4520
+	{
4521
+		$operator = '=';
4522
+		$value    = $op_and_value;
4523
+		if (is_array($op_and_value)) {
4524
+			$operator = isset($op_and_value[0])
4525
+				? $this->_prepare_operator_for_sql($op_and_value[0])
4526
+				: null;
4527
+			if (! $operator) {
4528
+				$php_array_like_string = [];
4529
+				foreach ($op_and_value as $key => $value) {
4530
+					$php_array_like_string[] = "$key=>$value";
4531
+				}
4532
+				throw new EE_Error(
4533
+					sprintf(
4534
+						esc_html__(
4535
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4536
+							"event_espresso"
4537
+						),
4538
+						implode(",", $php_array_like_string)
4539
+					)
4540
+				);
4541
+			}
4542
+			$value = $op_and_value[1] ?? null;
4543
+		}
4544
+
4545
+		// check to see if the value is actually another field
4546
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4547
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4548
+		}
4549
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4550
+			// in this case, the value should be an array, or at least a comma-separated list
4551
+			// it will need to handle a little differently
4552
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4553
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4554
+			return $operator . SP . $cleaned_value;
4555
+		}
4556
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4557
+			// the value should be an array with count of two.
4558
+			if (count($value) !== 2) {
4559
+				throw new EE_Error(
4560
+					sprintf(
4561
+						esc_html__(
4562
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4563
+							'event_espresso'
4564
+						),
4565
+						"BETWEEN"
4566
+					)
4567
+				);
4568
+			}
4569
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4570
+			return $operator . SP . $cleaned_value;
4571
+		}
4572
+		if (in_array($operator, $this->valid_null_style_operators())) {
4573
+			if ($value !== null) {
4574
+				throw new EE_Error(
4575
+					sprintf(
4576
+						esc_html__(
4577
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4578
+							"event_espresso"
4579
+						),
4580
+						$value,
4581
+						$operator
4582
+					)
4583
+				);
4584
+			}
4585
+			return $operator;
4586
+		}
4587
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4588
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4589
+			// remove other junk. So just treat it as a string.
4590
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4591
+		}
4592
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4593
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4594
+		}
4595
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4596
+			throw new EE_Error(
4597
+				sprintf(
4598
+					esc_html__(
4599
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4600
+						'event_espresso'
4601
+					),
4602
+					$operator,
4603
+					$operator
4604
+				)
4605
+			);
4606
+		}
4607
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4608
+			throw new EE_Error(
4609
+				sprintf(
4610
+					esc_html__(
4611
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4612
+						'event_espresso'
4613
+					),
4614
+					$operator,
4615
+					$operator
4616
+				)
4617
+			);
4618
+		}
4619
+		throw new EE_Error(
4620
+			sprintf(
4621
+				esc_html__(
4622
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4623
+					"event_espresso"
4624
+				),
4625
+				http_build_query($op_and_value)
4626
+			)
4627
+		);
4628
+	}
4629
+
4630
+
4631
+	/**
4632
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4633
+	 *
4634
+	 * @param array                      $values
4635
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4636
+	 *                                              '%s'
4637
+	 * @return string
4638
+	 * @throws EE_Error
4639
+	 */
4640
+	public function _construct_between_value($values, $field_obj)
4641
+	{
4642
+		$cleaned_values = [];
4643
+		foreach ($values as $value) {
4644
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4645
+		}
4646
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4647
+	}
4648
+
4649
+
4650
+	/**
4651
+	 * Takes an array or a comma-separated list of $values and cleans them
4652
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4653
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4654
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4655
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4656
+	 *
4657
+	 * @param mixed                      $values    array or comma-separated string
4658
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4659
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4660
+	 * @throws EE_Error
4661
+	 */
4662
+	public function _construct_in_value($values, $field_obj)
4663
+	{
4664
+		$prepped = [];
4665
+		// check if the value is a CSV list
4666
+		if (is_string($values)) {
4667
+			// in which case, turn it into an array
4668
+			$values = explode(',', $values);
4669
+		}
4670
+		// make sure we only have one of each value in the list
4671
+		$values = array_unique($values);
4672
+		foreach ($values as $value) {
4673
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4674
+		}
4675
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4676
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4677
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4678
+		if (empty($prepped)) {
4679
+			$all_fields  = $this->field_settings();
4680
+			$first_field = reset($all_fields);
4681
+			$main_table  = $this->_get_main_table();
4682
+			$prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4683
+		}
4684
+		return '(' . implode(',', $prepped) . ')';
4685
+	}
4686
+
4687
+
4688
+	/**
4689
+	 * @param mixed                      $value
4690
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4691
+	 * @return false|null|string
4692
+	 * @throws EE_Error
4693
+	 */
4694
+	private function _wpdb_prepare_using_field($value, $field_obj)
4695
+	{
4696
+		/** @type WPDB $wpdb */
4697
+		global $wpdb;
4698
+		if ($field_obj instanceof EE_Model_Field_Base) {
4699
+			return $wpdb->prepare(
4700
+				$field_obj->get_wpdb_data_type(),
4701
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4702
+			);
4703
+		} //$field_obj should really just be a data type
4704
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4705
+			throw new EE_Error(
4706
+				sprintf(
4707
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4708
+					$field_obj,
4709
+					implode(",", $this->_valid_wpdb_data_types)
4710
+				)
4711
+			);
4712
+		}
4713
+		return $wpdb->prepare($field_obj, $value);
4714
+	}
4715
+
4716
+
4717
+	/**
4718
+	 * Takes the input parameter and finds the model field that it indicates.
4719
+	 *
4720
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4721
+	 * @return EE_Model_Field_Base
4722
+	 * @throws EE_Error
4723
+	 */
4724
+	protected function _deduce_field_from_query_param($query_param_name)
4725
+	{
4726
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4727
+		// which will help us find the database table and column
4728
+		$query_param_parts = explode(".", $query_param_name);
4729
+		if (empty($query_param_parts)) {
4730
+			throw new EE_Error(
4731
+				sprintf(
4732
+					esc_html__(
4733
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4734
+						'event_espresso'
4735
+					),
4736
+					$query_param_name
4737
+				)
4738
+			);
4739
+		}
4740
+		$number_of_parts       = count($query_param_parts);
4741
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4742
+		if ($number_of_parts === 1) {
4743
+			$field_name = $last_query_param_part;
4744
+			$model_obj  = $this;
4745
+		} else {// $number_of_parts >= 2
4746
+			// the last part is the column name, and there are only 2parts. therefore...
4747
+			$field_name = $last_query_param_part;
4748
+			$model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4749
+		}
4750
+		try {
4751
+			return $model_obj->field_settings_for($field_name);
4752
+		} catch (EE_Error $e) {
4753
+			return null;
4754
+		}
4755
+	}
4756
+
4757
+
4758
+	/**
4759
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4760
+	 * alias and column which corresponds to it
4761
+	 *
4762
+	 * @param string $field_name
4763
+	 * @return string
4764
+	 * @throws EE_Error
4765
+	 */
4766
+	public function _get_qualified_column_for_field($field_name)
4767
+	{
4768
+		$all_fields = $this->field_settings();
4769
+		$field      = $all_fields[ $field_name ] ?? false;
4770
+		if ($field) {
4771
+			return $field->get_qualified_column();
4772
+		}
4773
+		throw new EE_Error(
4774
+			sprintf(
4775
+				esc_html__(
4776
+					"There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4777
+					'event_espresso'
4778
+				),
4779
+				$field_name,
4780
+				get_class($this)
4781
+			)
4782
+		);
4783
+	}
4784
+
4785
+
4786
+	/**
4787
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4788
+	 * Example usage:
4789
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4790
+	 *      array(),
4791
+	 *      ARRAY_A,
4792
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4793
+	 *  );
4794
+	 * is equivalent to
4795
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4796
+	 * and
4797
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4798
+	 *      array(
4799
+	 *          array(
4800
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4801
+	 *          ),
4802
+	 *          ARRAY_A,
4803
+	 *          implode(
4804
+	 *              ', ',
4805
+	 *              array_merge(
4806
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4807
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4808
+	 *              )
4809
+	 *          )
4810
+	 *      )
4811
+	 *  );
4812
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4813
+	 *
4814
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4815
+	 *                                            and the one whose fields you are selecting for example: when querying
4816
+	 *                                            tickets model and selecting fields from the tickets model you would
4817
+	 *                                            leave this parameter empty, because no models are needed to join
4818
+	 *                                            between the queried model and the selected one. Likewise when
4819
+	 *                                            querying the datetime model and selecting fields from the tickets
4820
+	 *                                            model, it would also be left empty, because there is a direct
4821
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4822
+	 *                                            them together. However, when querying from the event model and
4823
+	 *                                            selecting fields from the ticket model, you should provide the string
4824
+	 *                                            'Datetime', indicating that the event model must first join to the
4825
+	 *                                            datetime model in order to find its relation to ticket model.
4826
+	 *                                            Also, when querying from the venue model and selecting fields from
4827
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4828
+	 *                                            indicating you need to join the venue model to the event model,
4829
+	 *                                            to the datetime model, in order to find its relation to the ticket
4830
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4831
+	 *                                            the models' tables qualified columns
4832
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4833
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4834
+	 *                                            qualified column names
4835
+	 * @return array|string
4836
+	 */
4837
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4838
+	{
4839
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4840
+				? ''
4841
+				: '__');
4842
+		$qualified_columns = [];
4843
+		foreach ($this->field_settings() as $field_name => $field) {
4844
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4845
+		}
4846
+		return $return_string
4847
+			? implode(', ', $qualified_columns)
4848
+			: $qualified_columns;
4849
+	}
4850
+
4851
+
4852
+	/**
4853
+	 * constructs the select use on special limit joins
4854
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4855
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4856
+	 * (as that is typically where the limits would be set).
4857
+	 *
4858
+	 * @param string       $table_alias The table the select is being built for
4859
+	 * @param mixed|string $limit       The limit for this select
4860
+	 * @return string                The final select join element for the query.
4861
+	 * @throws EE_Error
4862
+	 * @throws EE_Error
4863
+	 */
4864
+	public function _construct_limit_join_select($table_alias, $limit)
4865
+	{
4866
+		$SQL = '';
4867
+		foreach ($this->_tables as $table_obj) {
4868
+			if ($table_obj instanceof EE_Primary_Table) {
4869
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4870
+					? $table_obj->get_select_join_limit($limit)
4871
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4872
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4873
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4874
+					? $table_obj->get_select_join_limit_join($limit)
4875
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4876
+			}
4877
+		}
4878
+		return $SQL;
4879
+	}
4880
+
4881
+
4882
+	/**
4883
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4884
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4885
+	 *
4886
+	 * @return string SQL
4887
+	 * @throws EE_Error
4888
+	 */
4889
+	public function _construct_internal_join()
4890
+	{
4891
+		$SQL = $this->_get_main_table()->get_table_sql();
4892
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4893
+		return $SQL;
4894
+	}
4895
+
4896
+
4897
+	/**
4898
+	 * Constructs the SQL for joining all the tables on this model.
4899
+	 * Normally $alias should be the primary table's alias, but in cases where
4900
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4901
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4902
+	 * alias, this will construct SQL like:
4903
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4904
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4905
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4906
+	 *
4907
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4908
+	 * @return string
4909
+	 * @throws EE_Error
4910
+	 * @throws EE_Error
4911
+	 */
4912
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4913
+	{
4914
+		$SQL               = '';
4915
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4916
+		foreach ($this->_tables as $table_obj) {
4917
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4918
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4919
+					// so we're joining to this table, meaning the table is already in
4920
+					// the FROM statement, BUT the primary table isn't. So we want
4921
+					// to add the inverse join sql
4922
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4923
+				} else {
4924
+					// just add a regular JOIN to this table from the primary table
4925
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4926
+				}
4927
+			}// if it's a primary table, dont add any SQL. it should already be in the FROM statement
4928
+		}
4929
+		return $SQL;
4930
+	}
4931
+
4932
+
4933
+	/**
4934
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4935
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4936
+	 * their data type (eg, '%s', '%d', etc)
4937
+	 *
4938
+	 * @return array
4939
+	 */
4940
+	public function _get_data_types()
4941
+	{
4942
+		$data_types = [];
4943
+		foreach ($this->field_settings() as $field_obj) {
4944
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4945
+			/** @var $field_obj EE_Model_Field_Base */
4946
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4947
+		}
4948
+		return $data_types;
4949
+	}
4950
+
4951
+
4952
+	/**
4953
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4954
+	 *
4955
+	 * @param string $model_name
4956
+	 * @return EEM_Base
4957
+	 * @throws EE_Error
4958
+	 */
4959
+	public function get_related_model_obj($model_name)
4960
+	{
4961
+		$model_classname = "EEM_" . $model_name;
4962
+		if (! class_exists($model_classname)) {
4963
+			throw new EE_Error(
4964
+				sprintf(
4965
+					esc_html__(
4966
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4967
+						'event_espresso'
4968
+					),
4969
+					$model_name,
4970
+					$model_classname
4971
+				)
4972
+			);
4973
+		}
4974
+		return call_user_func($model_classname . "::instance");
4975
+	}
4976
+
4977
+
4978
+	/**
4979
+	 * Returns the array of EE_ModelRelations for this model.
4980
+	 *
4981
+	 * @return EE_Model_Relation_Base[]
4982
+	 */
4983
+	public function relation_settings()
4984
+	{
4985
+		return $this->_model_relations;
4986
+	}
4987
+
4988
+
4989
+	/**
4990
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4991
+	 * because without THOSE models, this model probably doesn't have much purpose.
4992
+	 * (Eg, without an event, datetimes have little purpose.)
4993
+	 *
4994
+	 * @return EE_Belongs_To_Relation[]
4995
+	 */
4996
+	public function belongs_to_relations()
4997
+	{
4998
+		$belongs_to_relations = [];
4999
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
5000
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
5001
+				$belongs_to_relations[ $model_name ] = $relation_obj;
5002
+			}
5003
+		}
5004
+		return $belongs_to_relations;
5005
+	}
5006
+
5007
+
5008
+	/**
5009
+	 * Returns the specified EE_Model_Relation, or throws an exception
5010
+	 *
5011
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
5012
+	 * @return EE_Model_Relation_Base
5013
+	 * @throws EE_Error
5014
+	 */
5015
+	public function related_settings_for($relation_name)
5016
+	{
5017
+		$relatedModels = $this->relation_settings();
5018
+		if (! array_key_exists($relation_name, $relatedModels)) {
5019
+			throw new EE_Error(
5020
+				sprintf(
5021
+					esc_html__(
5022
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
5023
+						'event_espresso'
5024
+					),
5025
+					$relation_name,
5026
+					$this->_get_class_name(),
5027
+					implode(', ', array_keys($relatedModels))
5028
+				)
5029
+			);
5030
+		}
5031
+		return $relatedModels[ $relation_name ];
5032
+	}
5033
+
5034
+
5035
+	/**
5036
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
5037
+	 * fields
5038
+	 *
5039
+	 * @param string  $fieldName
5040
+	 * @param boolean $include_db_only_fields
5041
+	 * @return EE_Model_Field_Base
5042
+	 * @throws EE_Error
5043
+	 */
5044
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
5045
+	{
5046
+		$fieldSettings = $this->field_settings($include_db_only_fields);
5047
+		if (! array_key_exists($fieldName, $fieldSettings)) {
5048
+			throw new EE_Error(
5049
+				sprintf(
5050
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
5051
+					$fieldName,
5052
+					get_class($this)
5053
+				)
5054
+			);
5055
+		}
5056
+		return $fieldSettings[ $fieldName ];
5057
+	}
5058
+
5059
+
5060
+	/**
5061
+	 * Checks if this field exists on this model
5062
+	 *
5063
+	 * @param string $fieldName a key in the model's _field_settings array
5064
+	 * @return boolean
5065
+	 */
5066
+	public function has_field($fieldName)
5067
+	{
5068
+		$fieldSettings = $this->field_settings(true);
5069
+		if (isset($fieldSettings[ $fieldName ])) {
5070
+			return true;
5071
+		}
5072
+		return false;
5073
+	}
5074
+
5075
+
5076
+	/**
5077
+	 * Returns whether or not this model has a relation to the specified model
5078
+	 *
5079
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
5080
+	 * @return boolean
5081
+	 */
5082
+	public function has_relation($relation_name)
5083
+	{
5084
+		$relations = $this->relation_settings();
5085
+		if (isset($relations[ $relation_name ])) {
5086
+			return true;
5087
+		}
5088
+		return false;
5089
+	}
5090
+
5091
+
5092
+	/**
5093
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5094
+	 * Eg, on EE_Answer that would be ANS_ID field object
5095
+	 *
5096
+	 * @param $field_obj
5097
+	 * @return boolean
5098
+	 */
5099
+	public function is_primary_key_field($field_obj): bool
5100
+	{
5101
+		return $field_obj instanceof EE_Primary_Key_Field_Base;
5102
+	}
5103
+
5104
+
5105
+	/**
5106
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5107
+	 * Eg, on EE_Answer that would be ANS_ID field object
5108
+	 *
5109
+	 * @return EE_Primary_Key_Field_Base
5110
+	 * @throws EE_Error
5111
+	 */
5112
+	public function get_primary_key_field()
5113
+	{
5114
+		if ($this->_primary_key_field === null) {
5115
+			foreach ($this->field_settings(true) as $field_obj) {
5116
+				if ($this->is_primary_key_field($field_obj)) {
5117
+					$this->_primary_key_field = $field_obj;
5118
+					break;
5119
+				}
5120
+			}
5121
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5122
+				throw new EE_Error(
5123
+					sprintf(
5124
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5125
+						get_class($this)
5126
+					)
5127
+				);
5128
+			}
5129
+		}
5130
+		return $this->_primary_key_field;
5131
+	}
5132
+
5133
+
5134
+	/**
5135
+	 * Returns whether or not not there is a primary key on this model.
5136
+	 * Internally does some caching.
5137
+	 *
5138
+	 * @return boolean
5139
+	 */
5140
+	public function has_primary_key_field()
5141
+	{
5142
+		if ($this->_has_primary_key_field === null) {
5143
+			try {
5144
+				$this->get_primary_key_field();
5145
+				$this->_has_primary_key_field = true;
5146
+			} catch (EE_Error $e) {
5147
+				$this->_has_primary_key_field = false;
5148
+			}
5149
+		}
5150
+		return $this->_has_primary_key_field;
5151
+	}
5152
+
5153
+
5154
+	/**
5155
+	 * Finds the first field of type $field_class_name.
5156
+	 *
5157
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5158
+	 *                                 EE_Foreign_Key_Field, etc
5159
+	 * @return EE_Model_Field_Base or null if none is found
5160
+	 */
5161
+	public function get_a_field_of_type($field_class_name)
5162
+	{
5163
+		foreach ($this->field_settings() as $field) {
5164
+			if ($field instanceof $field_class_name) {
5165
+				return $field;
5166
+			}
5167
+		}
5168
+		return null;
5169
+	}
5170
+
5171
+
5172
+	/**
5173
+	 * Gets a foreign key field pointing to model.
5174
+	 *
5175
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5176
+	 * @return EE_Foreign_Key_Field_Base
5177
+	 * @throws EE_Error
5178
+	 */
5179
+	public function get_foreign_key_to($model_name)
5180
+	{
5181
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5182
+			foreach ($this->field_settings() as $field) {
5183
+				if (
5184
+					$field instanceof EE_Foreign_Key_Field_Base
5185
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5186
+				) {
5187
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5188
+					break;
5189
+				}
5190
+			}
5191
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5192
+				throw new EE_Error(
5193
+					sprintf(
5194
+						esc_html__(
5195
+							"There is no foreign key field pointing to model %s on model %s",
5196
+							'event_espresso'
5197
+						),
5198
+						$model_name,
5199
+						get_class($this)
5200
+					)
5201
+				);
5202
+			}
5203
+		}
5204
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5205
+	}
5206
+
5207
+
5208
+	/**
5209
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5210
+	 *
5211
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5212
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5213
+	 *                            Either one works
5214
+	 * @return string
5215
+	 */
5216
+	public function get_table_for_alias($table_alias)
5217
+	{
5218
+		$table_alias_sans_model_relation_chain_prefix =
5219
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5220
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5221
+	}
5222
+
5223
+
5224
+	/**
5225
+	 * Returns a flat array of all field son this model, instead of organizing them
5226
+	 * by table_alias as they are in the constructor.
5227
+	 *
5228
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5229
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5230
+	 */
5231
+	public function field_settings($include_db_only_fields = false)
5232
+	{
5233
+		if ($include_db_only_fields) {
5234
+			if ($this->_cached_fields === null) {
5235
+				$this->_cached_fields = [];
5236
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5237
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5238
+						$this->_cached_fields[ $field_name ] = $field_obj;
5239
+					}
5240
+				}
5241
+			}
5242
+			return $this->_cached_fields;
5243
+		}
5244
+		if ($this->_cached_fields_non_db_only === null) {
5245
+			$this->_cached_fields_non_db_only = [];
5246
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5247
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5248
+					/** @var $field_obj EE_Model_Field_Base */
5249
+					if (! $field_obj->is_db_only_field()) {
5250
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5251
+					}
5252
+				}
5253
+			}
5254
+		}
5255
+		return $this->_cached_fields_non_db_only;
5256
+	}
5257
+
5258
+
5259
+	/**
5260
+	 *        cycle though array of attendees and create objects out of each item
5261
+	 *
5262
+	 * @access        private
5263
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5264
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5265
+	 *                           numerically indexed)
5266
+	 * @throws EE_Error
5267
+	 * @throws ReflectionException
5268
+	 */
5269
+	protected function _create_objects($rows = [])
5270
+	{
5271
+		$array_of_objects = [];
5272
+		if (empty($rows)) {
5273
+			return [];
5274
+		}
5275
+		$count_if_model_has_no_primary_key = 0;
5276
+		$has_primary_key                   = $this->has_primary_key_field();
5277
+		$primary_key_field                 = $has_primary_key
5278
+			? $this->get_primary_key_field()
5279
+			: null;
5280
+		foreach ((array) $rows as $row) {
5281
+			if (empty($row)) {
5282
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5283
+				return [];
5284
+			}
5285
+			// check if we've already set this object in the results array,
5286
+			// in which case there's no need to process it further (again)
5287
+			if ($has_primary_key) {
5288
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5289
+					$row,
5290
+					$primary_key_field->get_qualified_column(),
5291
+					$primary_key_field->get_table_column()
5292
+				);
5293
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5294
+					continue;
5295
+				}
5296
+			}
5297
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5298
+			if (! $classInstance) {
5299
+				throw new EE_Error(
5300
+					sprintf(
5301
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5302
+						$this->get_this_model_name(),
5303
+						http_build_query($row)
5304
+					)
5305
+				);
5306
+			}
5307
+			// set the timezone on the instantiated objects
5308
+			$classInstance->set_timezone($this->_timezone);
5309
+			// make sure if there is any timezone setting present that we set the timezone for the object
5310
+			$key                      = $has_primary_key
5311
+				? $classInstance->ID()
5312
+				: $count_if_model_has_no_primary_key++;
5313
+			$array_of_objects[ $key ] = $classInstance;
5314
+			// also, for all the relations of type BelongsTo, see if we can cache
5315
+			// those related models
5316
+			// (we could do this for other relations too, but if there are conditions
5317
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5318
+			// so it requires a little more thought than just caching them immediately...)
5319
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5320
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5321
+					// check if this model's INFO is present. If so, cache it on the model
5322
+					$other_model           = $relation_obj->get_other_model();
5323
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5324
+					// if we managed to make a model object from the results, cache it on the main model object
5325
+					if ($other_model_obj_maybe) {
5326
+						// set timezone on these other model objects if they are present
5327
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5328
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5329
+					}
5330
+				}
5331
+			}
5332
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5333
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5334
+			// the field in the CustomSelects object
5335
+			if ($this->_custom_selections instanceof CustomSelects) {
5336
+				$classInstance->setCustomSelectsValues(
5337
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5338
+				);
5339
+			}
5340
+		}
5341
+		return $array_of_objects;
5342
+	}
5343
+
5344
+
5345
+	/**
5346
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5347
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5348
+	 *
5349
+	 * @param array $db_results_row
5350
+	 * @return array
5351
+	 */
5352
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5353
+	{
5354
+		$results = [];
5355
+		if ($this->_custom_selections instanceof CustomSelects) {
5356
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5357
+				if (isset($db_results_row[ $alias ])) {
5358
+					$results[ $alias ] = $this->convertValueToDataType(
5359
+						$db_results_row[ $alias ],
5360
+						$this->_custom_selections->getDataTypeForAlias($alias)
5361
+					);
5362
+				}
5363
+			}
5364
+		}
5365
+		return $results;
5366
+	}
5367
+
5368
+
5369
+	/**
5370
+	 * This will set the value for the given alias
5371
+	 *
5372
+	 * @param string $value
5373
+	 * @param string $datatype (one of %d, %s, %f)
5374
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5375
+	 */
5376
+	protected function convertValueToDataType($value, $datatype)
5377
+	{
5378
+		switch ($datatype) {
5379
+			case '%f':
5380
+				return (float) $value;
5381
+			case '%d':
5382
+				return (int) $value;
5383
+			default:
5384
+				return (string) $value;
5385
+		}
5386
+	}
5387
+
5388
+
5389
+	/**
5390
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5391
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5392
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5393
+	 * object (as set in the model_field!).
5394
+	 *
5395
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5396
+	 * @throws EE_Error
5397
+	 * @throws ReflectionException
5398
+	 */
5399
+	public function create_default_object()
5400
+	{
5401
+		$this_model_fields_and_values = [];
5402
+		// setup the row using default values;
5403
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5404
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5405
+		}
5406
+		$className = $this->_get_class_name();
5407
+		return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5408
+	}
5409
+
5410
+
5411
+	/**
5412
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5413
+	 *                             or an stdClass where each property is the name of a column,
5414
+	 * @return EE_Base_Class
5415
+	 * @throws EE_Error
5416
+	 * @throws ReflectionException
5417
+	 */
5418
+	public function instantiate_class_from_array_or_object($cols_n_values)
5419
+	{
5420
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5421
+			$cols_n_values = get_object_vars($cols_n_values);
5422
+		}
5423
+		$primary_key = null;
5424
+		// make sure the array only has keys that are fields/columns on this model
5425
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5426
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5427
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5428
+		}
5429
+		$className = $this->_get_class_name();
5430
+		// check we actually found results that we can use to build our model object
5431
+		// if not, return null
5432
+		if ($this->has_primary_key_field()) {
5433
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5434
+				return null;
5435
+			}
5436
+		} elseif ($this->unique_indexes()) {
5437
+			$first_column = reset($this_model_fields_n_values);
5438
+			if (empty($first_column)) {
5439
+				return null;
5440
+			}
5441
+		}
5442
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5443
+		if ($primary_key) {
5444
+			$classInstance = $this->get_from_entity_map($primary_key);
5445
+			if (! $classInstance) {
5446
+				$classInstance = EE_Registry::instance()
5447
+											->load_class(
5448
+												$className,
5449
+												[$this_model_fields_n_values, $this->_timezone],
5450
+												true,
5451
+												false
5452
+											);
5453
+				// add this new object to the entity map
5454
+				$classInstance = $this->add_to_entity_map($classInstance);
5455
+			}
5456
+		} else {
5457
+			$classInstance = EE_Registry::instance()->load_class(
5458
+				$className,
5459
+				[$this_model_fields_n_values, $this->_timezone],
5460
+				true,
5461
+				false
5462
+			);
5463
+		}
5464
+		return $classInstance;
5465
+	}
5466
+
5467
+
5468
+	/**
5469
+	 * Gets the model object from the  entity map if it exists
5470
+	 *
5471
+	 * @param int|string $id the ID of the model object
5472
+	 * @return EE_Base_Class
5473
+	 */
5474
+	public function get_from_entity_map($id)
5475
+	{
5476
+		return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5477
+	}
5478
+
5479
+
5480
+	/**
5481
+	 * add_to_entity_map
5482
+	 * Adds the object to the model's entity mappings
5483
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5484
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5485
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5486
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5487
+	 *        then this method should be called immediately after the update query
5488
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5489
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5490
+	 *
5491
+	 * @param EE_Base_Class $object
5492
+	 * @return EE_Base_Class
5493
+	 * @throws EE_Error
5494
+	 * @throws ReflectionException
5495
+	 */
5496
+	public function add_to_entity_map(EE_Base_Class $object)
5497
+	{
5498
+		$className = $this->_get_class_name();
5499
+		if (! $object instanceof $className) {
5500
+			throw new EE_Error(
5501
+				sprintf(
5502
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5503
+					is_object($object)
5504
+						? get_class($object)
5505
+						: $object,
5506
+					$className
5507
+				)
5508
+			);
5509
+		}
5510
+
5511
+		if (! $object->ID()) {
5512
+			throw new EE_Error(
5513
+				sprintf(
5514
+					esc_html__(
5515
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5516
+						"event_espresso"
5517
+					),
5518
+					get_class($this)
5519
+				)
5520
+			);
5521
+		}
5522
+		// double check it's not already there
5523
+		$classInstance = $this->get_from_entity_map($object->ID());
5524
+		if ($classInstance) {
5525
+			return $classInstance;
5526
+		}
5527
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5528
+		return $object;
5529
+	}
5530
+
5531
+
5532
+	/**
5533
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5534
+	 * if no identifier is provided, then the entire entity map is emptied
5535
+	 *
5536
+	 * @param int|string $id the ID of the model object
5537
+	 * @return boolean
5538
+	 */
5539
+	public function clear_entity_map($id = null)
5540
+	{
5541
+		if (empty($id)) {
5542
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5543
+			return true;
5544
+		}
5545
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5546
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5547
+			return true;
5548
+		}
5549
+		return false;
5550
+	}
5551
+
5552
+
5553
+	/**
5554
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5555
+	 * Given an array where keys are column (or column alias) names and values,
5556
+	 * returns an array of their corresponding field names and database values
5557
+	 *
5558
+	 * @param array $cols_n_values
5559
+	 * @return array
5560
+	 * @throws EE_Error
5561
+	 * @throws ReflectionException
5562
+	 */
5563
+	public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5564
+	{
5565
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5566
+	}
5567
+
5568
+
5569
+	/**
5570
+	 * _deduce_fields_n_values_from_cols_n_values
5571
+	 * Given an array where keys are column (or column alias) names and values,
5572
+	 * returns an array of their corresponding field names and database values
5573
+	 *
5574
+	 * @param array|stdClass $cols_n_values
5575
+	 * @return array
5576
+	 * @throws EE_Error
5577
+	 * @throws ReflectionException
5578
+	 */
5579
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5580
+	{
5581
+		if ($cols_n_values instanceof stdClass) {
5582
+			$cols_n_values = get_object_vars($cols_n_values);
5583
+		}
5584
+		$this_model_fields_n_values = [];
5585
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5586
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5587
+				$cols_n_values,
5588
+				$table_obj->get_fully_qualified_pk_column(),
5589
+				$table_obj->get_pk_column()
5590
+			);
5591
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5592
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5593
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5594
+					if (! $field_obj->is_db_only_field()) {
5595
+						// prepare field as if its coming from db
5596
+						$prepared_value                            =
5597
+							$field_obj->prepare_for_set($field_obj->get_default_value());
5598
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5599
+					}
5600
+				}
5601
+			} else {
5602
+				// the table's rows existed. Use their values
5603
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5604
+					if (! $field_obj->is_db_only_field()) {
5605
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5606
+							$cols_n_values,
5607
+							$field_obj->get_qualified_column(),
5608
+							$field_obj->get_table_column()
5609
+						);
5610
+					}
5611
+				}
5612
+			}
5613
+		}
5614
+		return $this_model_fields_n_values;
5615
+	}
5616
+
5617
+
5618
+	/**
5619
+	 * @param $cols_n_values
5620
+	 * @param $qualified_column
5621
+	 * @param $regular_column
5622
+	 * @return null
5623
+	 * @throws EE_Error
5624
+	 * @throws ReflectionException
5625
+	 */
5626
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5627
+	{
5628
+		$value = null;
5629
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5630
+		// does the field on the model relate to this column retrieved from the db?
5631
+		// or is it a db-only field? (not relating to the model)
5632
+		if (isset($cols_n_values[ $qualified_column ])) {
5633
+			$value = $cols_n_values[ $qualified_column ];
5634
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5635
+			$value = $cols_n_values[ $regular_column ];
5636
+		} elseif (! empty($this->foreign_key_aliases)) {
5637
+			// no PK?  ok check if there is a foreign key alias set for this table
5638
+			// then check if that alias exists in the incoming data
5639
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5640
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5641
+				if ($PK_column === $qualified_column && !empty($cols_n_values[ $FK_alias ])) {
5642
+					$value = $cols_n_values[ $FK_alias ];
5643
+					[$pk_class] = explode('.', $PK_column);
5644
+					$pk_model_name = "EEM_{$pk_class}";
5645
+					/** @var EEM_Base $pk_model */
5646
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5647
+					if ($pk_model instanceof EEM_Base) {
5648
+						// make sure object is pulled from db and added to entity map
5649
+						$pk_model->get_one_by_ID($value);
5650
+					}
5651
+					break;
5652
+				}
5653
+			}
5654
+		}
5655
+		return $value;
5656
+	}
5657
+
5658
+
5659
+	/**
5660
+	 * refresh_entity_map_from_db
5661
+	 * Makes sure the model object in the entity map at $id assumes the values
5662
+	 * of the database (opposite of EE_base_Class::save())
5663
+	 *
5664
+	 * @param int|string $id
5665
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5666
+	 * @throws EE_Error
5667
+	 * @throws ReflectionException
5668
+	 */
5669
+	public function refresh_entity_map_from_db($id)
5670
+	{
5671
+		$obj_in_map = $this->get_from_entity_map($id);
5672
+		if ($obj_in_map) {
5673
+			$wpdb_results = $this->_get_all_wpdb_results(
5674
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5675
+			);
5676
+			if ($wpdb_results && is_array($wpdb_results)) {
5677
+				$one_row = reset($wpdb_results);
5678
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5679
+					$obj_in_map->set_from_db($field_name, $db_value);
5680
+				}
5681
+				// clear the cache of related model objects
5682
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5683
+					$obj_in_map->clear_cache($relation_name, null, true);
5684
+				}
5685
+			}
5686
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5687
+			return $obj_in_map;
5688
+		}
5689
+		return $this->get_one_by_ID($id);
5690
+	}
5691
+
5692
+
5693
+	/**
5694
+	 * refresh_entity_map_with
5695
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5696
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5697
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5698
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5699
+	 *
5700
+	 * @param int|string    $id
5701
+	 * @param EE_Base_Class $replacing_model_obj
5702
+	 * @return EE_Base_Class
5703
+	 * @throws EE_Error
5704
+	 * @throws ReflectionException
5705
+	 */
5706
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5707
+	{
5708
+		$obj_in_map = $this->get_from_entity_map($id);
5709
+		if ($obj_in_map) {
5710
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5711
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5712
+					$obj_in_map->set($field_name, $value);
5713
+				}
5714
+				// make the model object in the entity map's cache match the $replacing_model_obj
5715
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5716
+					$obj_in_map->clear_cache($relation_name, null, true);
5717
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5718
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5719
+					}
5720
+				}
5721
+			}
5722
+			return $obj_in_map;
5723
+		}
5724
+		$this->add_to_entity_map($replacing_model_obj);
5725
+		return $replacing_model_obj;
5726
+	}
5727
+
5728
+
5729
+	/**
5730
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5731
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5732
+	 * require_once($this->_getClassName().".class.php");
5733
+	 *
5734
+	 * @return string
5735
+	 */
5736
+	private function _get_class_name()
5737
+	{
5738
+		return "EE_" . $this->get_this_model_name();
5739
+	}
5740
+
5741
+
5742
+	/**
5743
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5744
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5745
+	 * it would be 'Events'.
5746
+	 *
5747
+	 * @param int|float|null $quantity
5748
+	 * @return string
5749
+	 */
5750
+	public function item_name($quantity = 1): string
5751
+	{
5752
+		$quantity = floor($quantity);
5753
+		return apply_filters(
5754
+			'FHEE__EEM_Base__item_name__plural_or_singular',
5755
+			$quantity > 1
5756
+				? $this->plural_item
5757
+				: $this->singular_item,
5758
+			$quantity,
5759
+			$this->plural_item,
5760
+			$this->singular_item
5761
+		);
5762
+	}
5763
+
5764
+
5765
+	/**
5766
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5767
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5768
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5769
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5770
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5771
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5772
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5773
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5774
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5775
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5776
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5777
+	 *        return $previousReturnValue.$returnString;
5778
+	 * }
5779
+	 * require('EEM_Answer.model.php');
5780
+	 * echo EEM_Answer::instance()->my_callback('monkeys',100);
5781
+	 * // will output "you called my_callback! and passed args:monkeys,100"
5782
+	 *
5783
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5784
+	 * @param array  $args       array of original arguments passed to the function
5785
+	 * @return mixed whatever the plugin which calls add_filter decides
5786
+	 * @throws EE_Error
5787
+	 */
5788
+	public function __call($methodName, $args)
5789
+	{
5790
+		$className = get_class($this);
5791
+		$tagName   = "FHEE__{$className}__{$methodName}";
5792
+		if (! has_filter($tagName)) {
5793
+			throw new EE_Error(
5794
+				sprintf(
5795
+					esc_html__(
5796
+						'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5797
+						'event_espresso'
5798
+					),
5799
+					$methodName,
5800
+					$className,
5801
+					$tagName,
5802
+					'<br />'
5803
+				)
5804
+			);
5805
+		}
5806
+		return apply_filters($tagName, null, $this, $args);
5807
+	}
5808
+
5809
+
5810
+	/**
5811
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5812
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5813
+	 *
5814
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5815
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5816
+	 *                                                       the object's class name
5817
+	 *                                                       or object's ID
5818
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5819
+	 *                                                       exists in the database. If it does not, we add it
5820
+	 * @return EE_Base_Class
5821
+	 * @throws EE_Error
5822
+	 * @throws ReflectionException
5823
+	 */
5824
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5825
+	{
5826
+		$className = $this->_get_class_name();
5827
+		if ($base_class_obj_or_id instanceof $className) {
5828
+			$model_object = $base_class_obj_or_id;
5829
+		} else {
5830
+			$primary_key_field = $this->get_primary_key_field();
5831
+			if (
5832
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5833
+				&& (
5834
+					is_int($base_class_obj_or_id)
5835
+					|| is_string($base_class_obj_or_id)
5836
+				)
5837
+			) {
5838
+				// assume it's an ID.
5839
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5840
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5841
+			} elseif (
5842
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5843
+				&& is_string($base_class_obj_or_id)
5844
+			) {
5845
+				// assume it's a string representation of the object
5846
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5847
+			} else {
5848
+				throw new EE_Error(
5849
+					sprintf(
5850
+						esc_html__(
5851
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5852
+							'event_espresso'
5853
+						),
5854
+						$base_class_obj_or_id,
5855
+						$this->_get_class_name(),
5856
+						print_r($base_class_obj_or_id, true)
5857
+					)
5858
+				);
5859
+			}
5860
+		}
5861
+		if ($ensure_is_in_db && $model_object instanceof EE_Base_Class && $model_object->ID() !== null) {
5862
+			$model_object->save();
5863
+		}
5864
+		return $model_object;
5865
+	}
5866
+
5867
+
5868
+	/**
5869
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5870
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5871
+	 * returns it ID.
5872
+	 *
5873
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5874
+	 * @return int|string depending on the type of this model object's ID
5875
+	 * @throws EE_Error
5876
+	 * @throws ReflectionException
5877
+	 */
5878
+	public function ensure_is_ID($base_class_obj_or_id)
5879
+	{
5880
+		$className = $this->_get_class_name();
5881
+		if ($base_class_obj_or_id instanceof $className) {
5882
+			/** @var $base_class_obj_or_id EE_Base_Class */
5883
+			$id = $base_class_obj_or_id->ID();
5884
+		} elseif (is_int($base_class_obj_or_id)) {
5885
+			// assume it's an ID
5886
+			$id = $base_class_obj_or_id;
5887
+		} elseif (is_string($base_class_obj_or_id)) {
5888
+			// assume its a string representation of the object
5889
+			$id = $base_class_obj_or_id;
5890
+		} else {
5891
+			throw new EE_Error(
5892
+				sprintf(
5893
+					esc_html__(
5894
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5895
+						'event_espresso'
5896
+					),
5897
+					$base_class_obj_or_id,
5898
+					$this->_get_class_name(),
5899
+					print_r($base_class_obj_or_id, true)
5900
+				)
5901
+			);
5902
+		}
5903
+		return $id;
5904
+	}
5905
+
5906
+
5907
+	/**
5908
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5909
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5910
+	 * been sanitized and converted into the appropriate domain.
5911
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5912
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5913
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5914
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5915
+	 * $EVT = EEM_Event::instance(); $old_setting =
5916
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5917
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5918
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5919
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5920
+	 *
5921
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5922
+	 * @return void
5923
+	 */
5924
+	public function assume_values_already_prepared_by_model_object(
5925
+		$values_already_prepared = self::not_prepared_by_model_object
5926
+	) {
5927
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5928
+	}
5929
+
5930
+
5931
+	/**
5932
+	 * Read comments for assume_values_already_prepared_by_model_object()
5933
+	 *
5934
+	 * @return int
5935
+	 */
5936
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5937
+	{
5938
+		return $this->_values_already_prepared_by_model_object;
5939
+	}
5940
+
5941
+
5942
+	/**
5943
+	 * Gets all the indexes on this model
5944
+	 *
5945
+	 * @return EE_Index[]
5946
+	 */
5947
+	public function indexes()
5948
+	{
5949
+		return $this->_indexes;
5950
+	}
5951
+
5952
+
5953
+	/**
5954
+	 * Gets all the Unique Indexes on this model
5955
+	 *
5956
+	 * @return EE_Unique_Index[]
5957
+	 */
5958
+	public function unique_indexes()
5959
+	{
5960
+		$unique_indexes = [];
5961
+		foreach ($this->_indexes as $name => $index) {
5962
+			if ($index instanceof EE_Unique_Index) {
5963
+				$unique_indexes [ $name ] = $index;
5964
+			}
5965
+		}
5966
+		return $unique_indexes;
5967
+	}
5968
+
5969
+
5970
+	/**
5971
+	 * Gets all the fields which, when combined, make the primary key.
5972
+	 * This is usually just an array with 1 element (the primary key), but in cases
5973
+	 * where there is no primary key, it's a combination of fields as defined
5974
+	 * on a primary index
5975
+	 *
5976
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5977
+	 * @throws EE_Error
5978
+	 */
5979
+	public function get_combined_primary_key_fields()
5980
+	{
5981
+		foreach ($this->indexes() as $index) {
5982
+			if ($index instanceof EE_Primary_Key_Index) {
5983
+				return $index->fields();
5984
+			}
5985
+		}
5986
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5987
+	}
5988
+
5989
+
5990
+	/**
5991
+	 * Used to build a primary key string (when the model has no primary key),
5992
+	 * which can be used a unique string to identify this model object.
5993
+	 *
5994
+	 * @param array $fields_n_values keys are field names, values are their values.
5995
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5996
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5997
+	 *                               before passing it to this function (that will convert it from columns-n-values
5998
+	 *                               to field-names-n-values).
5999
+	 * @return string
6000
+	 * @throws EE_Error
6001
+	 */
6002
+	public function get_index_primary_key_string($fields_n_values)
6003
+	{
6004
+		$cols_n_values_for_primary_key_index = array_intersect_key(
6005
+			$fields_n_values,
6006
+			$this->get_combined_primary_key_fields()
6007
+		);
6008
+		return http_build_query($cols_n_values_for_primary_key_index);
6009
+	}
6010
+
6011
+
6012
+	/**
6013
+	 * Gets the field values from the primary key string
6014
+	 *
6015
+	 * @param string $index_primary_key_string
6016
+	 * @return null|array
6017
+	 * @throws EE_Error
6018
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
6019
+	 */
6020
+	public function parse_index_primary_key_string($index_primary_key_string)
6021
+	{
6022
+		$key_fields = $this->get_combined_primary_key_fields();
6023
+		// check all of them are in the $id
6024
+		$key_vals_in_combined_pk = [];
6025
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6026
+		foreach ($key_fields as $key_field_name => $field_obj) {
6027
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6028
+				return null;
6029
+			}
6030
+		}
6031
+		return $key_vals_in_combined_pk;
6032
+	}
6033
+
6034
+
6035
+	/**
6036
+	 * verifies that an array of key-value pairs for model fields has a key
6037
+	 * for each field comprising the primary key index
6038
+	 *
6039
+	 * @param array $key_vals
6040
+	 * @return boolean
6041
+	 * @throws EE_Error
6042
+	 */
6043
+	public function has_all_combined_primary_key_fields($key_vals)
6044
+	{
6045
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6046
+		foreach ($keys_it_should_have as $key) {
6047
+			if (! isset($key_vals[ $key ])) {
6048
+				return false;
6049
+			}
6050
+		}
6051
+		return true;
6052
+	}
6053
+
6054
+
6055
+	/**
6056
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
6057
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
6058
+	 *
6059
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
6060
+	 * @param array               $query_params                     @see
6061
+	 *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
6062
+	 * @throws EE_Error
6063
+	 * @throws ReflectionException
6064
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
6065
+	 *                                                              indexed)
6066
+	 */
6067
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
6068
+	{
6069
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
6070
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
6071
+		} elseif (is_array($model_object_or_attributes_array)) {
6072
+			$attributes_array = $model_object_or_attributes_array;
6073
+		} else {
6074
+			throw new EE_Error(
6075
+				sprintf(
6076
+					esc_html__(
6077
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
6078
+						"event_espresso"
6079
+					),
6080
+					$model_object_or_attributes_array
6081
+				)
6082
+			);
6083
+		}
6084
+		// even copies obviously won't have the same ID, so remove the primary key
6085
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
6086
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6087
+			unset($attributes_array[ $this->primary_key_name() ]);
6088
+		}
6089
+		if (isset($query_params[0])) {
6090
+			$query_params[0] = array_merge($attributes_array, $query_params);
6091
+		} else {
6092
+			$query_params[0] = $attributes_array;
6093
+		}
6094
+		return $this->get_all($query_params);
6095
+	}
6096
+
6097
+
6098
+	/**
6099
+	 * Gets the first copy we find. See get_all_copies for more details
6100
+	 *
6101
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6102
+	 * @param array $query_params
6103
+	 * @return EE_Base_Class
6104
+	 * @throws EE_Error
6105
+	 * @throws ReflectionException
6106
+	 */
6107
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6108
+	{
6109
+		if (! is_array($query_params)) {
6110
+			EE_Error::doing_it_wrong(
6111
+				'EEM_Base::get_one_copy',
6112
+				sprintf(
6113
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6114
+					gettype($query_params)
6115
+				),
6116
+				'4.6.0'
6117
+			);
6118
+			$query_params = [];
6119
+		}
6120
+		$query_params['limit'] = 1;
6121
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6122
+		if (is_array($copies)) {
6123
+			return array_shift($copies);
6124
+		}
6125
+		return null;
6126
+	}
6127
+
6128
+
6129
+	/**
6130
+	 * Updates the item with the specified id. Ignores default query parameters because
6131
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6132
+	 *
6133
+	 * @param array      $fields_n_values keys are field names, values are their new values
6134
+	 * @param int|string $id              the value of the primary key to update
6135
+	 * @return int number of rows updated
6136
+	 * @throws EE_Error
6137
+	 * @throws ReflectionException
6138
+	 */
6139
+	public function update_by_ID($fields_n_values, $id)
6140
+	{
6141
+		$query_params = [
6142
+			0                          => [$this->get_primary_key_field()->get_name() => $id],
6143
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6144
+		];
6145
+		return $this->update($fields_n_values, $query_params);
6146
+	}
6147
+
6148
+
6149
+	/**
6150
+	 * Changes an operator which was supplied to the models into one usable in SQL
6151
+	 *
6152
+	 * @param string $operator_supplied
6153
+	 * @return string an operator which can be used in SQL
6154
+	 * @throws EE_Error
6155
+	 */
6156
+	private function _prepare_operator_for_sql($operator_supplied)
6157
+	{
6158
+		$sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6159
+		if ($sql_operator) {
6160
+			return $sql_operator;
6161
+		}
6162
+		throw new EE_Error(
6163
+			sprintf(
6164
+				esc_html__(
6165
+					"The operator '%s' is not in the list of valid operators: %s",
6166
+					"event_espresso"
6167
+				),
6168
+				$operator_supplied,
6169
+				implode(",", array_keys($this->_valid_operators))
6170
+			)
6171
+		);
6172
+	}
6173
+
6174
+
6175
+	/**
6176
+	 * Gets the valid operators
6177
+	 *
6178
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6179
+	 */
6180
+	public function valid_operators()
6181
+	{
6182
+		return $this->_valid_operators;
6183
+	}
6184
+
6185
+
6186
+	/**
6187
+	 * Gets the between-style operators (take 2 arguments).
6188
+	 *
6189
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6190
+	 */
6191
+	public function valid_between_style_operators()
6192
+	{
6193
+		return array_intersect(
6194
+			$this->valid_operators(),
6195
+			$this->_between_style_operators
6196
+		);
6197
+	}
6198
+
6199
+
6200
+	/**
6201
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6202
+	 *
6203
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6204
+	 */
6205
+	public function valid_like_style_operators()
6206
+	{
6207
+		return array_intersect(
6208
+			$this->valid_operators(),
6209
+			$this->_like_style_operators
6210
+		);
6211
+	}
6212
+
6213
+
6214
+	/**
6215
+	 * Gets the "in"-style operators
6216
+	 *
6217
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6218
+	 */
6219
+	public function valid_in_style_operators()
6220
+	{
6221
+		return array_intersect(
6222
+			$this->valid_operators(),
6223
+			$this->_in_style_operators
6224
+		);
6225
+	}
6226
+
6227
+
6228
+	/**
6229
+	 * Gets the "null"-style operators (accept no arguments)
6230
+	 *
6231
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6232
+	 */
6233
+	public function valid_null_style_operators()
6234
+	{
6235
+		return array_intersect(
6236
+			$this->valid_operators(),
6237
+			$this->_null_style_operators
6238
+		);
6239
+	}
6240
+
6241
+
6242
+	/**
6243
+	 * Gets an array where keys are the primary keys and values are their 'names'
6244
+	 * (as determined by the model object's name() function, which is often overridden)
6245
+	 *
6246
+	 * @param array $query_params like get_all's
6247
+	 * @return string[]
6248
+	 * @throws EE_Error
6249
+	 * @throws ReflectionException
6250
+	 */
6251
+	public function get_all_names($query_params = [])
6252
+	{
6253
+		$objs  = $this->get_all($query_params);
6254
+		$names = [];
6255
+		foreach ($objs as $obj) {
6256
+			$names[ $obj->ID() ] = $obj->name();
6257
+		}
6258
+		return $names;
6259
+	}
6260
+
6261
+
6262
+	/**
6263
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6264
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6265
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6266
+	 * array_keys() on $model_objects.
6267
+	 *
6268
+	 * @param \EE_Base_Class[] $model_objects
6269
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6270
+	 *                                               in the returned array
6271
+	 * @return array
6272
+	 * @throws EE_Error
6273
+	 * @throws ReflectionException
6274
+	 */
6275
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6276
+	{
6277
+		if (! $this->has_primary_key_field()) {
6278
+			if (WP_DEBUG) {
6279
+				EE_Error::add_error(
6280
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6281
+					__FILE__,
6282
+					__FUNCTION__,
6283
+					__LINE__
6284
+				);
6285
+			}
6286
+		}
6287
+		$IDs = [];
6288
+		foreach ($model_objects as $model_object) {
6289
+			$id = $model_object->ID();
6290
+			if (! $id) {
6291
+				if ($filter_out_empty_ids) {
6292
+					continue;
6293
+				}
6294
+				if (WP_DEBUG) {
6295
+					EE_Error::add_error(
6296
+						esc_html__(
6297
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6298
+							'event_espresso'
6299
+						),
6300
+						__FILE__,
6301
+						__FUNCTION__,
6302
+						__LINE__
6303
+					);
6304
+				}
6305
+			}
6306
+			$IDs[] = $id;
6307
+		}
6308
+		return $IDs;
6309
+	}
6310
+
6311
+
6312
+	/**
6313
+	 * Returns the string used in capabilities relating to this model. If there
6314
+	 * are no capabilities that relate to this model returns false
6315
+	 *
6316
+	 * @return string|false
6317
+	 */
6318
+	public function cap_slug()
6319
+	{
6320
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6321
+	}
6322
+
6323
+
6324
+	/**
6325
+	 * Returns the capability-restrictions array (@param string $context
6326
+	 *
6327
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6328
+	 * @throws EE_Error
6329
+	 * @see EEM_Base::_cap_restrictions).
6330
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6331
+	 *      only returns the cap restrictions array in that context (ie, the array
6332
+	 *      at that key)
6333
+	 */
6334
+	public function cap_restrictions($context = EEM_Base::caps_read)
6335
+	{
6336
+		EEM_Base::verify_is_valid_cap_context($context);
6337
+		// check if we ought to run the restriction generator first
6338
+		if (
6339
+			isset($this->_cap_restriction_generators[ $context ])
6340
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6341
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6342
+		) {
6343
+			$this->_cap_restrictions[ $context ] = array_merge(
6344
+				$this->_cap_restrictions[ $context ],
6345
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6346
+			);
6347
+		}
6348
+		// and make sure we've finalized the construction of each restriction
6349
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6350
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6351
+				$where_conditions_obj->_finalize_construct($this);
6352
+			}
6353
+		}
6354
+		return $this->_cap_restrictions[ $context ];
6355
+	}
6356
+
6357
+
6358
+	/**
6359
+	 * Indicating whether or not this model thinks its a wp core model
6360
+	 *
6361
+	 * @return boolean
6362
+	 */
6363
+	public function is_wp_core_model()
6364
+	{
6365
+		return $this->_wp_core_model;
6366
+	}
6367
+
6368
+
6369
+	/**
6370
+	 * Gets all the caps that are missing which impose a restriction on
6371
+	 * queries made in this context
6372
+	 *
6373
+	 * @param string $context one of EEM_Base::caps_ constants
6374
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6375
+	 * @throws EE_Error
6376
+	 */
6377
+	public function caps_missing($context = EEM_Base::caps_read)
6378
+	{
6379
+		$missing_caps     = [];
6380
+		$cap_restrictions = $this->cap_restrictions($context);
6381
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6382
+			if (
6383
+				! EE_Capabilities::instance()
6384
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6385
+			) {
6386
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6387
+			}
6388
+		}
6389
+		return $missing_caps;
6390
+	}
6391
+
6392
+
6393
+	/**
6394
+	 * Gets the mapping from capability contexts to action strings used in capability names
6395
+	 *
6396
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6397
+	 * one of 'read', 'edit', or 'delete'
6398
+	 */
6399
+	public function cap_contexts_to_cap_action_map()
6400
+	{
6401
+		return apply_filters(
6402
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6403
+			$this->_cap_contexts_to_cap_action_map,
6404
+			$this
6405
+		);
6406
+	}
6407
+
6408
+
6409
+	/**
6410
+	 * Gets the action string for the specified capability context
6411
+	 *
6412
+	 * @param string $context
6413
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6414
+	 * @throws EE_Error
6415
+	 */
6416
+	public function cap_action_for_context($context)
6417
+	{
6418
+		$mapping = $this->cap_contexts_to_cap_action_map();
6419
+		if (isset($mapping[ $context ])) {
6420
+			return $mapping[ $context ];
6421
+		}
6422
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6423
+			return $action;
6424
+		}
6425
+		throw new EE_Error(
6426
+			sprintf(
6427
+				esc_html__(
6428
+					'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6429
+					'event_espresso'
6430
+				),
6431
+				$context,
6432
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6433
+			)
6434
+		);
6435
+	}
6436
+
6437
+
6438
+	/**
6439
+	 * Returns all the capability contexts which are valid when querying models
6440
+	 *
6441
+	 * @return array
6442
+	 */
6443
+	public static function valid_cap_contexts(): array
6444
+	{
6445
+		return (array) apply_filters(
6446
+			'FHEE__EEM_Base__valid_cap_contexts',
6447
+			[
6448
+				self::caps_read,
6449
+				self::caps_read_admin,
6450
+				self::caps_edit,
6451
+				self::caps_delete,
6452
+			]
6453
+		);
6454
+	}
6455
+
6456
+
6457
+	/**
6458
+	 * Returns all valid options for 'default_where_conditions'
6459
+	 *
6460
+	 * @return array
6461
+	 */
6462
+	public static function valid_default_where_conditions(): array
6463
+	{
6464
+		return [
6465
+			EEM_Base::default_where_conditions_all,
6466
+			EEM_Base::default_where_conditions_this_only,
6467
+			EEM_Base::default_where_conditions_others_only,
6468
+			EEM_Base::default_where_conditions_minimum_all,
6469
+			EEM_Base::default_where_conditions_minimum_others,
6470
+			EEM_Base::default_where_conditions_none,
6471
+		];
6472
+	}
6473
+
6474
+	// public static function default_where_conditions_full
6475
+
6476
+
6477
+	/**
6478
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6479
+	 *
6480
+	 * @param string $context
6481
+	 * @return bool
6482
+	 * @throws EE_Error
6483
+	 */
6484
+	public static function verify_is_valid_cap_context($context): bool
6485
+	{
6486
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6487
+		if (in_array($context, $valid_cap_contexts)) {
6488
+			return true;
6489
+		}
6490
+		throw new EE_Error(
6491
+			sprintf(
6492
+				esc_html__(
6493
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6494
+					'event_espresso'
6495
+				),
6496
+				$context,
6497
+				'EEM_Base',
6498
+				implode(',', $valid_cap_contexts)
6499
+			)
6500
+		);
6501
+	}
6502
+
6503
+
6504
+	/**
6505
+	 * Clears all the models field caches. This is only useful when a sub-class
6506
+	 * might have added a field or something and these caches might be invalidated
6507
+	 */
6508
+	protected function _invalidate_field_caches()
6509
+	{
6510
+		$this->_cache_foreign_key_to_fields = [];
6511
+		$this->_cached_fields               = null;
6512
+		$this->_cached_fields_non_db_only   = null;
6513
+	}
6514
+
6515
+
6516
+	/**
6517
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6518
+	 * (eg "and", "or", "not").
6519
+	 *
6520
+	 * @return array
6521
+	 */
6522
+	public function logic_query_param_keys(): array
6523
+	{
6524
+		return $this->_logic_query_param_keys;
6525
+	}
6526
+
6527
+
6528
+	/**
6529
+	 * Determines whether or not the where query param array key is for a logic query param.
6530
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6531
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6532
+	 *
6533
+	 * @param $query_param_key
6534
+	 * @return bool
6535
+	 */
6536
+	public function is_logic_query_param_key($query_param_key): bool
6537
+	{
6538
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6539
+			if (
6540
+				$query_param_key === $logic_query_param_key
6541
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6542
+			) {
6543
+				return true;
6544
+			}
6545
+		}
6546
+		return false;
6547
+	}
6548
+
6549
+
6550
+	/**
6551
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6552
+	 *
6553
+	 * @return boolean
6554
+	 * @since 4.9.74.p
6555
+	 */
6556
+	public function hasPassword(): bool
6557
+	{
6558
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6559
+		if ($this->has_password_field === null) {
6560
+			$password_field           = $this->getPasswordField();
6561
+			$this->has_password_field = $password_field instanceof EE_Password_Field;
6562
+		}
6563
+		return $this->has_password_field;
6564
+	}
6565
+
6566
+
6567
+	/**
6568
+	 * Returns the password field on this model, if there is one
6569
+	 *
6570
+	 * @return EE_Password_Field|null
6571
+	 * @since 4.9.74.p
6572
+	 */
6573
+	public function getPasswordField()
6574
+	{
6575
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6576
+		// there's no need to search for it. If we don't know yet, then find out
6577
+		if ($this->has_password_field === null && $this->password_field === null) {
6578
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6579
+		}
6580
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6581
+		return $this->password_field;
6582
+	}
6583
+
6584
+
6585
+	/**
6586
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6587
+	 *
6588
+	 * @return EE_Model_Field_Base[]
6589
+	 * @throws EE_Error
6590
+	 * @since 4.9.74.p
6591
+	 */
6592
+	public function getPasswordProtectedFields()
6593
+	{
6594
+		$password_field = $this->getPasswordField();
6595
+		$fields         = [];
6596
+		if ($password_field instanceof EE_Password_Field) {
6597
+			$field_names = $password_field->protectedFields();
6598
+			foreach ($field_names as $field_name) {
6599
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6600
+			}
6601
+		}
6602
+		return $fields;
6603
+	}
6604
+
6605
+
6606
+	/**
6607
+	 * Checks if the current user can perform the requested action on this model
6608
+	 *
6609
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6610
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6611
+	 * @return bool
6612
+	 * @throws EE_Error
6613
+	 * @throws InvalidArgumentException
6614
+	 * @throws InvalidDataTypeException
6615
+	 * @throws InvalidInterfaceException
6616
+	 * @throws ReflectionException
6617
+	 * @throws UnexpectedEntityException
6618
+	 * @since 4.9.74.p
6619
+	 */
6620
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6621
+	{
6622
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6623
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6624
+		}
6625
+		if (! is_array($model_obj_or_fields_n_values)) {
6626
+			throw new UnexpectedEntityException(
6627
+				$model_obj_or_fields_n_values,
6628
+				'EE_Base_Class',
6629
+				sprintf(
6630
+					esc_html__(
6631
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6632
+						'event_espresso'
6633
+					),
6634
+					__FUNCTION__
6635
+				)
6636
+			);
6637
+		}
6638
+		return $this->exists(
6639
+			$this->alter_query_params_to_restrict_by_ID(
6640
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6641
+				[
6642
+					'default_where_conditions' => 'none',
6643
+					'caps'                     => $cap_to_check,
6644
+				]
6645
+			)
6646
+		);
6647
+	}
6648
+
6649
+
6650
+	/**
6651
+	 * Returns the query param where conditions key to the password affecting this model.
6652
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6653
+	 *
6654
+	 * @return null|string
6655
+	 * @throws EE_Error
6656
+	 * @throws InvalidArgumentException
6657
+	 * @throws InvalidDataTypeException
6658
+	 * @throws InvalidInterfaceException
6659
+	 * @throws ModelConfigurationException
6660
+	 * @throws ReflectionException
6661
+	 * @since 4.9.74.p
6662
+	 */
6663
+	public function modelChainAndPassword()
6664
+	{
6665
+		if ($this->model_chain_to_password === null) {
6666
+			throw new ModelConfigurationException(
6667
+				$this,
6668
+				esc_html_x(
6669
+				// @codingStandardsIgnoreStart
6670
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6671
+					// @codingStandardsIgnoreEnd
6672
+					'1: model name',
6673
+					'event_espresso'
6674
+				)
6675
+			);
6676
+		}
6677
+		if ($this->model_chain_to_password === '') {
6678
+			$model_with_password = $this;
6679
+		} else {
6680
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6681
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6682
+			} else {
6683
+				$last_model_in_chain = $this->model_chain_to_password;
6684
+			}
6685
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6686
+		}
6687
+
6688
+		$password_field = $model_with_password->getPasswordField();
6689
+		if ($password_field instanceof EE_Password_Field) {
6690
+			$password_field_name = $password_field->get_name();
6691
+		} else {
6692
+			throw new ModelConfigurationException(
6693
+				$this,
6694
+				sprintf(
6695
+					esc_html_x(
6696
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6697
+						'1: model name, 2: special string',
6698
+						'event_espresso'
6699
+					),
6700
+					$model_with_password->get_this_model_name(),
6701
+					$this->model_chain_to_password
6702
+				)
6703
+			);
6704
+		}
6705
+		return (
6706
+			   $this->model_chain_to_password
6707
+				   ? $this->model_chain_to_password . '.'
6708
+				   : ''
6709
+			   ) . $password_field_name;
6710
+	}
6711
+
6712
+
6713
+	/**
6714
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6715
+	 * or if this model itself has a password affecting access to some of its other fields.
6716
+	 *
6717
+	 * @return boolean
6718
+	 * @since 4.9.74.p
6719
+	 */
6720
+	public function restrictedByRelatedModelPassword(): bool
6721
+	{
6722
+		return $this->model_chain_to_password !== null;
6723
+	}
6724 6724
 }
Please login to merge, or discard this patch.
core/db_models/EEM_System_Status.model.php 2 patches
Indentation   +377 added lines, -377 removed lines patch added patch discarded remove patch
@@ -5,382 +5,382 @@
 block discarded – undo
5 5
  */
6 6
 class EEM_System_Status
7 7
 {
8
-    protected static ?EEM_System_Status $_instance = null;
9
-
10
-
11
-    /**
12
-     * This function is a singleton method used to instantiate the EEM_Attendee object
13
-     *
14
-     * @return EEM_System_Status
15
-     */
16
-    public static function instance()
17
-    {
18
-        // check if instance of EEM_System_Status already exists
19
-        if (self::$_instance === null) {
20
-            // instantiate EEM_System_Status
21
-            self::$_instance = new self();
22
-        }
23
-        return self::$_instance;
24
-    }
25
-
26
-
27
-    private function __construct()
28
-    {
29
-    }
30
-
31
-
32
-    /**
33
-     * @return array where each key is a function name on this class, and each value is SOMETHING--
34
-     * it might be a value, an array, or an object
35
-     */
36
-    public function get_system_stati()
37
-    {
38
-        return apply_filters(
39
-            'FHEE__EEM_System_Status__get_system_stati',
40
-            [
41
-                'ee_version'            => $this->get_ee_version(),
42
-                'ee_activation_history' => $this->get_ee_activation_history(),
43
-                'ee_config'             => $this->get_ee_config(),
44
-                'ee_migration_history'  => $this->get_ee_migration_history(),
45
-                'active_plugins'        => $this->get_active_plugins(),
46
-                'wp_settings'           => $this->get_wp_settings(),
47
-                'wp_maintenance_mode'   => $this->get_wp_maintenance_mode(),
48
-                'https_enabled'         => $this->get_https_enabled(),
49
-                'logging_enabled'       => $this->get_logging_enabled(),
50
-                'remote_posting'        => $this->get_remote_posting(),
51
-                'php_version'           => $this->php_version(),
52
-                'php.ini_settings'      => $this->get_php_ini_all(),
53
-                'php_info'              => $this->get_php_info(),
54
-            ],
55
-            $this
56
-        );
57
-    }
58
-
59
-
60
-    /**
61
-     * @return string
62
-     */
63
-    public function get_ee_version()
64
-    {
65
-        return espresso_version();
66
-    }
67
-
68
-
69
-    /**
70
-     * @return string
71
-     */
72
-    public function php_version()
73
-    {
74
-        return phpversion();
75
-    }
76
-
77
-
78
-    /**
79
-     * @return array, where each key is a plugin name (lower-cased), values are sub-arrays.
80
-     * Sub-arrays like described in wp function get_plugin_data. Ie,     *
81
-     *  'Name' => 'Plugin Name',
82
-     * 'PluginURI' => 'Plugin URI',
83
-     * 'Version' => 'Version',
84
-     * 'Description' => 'Description',
85
-     * 'Author' => 'Author',
86
-     * 'AuthorURI' => 'Author URI',
87
-     * 'TextDomain' => 'Text Domain',
88
-     * 'DomainPath' => 'Domain Path',
89
-     * 'Network' => 'Network',
90
-     */
91
-    public function get_active_plugins()
92
-    {
93
-        $active_plugins = (array) get_option('active_plugins', []);
94
-        if (is_multisite()) {
95
-            $active_plugins = array_merge($active_plugins, get_site_option('active_sitewide_plugins', []));
96
-        }
97
-        $active_plugins = array_map('strtolower', $active_plugins);
98
-        $plugin_info    = [];
99
-        foreach ($active_plugins as $plugin) {
100
-            $plugin_data = @get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin);
101
-
102
-            $plugin_info[ $plugin ] = $plugin_data;
103
-        }
104
-        return $plugin_info;
105
-    }
106
-
107
-
108
-    /**
109
-     * @return array with keys 'home_url' and 'site_url'
110
-     */
111
-    public function get_wp_settings()
112
-    {
113
-        $wp_memory_int = $this->let_to_num(WP_MEMORY_LIMIT);
114
-        if ($wp_memory_int < 67108864) {
115
-            $wp_memory_to_display = '<mark class="error">';
116
-            $wp_memory_to_display .= sprintf(
117
-                esc_html__(
118
-                    '%s - We recommend setting memory to at least 64MB. See: %s Increasing memory allocated to PHP %s',
119
-                    'event_espresso'
120
-                ),
121
-                WP_MEMORY_LIMIT,
122
-                '<a href="http://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP">',
123
-                '</a>"'
124
-            );
125
-            $wp_memory_to_display .= '</mark>';
126
-        } else {
127
-            $wp_memory_to_display = '<mark class="yes">' . size_format($wp_memory_int) . '</mark>';
128
-        }
129
-        return [
130
-            'name'                => get_bloginfo('name', 'display'),
131
-            'is_multisite'        => is_multisite(),
132
-            'version'             => get_bloginfo('version', 'display'),
133
-            'home_url'            => home_url(),
134
-            'site_url'            => site_url(),
135
-            'WP_DEBUG'            => WP_DEBUG,
136
-            'permalink_structure' => get_option('permalink_structure'),
137
-            'theme'               => wp_get_theme(),
138
-            'gmt_offset'          => get_option('gmt_offset'),
139
-            'timezone_string'     => get_option('timezone_string'),
140
-            'admin_email'         => get_bloginfo('admin_email', 'display'),
141
-            'language'            => get_bloginfo('language', 'display'),
142
-            'wp_max_upload_size'  => size_format(wp_max_upload_size()),
143
-            'wp_memory'           => $wp_memory_to_display,
144
-        ];
145
-    }
146
-
147
-
148
-    /**
149
-     * Gets an array of information about the history of ee versions installed
150
-     *
151
-     * @return array
152
-     */
153
-    public function get_ee_activation_history()
154
-    {
155
-        return get_option('espresso_db_update');
156
-    }
157
-
158
-
159
-    /**
160
-     * Gets an array where keys are ee versions, and their values are arrays indicating all the different times that
161
-     * version was installed
162
-     *
163
-     * @return EE_Data_Migration_Script_Base[]
164
-     */
165
-    public function get_ee_migration_history()
166
-    {
167
-        $options                       = EE_Data_Migration_Manager::instance()->get_all_migration_script_options();
168
-        $presentable_migration_scripts = [];
169
-        foreach ($options as $option_array) {
170
-            $presentable_migration_scripts[ str_replace(
171
-                EE_Data_Migration_Manager::data_migration_script_option_prefix,
172
-                "",
173
-                $option_array['option_name']
174
-            ) ] = maybe_unserialize($option_array['option_value']);
175
-        }
176
-        return $presentable_migration_scripts;
8
+	protected static ?EEM_System_Status $_instance = null;
9
+
10
+
11
+	/**
12
+	 * This function is a singleton method used to instantiate the EEM_Attendee object
13
+	 *
14
+	 * @return EEM_System_Status
15
+	 */
16
+	public static function instance()
17
+	{
18
+		// check if instance of EEM_System_Status already exists
19
+		if (self::$_instance === null) {
20
+			// instantiate EEM_System_Status
21
+			self::$_instance = new self();
22
+		}
23
+		return self::$_instance;
24
+	}
25
+
26
+
27
+	private function __construct()
28
+	{
29
+	}
30
+
31
+
32
+	/**
33
+	 * @return array where each key is a function name on this class, and each value is SOMETHING--
34
+	 * it might be a value, an array, or an object
35
+	 */
36
+	public function get_system_stati()
37
+	{
38
+		return apply_filters(
39
+			'FHEE__EEM_System_Status__get_system_stati',
40
+			[
41
+				'ee_version'            => $this->get_ee_version(),
42
+				'ee_activation_history' => $this->get_ee_activation_history(),
43
+				'ee_config'             => $this->get_ee_config(),
44
+				'ee_migration_history'  => $this->get_ee_migration_history(),
45
+				'active_plugins'        => $this->get_active_plugins(),
46
+				'wp_settings'           => $this->get_wp_settings(),
47
+				'wp_maintenance_mode'   => $this->get_wp_maintenance_mode(),
48
+				'https_enabled'         => $this->get_https_enabled(),
49
+				'logging_enabled'       => $this->get_logging_enabled(),
50
+				'remote_posting'        => $this->get_remote_posting(),
51
+				'php_version'           => $this->php_version(),
52
+				'php.ini_settings'      => $this->get_php_ini_all(),
53
+				'php_info'              => $this->get_php_info(),
54
+			],
55
+			$this
56
+		);
57
+	}
58
+
59
+
60
+	/**
61
+	 * @return string
62
+	 */
63
+	public function get_ee_version()
64
+	{
65
+		return espresso_version();
66
+	}
67
+
68
+
69
+	/**
70
+	 * @return string
71
+	 */
72
+	public function php_version()
73
+	{
74
+		return phpversion();
75
+	}
76
+
77
+
78
+	/**
79
+	 * @return array, where each key is a plugin name (lower-cased), values are sub-arrays.
80
+	 * Sub-arrays like described in wp function get_plugin_data. Ie,     *
81
+	 *  'Name' => 'Plugin Name',
82
+	 * 'PluginURI' => 'Plugin URI',
83
+	 * 'Version' => 'Version',
84
+	 * 'Description' => 'Description',
85
+	 * 'Author' => 'Author',
86
+	 * 'AuthorURI' => 'Author URI',
87
+	 * 'TextDomain' => 'Text Domain',
88
+	 * 'DomainPath' => 'Domain Path',
89
+	 * 'Network' => 'Network',
90
+	 */
91
+	public function get_active_plugins()
92
+	{
93
+		$active_plugins = (array) get_option('active_plugins', []);
94
+		if (is_multisite()) {
95
+			$active_plugins = array_merge($active_plugins, get_site_option('active_sitewide_plugins', []));
96
+		}
97
+		$active_plugins = array_map('strtolower', $active_plugins);
98
+		$plugin_info    = [];
99
+		foreach ($active_plugins as $plugin) {
100
+			$plugin_data = @get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin);
101
+
102
+			$plugin_info[ $plugin ] = $plugin_data;
103
+		}
104
+		return $plugin_info;
105
+	}
106
+
107
+
108
+	/**
109
+	 * @return array with keys 'home_url' and 'site_url'
110
+	 */
111
+	public function get_wp_settings()
112
+	{
113
+		$wp_memory_int = $this->let_to_num(WP_MEMORY_LIMIT);
114
+		if ($wp_memory_int < 67108864) {
115
+			$wp_memory_to_display = '<mark class="error">';
116
+			$wp_memory_to_display .= sprintf(
117
+				esc_html__(
118
+					'%s - We recommend setting memory to at least 64MB. See: %s Increasing memory allocated to PHP %s',
119
+					'event_espresso'
120
+				),
121
+				WP_MEMORY_LIMIT,
122
+				'<a href="http://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP">',
123
+				'</a>"'
124
+			);
125
+			$wp_memory_to_display .= '</mark>';
126
+		} else {
127
+			$wp_memory_to_display = '<mark class="yes">' . size_format($wp_memory_int) . '</mark>';
128
+		}
129
+		return [
130
+			'name'                => get_bloginfo('name', 'display'),
131
+			'is_multisite'        => is_multisite(),
132
+			'version'             => get_bloginfo('version', 'display'),
133
+			'home_url'            => home_url(),
134
+			'site_url'            => site_url(),
135
+			'WP_DEBUG'            => WP_DEBUG,
136
+			'permalink_structure' => get_option('permalink_structure'),
137
+			'theme'               => wp_get_theme(),
138
+			'gmt_offset'          => get_option('gmt_offset'),
139
+			'timezone_string'     => get_option('timezone_string'),
140
+			'admin_email'         => get_bloginfo('admin_email', 'display'),
141
+			'language'            => get_bloginfo('language', 'display'),
142
+			'wp_max_upload_size'  => size_format(wp_max_upload_size()),
143
+			'wp_memory'           => $wp_memory_to_display,
144
+		];
145
+	}
146
+
147
+
148
+	/**
149
+	 * Gets an array of information about the history of ee versions installed
150
+	 *
151
+	 * @return array
152
+	 */
153
+	public function get_ee_activation_history()
154
+	{
155
+		return get_option('espresso_db_update');
156
+	}
157
+
158
+
159
+	/**
160
+	 * Gets an array where keys are ee versions, and their values are arrays indicating all the different times that
161
+	 * version was installed
162
+	 *
163
+	 * @return EE_Data_Migration_Script_Base[]
164
+	 */
165
+	public function get_ee_migration_history()
166
+	{
167
+		$options                       = EE_Data_Migration_Manager::instance()->get_all_migration_script_options();
168
+		$presentable_migration_scripts = [];
169
+		foreach ($options as $option_array) {
170
+			$presentable_migration_scripts[ str_replace(
171
+				EE_Data_Migration_Manager::data_migration_script_option_prefix,
172
+				"",
173
+				$option_array['option_name']
174
+			) ] = maybe_unserialize($option_array['option_value']);
175
+		}
176
+		return $presentable_migration_scripts;
177 177
 //      return get_option(EE_Data_Migration_Manager::data_migrations_option_name);//EE_Data_Migration_Manager::instance()->get_data_migrations_ran();
178
-    }
179
-
180
-
181
-    /**
182
-     * @return array like EE_Config class
183
-     */
184
-    public function get_ee_config()
185
-    {
186
-        return EE_Config::instance();
187
-    }
188
-
189
-
190
-    /**
191
-     * Gets an array of php setup info, pilfered from http://www.php.net/manual/en/function.phpinfo.php#87463
192
-     *
193
-     * @return array like the output of phpinfo(), but in an array
194
-     */
195
-    public function get_php_info()
196
-    {
197
-        ob_start();
198
-        phpinfo(-1);
199
-
200
-        $pi = preg_replace(
201
-            [
202
-                '#^.*<body>(.*)</body>.*$#ms',
203
-                '#<h2>PHP License</h2>.*$#ms',
204
-                '#<h1>Configuration</h1>#',
205
-                "#\r?\n#",
206
-                "#</(h1|h2|h3|tr)>#",
207
-                '# +<#',
208
-                "#[ \t]+#",
209
-                '#&nbsp;#',
210
-                '#  +#',
211
-                '# class=".*?"#',
212
-                '%&#039;%',
213
-                '#<tr>(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" /></a>'
214
-                . '<h1>PHP Version (.*?)</h1>(?:\n+?)</td></tr>#',
215
-                '#<h1><a href="(?:.*?)\?=(.*?)">PHP Credits</a></h1>#',
216
-                '#<tr>(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)</tr>#',
217
-                "# +#",
218
-                '#<tr>#',
219
-                '#</tr>#',
220
-            ],
221
-            [
222
-                '$1',
223
-                '',
224
-                '',
225
-                '',
226
-                '</$1>' . "\n",
227
-                '<',
228
-                ' ',
229
-                ' ',
230
-                ' ',
231
-                '',
232
-                ' ',
233
-                '<h2>PHP Configuration</h2>' . "\n" . '<tr><td>PHP Version</td><td>$2</td></tr>' .
234
-                "\n" . '<tr><td>PHP Egg</td><td>$1</td></tr>',
235
-                '<tr><td>PHP Credits Egg</td><td>$1</td></tr>',
236
-                '<tr><td>Zend Engine</td><td>$2</td></tr>' . "\n" .
237
-                '<tr><td>Zend Egg</td><td>$1</td></tr>',
238
-                ' ',
239
-                '%S%',
240
-                '%E%',
241
-            ],
242
-            ob_get_clean()
243
-        );
244
-
245
-        $sections = explode('<h2>', strip_tags((string) $pi, '<h2><th><td>'));
246
-        unset($sections[0]);
247
-
248
-        $pi = [];
249
-        foreach ($sections as $section) {
250
-            $n = substr($section, 0, strpos($section, '</h2>'));
251
-            preg_match_all(
252
-                '#%S%(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?%E%#',
253
-                $section,
254
-                $askapache,
255
-                PREG_SET_ORDER
256
-            );
257
-            foreach ($askapache as $m) {
258
-                $m2 = isset($m[2]) ? $m[2] : null;
259
-            }
260
-            $pi[ $n ][ $m[1] ] = (! isset($m[3]) || $m2 == $m[3]) ? $m2 : array_slice($m, 2);
261
-        }
262
-
263
-        return $pi;
264
-    }
265
-
266
-
267
-    /**
268
-     * Checks if site responds ot HTTPS
269
-     *
270
-     * @return boolean
271
-     */
272
-    public function get_https_enabled()
273
-    {
274
-        $home     = str_replace("http://", "https://", home_url());
275
-        $response = wp_remote_get($home);
276
-        if ($response instanceof WP_Error) {
277
-            $error_string = '';
278
-            foreach ($response->errors as $short_name => $description_array) {
279
-                $error_string .= "<b>$short_name</b>: " . implode(", ", $description_array);
280
-            }
281
-            return $error_string;
282
-        }
283
-        return "ok!";
284
-    }
285
-
286
-
287
-    /**
288
-     * Whether or not a .maintenance file is detected
289
-     *
290
-     * @return string descripting wp_maintenance_mode status
291
-     */
292
-    public function get_wp_maintenance_mode()
293
-    {
294
-        $opened = file_exists(ABSPATH . '.maintenance');
295
-        return $opened ? sprintf(
296
-            esc_html__(
297
-                '%s.maintenance file detected.%s Wordpress may have a failed auto-update which could prevent Event Espresso from updating the database correctly.',
298
-                'event_espresso'
299
-            ),
300
-            '<strong>',
301
-            '</strong>'
302
-        ) : esc_html__('.maintenance file not detected. WordPress is not in maintenance mode.', 'event_espresso');
303
-    }
304
-
305
-
306
-    /**
307
-     * Whether or not logging is enabled
308
-     *
309
-     * @return string descripting logging's status
310
-     */
311
-    public function get_logging_enabled()
312
-    {
313
-        $opened = @fopen(EVENT_ESPRESSO_UPLOAD_DIR . '/logs/espresso_log.txt', 'a');
314
-        return $opened
315
-            ? esc_html__('Log Directory is writable', 'event_espresso')
316
-            : sprintf(
317
-                esc_html__('%sLog directory is NOT writable%s', 'event_espresso'),
318
-                '<mark class="error"',
319
-                '</mark>'
320
-            );
321
-    }
322
-
323
-
324
-    /**
325
-     *  Whether curl ro fsock works
326
-     *
327
-     * @return string describing posting's status
328
-     */
329
-    public function get_remote_posting()
330
-    {
331
-        $fsock_works = function_exists('fsockopen');
332
-        $curl_works  = function_exists('curl_init');
333
-        if ($fsock_works && $curl_works) {
334
-            $status = esc_html__('Your server has fsockopen and cURL enabled.', 'event_espresso');
335
-        } elseif ($fsock_works) {
336
-            $status = esc_html__('Your server has fsockopen enabled, cURL is disabled.', 'event_espresso');
337
-        } elseif ($curl_works) {
338
-            $status = esc_html__('Your server has cURL enabled, fsockopen is disabled.', 'event_espresso');
339
-        } else {
340
-            $status = esc_html__(
341
-                'Your server does not have fsockopen or cURL enabled - PayPal IPN and other scripts which communicate with other servers will not work. Contact your hosting provider.',
342
-                'event_espresso'
343
-            ) . '</mark>';
344
-        }
345
-        return $status;
346
-    }
347
-
348
-
349
-    /**
350
-     * Gets all the php.ini settings
351
-     *
352
-     * @return array
353
-     */
354
-    public function get_php_ini_all()
355
-    {
356
-        return ini_get_all();
357
-    }
358
-
359
-
360
-    /**
361
-     * Transforms the php.ini notation for numbers (like '2M') to an integer.
362
-     *
363
-     * @param type $size
364
-     * @return int
365
-     */
366
-    public function let_to_num($size)
367
-    {
368
-        $l   = substr($size, -1);
369
-        $ret = substr($size, 0, -1);
370
-        // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
371
-        switch (strtoupper($l)) {
372
-            case 'P':
373
-                $ret *= 1024;
374
-            case 'T':
375
-                $ret *= 1024;
376
-            case 'G':
377
-                $ret *= 1024;
378
-            case 'M':
379
-                $ret *= 1024;
380
-            case 'K':
381
-                $ret *= 1024;
382
-        }
383
-        // phpcs:enable
384
-        return $ret;
385
-    }
178
+	}
179
+
180
+
181
+	/**
182
+	 * @return array like EE_Config class
183
+	 */
184
+	public function get_ee_config()
185
+	{
186
+		return EE_Config::instance();
187
+	}
188
+
189
+
190
+	/**
191
+	 * Gets an array of php setup info, pilfered from http://www.php.net/manual/en/function.phpinfo.php#87463
192
+	 *
193
+	 * @return array like the output of phpinfo(), but in an array
194
+	 */
195
+	public function get_php_info()
196
+	{
197
+		ob_start();
198
+		phpinfo(-1);
199
+
200
+		$pi = preg_replace(
201
+			[
202
+				'#^.*<body>(.*)</body>.*$#ms',
203
+				'#<h2>PHP License</h2>.*$#ms',
204
+				'#<h1>Configuration</h1>#',
205
+				"#\r?\n#",
206
+				"#</(h1|h2|h3|tr)>#",
207
+				'# +<#',
208
+				"#[ \t]+#",
209
+				'#&nbsp;#',
210
+				'#  +#',
211
+				'# class=".*?"#',
212
+				'%&#039;%',
213
+				'#<tr>(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" /></a>'
214
+				. '<h1>PHP Version (.*?)</h1>(?:\n+?)</td></tr>#',
215
+				'#<h1><a href="(?:.*?)\?=(.*?)">PHP Credits</a></h1>#',
216
+				'#<tr>(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)</tr>#',
217
+				"# +#",
218
+				'#<tr>#',
219
+				'#</tr>#',
220
+			],
221
+			[
222
+				'$1',
223
+				'',
224
+				'',
225
+				'',
226
+				'</$1>' . "\n",
227
+				'<',
228
+				' ',
229
+				' ',
230
+				' ',
231
+				'',
232
+				' ',
233
+				'<h2>PHP Configuration</h2>' . "\n" . '<tr><td>PHP Version</td><td>$2</td></tr>' .
234
+				"\n" . '<tr><td>PHP Egg</td><td>$1</td></tr>',
235
+				'<tr><td>PHP Credits Egg</td><td>$1</td></tr>',
236
+				'<tr><td>Zend Engine</td><td>$2</td></tr>' . "\n" .
237
+				'<tr><td>Zend Egg</td><td>$1</td></tr>',
238
+				' ',
239
+				'%S%',
240
+				'%E%',
241
+			],
242
+			ob_get_clean()
243
+		);
244
+
245
+		$sections = explode('<h2>', strip_tags((string) $pi, '<h2><th><td>'));
246
+		unset($sections[0]);
247
+
248
+		$pi = [];
249
+		foreach ($sections as $section) {
250
+			$n = substr($section, 0, strpos($section, '</h2>'));
251
+			preg_match_all(
252
+				'#%S%(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?%E%#',
253
+				$section,
254
+				$askapache,
255
+				PREG_SET_ORDER
256
+			);
257
+			foreach ($askapache as $m) {
258
+				$m2 = isset($m[2]) ? $m[2] : null;
259
+			}
260
+			$pi[ $n ][ $m[1] ] = (! isset($m[3]) || $m2 == $m[3]) ? $m2 : array_slice($m, 2);
261
+		}
262
+
263
+		return $pi;
264
+	}
265
+
266
+
267
+	/**
268
+	 * Checks if site responds ot HTTPS
269
+	 *
270
+	 * @return boolean
271
+	 */
272
+	public function get_https_enabled()
273
+	{
274
+		$home     = str_replace("http://", "https://", home_url());
275
+		$response = wp_remote_get($home);
276
+		if ($response instanceof WP_Error) {
277
+			$error_string = '';
278
+			foreach ($response->errors as $short_name => $description_array) {
279
+				$error_string .= "<b>$short_name</b>: " . implode(", ", $description_array);
280
+			}
281
+			return $error_string;
282
+		}
283
+		return "ok!";
284
+	}
285
+
286
+
287
+	/**
288
+	 * Whether or not a .maintenance file is detected
289
+	 *
290
+	 * @return string descripting wp_maintenance_mode status
291
+	 */
292
+	public function get_wp_maintenance_mode()
293
+	{
294
+		$opened = file_exists(ABSPATH . '.maintenance');
295
+		return $opened ? sprintf(
296
+			esc_html__(
297
+				'%s.maintenance file detected.%s Wordpress may have a failed auto-update which could prevent Event Espresso from updating the database correctly.',
298
+				'event_espresso'
299
+			),
300
+			'<strong>',
301
+			'</strong>'
302
+		) : esc_html__('.maintenance file not detected. WordPress is not in maintenance mode.', 'event_espresso');
303
+	}
304
+
305
+
306
+	/**
307
+	 * Whether or not logging is enabled
308
+	 *
309
+	 * @return string descripting logging's status
310
+	 */
311
+	public function get_logging_enabled()
312
+	{
313
+		$opened = @fopen(EVENT_ESPRESSO_UPLOAD_DIR . '/logs/espresso_log.txt', 'a');
314
+		return $opened
315
+			? esc_html__('Log Directory is writable', 'event_espresso')
316
+			: sprintf(
317
+				esc_html__('%sLog directory is NOT writable%s', 'event_espresso'),
318
+				'<mark class="error"',
319
+				'</mark>'
320
+			);
321
+	}
322
+
323
+
324
+	/**
325
+	 *  Whether curl ro fsock works
326
+	 *
327
+	 * @return string describing posting's status
328
+	 */
329
+	public function get_remote_posting()
330
+	{
331
+		$fsock_works = function_exists('fsockopen');
332
+		$curl_works  = function_exists('curl_init');
333
+		if ($fsock_works && $curl_works) {
334
+			$status = esc_html__('Your server has fsockopen and cURL enabled.', 'event_espresso');
335
+		} elseif ($fsock_works) {
336
+			$status = esc_html__('Your server has fsockopen enabled, cURL is disabled.', 'event_espresso');
337
+		} elseif ($curl_works) {
338
+			$status = esc_html__('Your server has cURL enabled, fsockopen is disabled.', 'event_espresso');
339
+		} else {
340
+			$status = esc_html__(
341
+				'Your server does not have fsockopen or cURL enabled - PayPal IPN and other scripts which communicate with other servers will not work. Contact your hosting provider.',
342
+				'event_espresso'
343
+			) . '</mark>';
344
+		}
345
+		return $status;
346
+	}
347
+
348
+
349
+	/**
350
+	 * Gets all the php.ini settings
351
+	 *
352
+	 * @return array
353
+	 */
354
+	public function get_php_ini_all()
355
+	{
356
+		return ini_get_all();
357
+	}
358
+
359
+
360
+	/**
361
+	 * Transforms the php.ini notation for numbers (like '2M') to an integer.
362
+	 *
363
+	 * @param type $size
364
+	 * @return int
365
+	 */
366
+	public function let_to_num($size)
367
+	{
368
+		$l   = substr($size, -1);
369
+		$ret = substr($size, 0, -1);
370
+		// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
371
+		switch (strtoupper($l)) {
372
+			case 'P':
373
+				$ret *= 1024;
374
+			case 'T':
375
+				$ret *= 1024;
376
+			case 'G':
377
+				$ret *= 1024;
378
+			case 'M':
379
+				$ret *= 1024;
380
+			case 'K':
381
+				$ret *= 1024;
382
+		}
383
+		// phpcs:enable
384
+		return $ret;
385
+	}
386 386
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -97,9 +97,9 @@  discard block
 block discarded – undo
97 97
         $active_plugins = array_map('strtolower', $active_plugins);
98 98
         $plugin_info    = [];
99 99
         foreach ($active_plugins as $plugin) {
100
-            $plugin_data = @get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin);
100
+            $plugin_data = @get_plugin_data(WP_PLUGIN_DIR.'/'.$plugin);
101 101
 
102
-            $plugin_info[ $plugin ] = $plugin_data;
102
+            $plugin_info[$plugin] = $plugin_data;
103 103
         }
104 104
         return $plugin_info;
105 105
     }
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
             );
125 125
             $wp_memory_to_display .= '</mark>';
126 126
         } else {
127
-            $wp_memory_to_display = '<mark class="yes">' . size_format($wp_memory_int) . '</mark>';
127
+            $wp_memory_to_display = '<mark class="yes">'.size_format($wp_memory_int).'</mark>';
128 128
         }
129 129
         return [
130 130
             'name'                => get_bloginfo('name', 'display'),
@@ -167,11 +167,11 @@  discard block
 block discarded – undo
167 167
         $options                       = EE_Data_Migration_Manager::instance()->get_all_migration_script_options();
168 168
         $presentable_migration_scripts = [];
169 169
         foreach ($options as $option_array) {
170
-            $presentable_migration_scripts[ str_replace(
170
+            $presentable_migration_scripts[str_replace(
171 171
                 EE_Data_Migration_Manager::data_migration_script_option_prefix,
172 172
                 "",
173 173
                 $option_array['option_name']
174
-            ) ] = maybe_unserialize($option_array['option_value']);
174
+            )] = maybe_unserialize($option_array['option_value']);
175 175
         }
176 176
         return $presentable_migration_scripts;
177 177
 //      return get_option(EE_Data_Migration_Manager::data_migrations_option_name);//EE_Data_Migration_Manager::instance()->get_data_migrations_ran();
@@ -223,17 +223,17 @@  discard block
 block discarded – undo
223 223
                 '',
224 224
                 '',
225 225
                 '',
226
-                '</$1>' . "\n",
226
+                '</$1>'."\n",
227 227
                 '<',
228 228
                 ' ',
229 229
                 ' ',
230 230
                 ' ',
231 231
                 '',
232 232
                 ' ',
233
-                '<h2>PHP Configuration</h2>' . "\n" . '<tr><td>PHP Version</td><td>$2</td></tr>' .
234
-                "\n" . '<tr><td>PHP Egg</td><td>$1</td></tr>',
233
+                '<h2>PHP Configuration</h2>'."\n".'<tr><td>PHP Version</td><td>$2</td></tr>'.
234
+                "\n".'<tr><td>PHP Egg</td><td>$1</td></tr>',
235 235
                 '<tr><td>PHP Credits Egg</td><td>$1</td></tr>',
236
-                '<tr><td>Zend Engine</td><td>$2</td></tr>' . "\n" .
236
+                '<tr><td>Zend Engine</td><td>$2</td></tr>'."\n".
237 237
                 '<tr><td>Zend Egg</td><td>$1</td></tr>',
238 238
                 ' ',
239 239
                 '%S%',
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
             foreach ($askapache as $m) {
258 258
                 $m2 = isset($m[2]) ? $m[2] : null;
259 259
             }
260
-            $pi[ $n ][ $m[1] ] = (! isset($m[3]) || $m2 == $m[3]) ? $m2 : array_slice($m, 2);
260
+            $pi[$n][$m[1]] = ( ! isset($m[3]) || $m2 == $m[3]) ? $m2 : array_slice($m, 2);
261 261
         }
262 262
 
263 263
         return $pi;
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
         if ($response instanceof WP_Error) {
277 277
             $error_string = '';
278 278
             foreach ($response->errors as $short_name => $description_array) {
279
-                $error_string .= "<b>$short_name</b>: " . implode(", ", $description_array);
279
+                $error_string .= "<b>$short_name</b>: ".implode(", ", $description_array);
280 280
             }
281 281
             return $error_string;
282 282
         }
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
      */
292 292
     public function get_wp_maintenance_mode()
293 293
     {
294
-        $opened = file_exists(ABSPATH . '.maintenance');
294
+        $opened = file_exists(ABSPATH.'.maintenance');
295 295
         return $opened ? sprintf(
296 296
             esc_html__(
297 297
                 '%s.maintenance file detected.%s Wordpress may have a failed auto-update which could prevent Event Espresso from updating the database correctly.',
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
      */
311 311
     public function get_logging_enabled()
312 312
     {
313
-        $opened = @fopen(EVENT_ESPRESSO_UPLOAD_DIR . '/logs/espresso_log.txt', 'a');
313
+        $opened = @fopen(EVENT_ESPRESSO_UPLOAD_DIR.'/logs/espresso_log.txt', 'a');
314 314
         return $opened
315 315
             ? esc_html__('Log Directory is writable', 'event_espresso')
316 316
             : sprintf(
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
             $status = esc_html__(
341 341
                 'Your server does not have fsockopen or cURL enabled - PayPal IPN and other scripts which communicate with other servers will not work. Contact your hosting provider.',
342 342
                 'event_espresso'
343
-            ) . '</mark>';
343
+            ).'</mark>';
344 344
         }
345 345
         return $status;
346 346
     }
Please login to merge, or discard this patch.
core/EE_Base.core.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -11,42 +11,42 @@
 block discarded – undo
11 11
  */
12 12
 class EE_Base
13 13
 {
14
-    /**
15
-     * override magic methods
16
-     * @return void
17
-     */
18
-    public function __get($a)
19
-    {
20
-        return false;
21
-    }
14
+	/**
15
+	 * override magic methods
16
+	 * @return void
17
+	 */
18
+	public function __get($a)
19
+	{
20
+		return false;
21
+	}
22 22
 
23
-    public function __set($a, $b)
24
-    {
25
-        return false;
26
-    }
23
+	public function __set($a, $b)
24
+	{
25
+		return false;
26
+	}
27 27
 
28
-    public function __isset($a)
29
-    {
30
-        return false;
31
-    }
28
+	public function __isset($a)
29
+	{
30
+		return false;
31
+	}
32 32
 
33
-    public function __unset($a)
34
-    {
35
-        return false;
36
-    }
33
+	public function __unset($a)
34
+	{
35
+		return false;
36
+	}
37 37
 
38
-    public function __clone()
39
-    {
40
-        return false;
41
-    }
38
+	public function __clone()
39
+	{
40
+		return false;
41
+	}
42 42
 
43
-    public function __wakeup()
44
-    {
45
-        return false;
46
-    }
43
+	public function __wakeup()
44
+	{
45
+		return false;
46
+	}
47 47
 
48
-    public function __destruct()
49
-    {
50
-        return false;
51
-    }
48
+	public function __destruct()
49
+	{
50
+		return false;
51
+	}
52 52
 }
Please login to merge, or discard this patch.