Completed
Branch Gutenberg/event-attendees-bloc... (dcb43c)
by
unknown
43:02 queued 34:56
created
core/services/orm/ModelFieldFactory.php 3 patches
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -33,9 +33,6 @@
 block discarded – undo
33 33
 use EE_WP_Post_Status_Field;
34 34
 use EE_WP_Post_Type_Field;
35 35
 use EE_WP_User_Field;
36
-use EventEspresso\core\exceptions\InvalidDataTypeException;
37
-use EventEspresso\core\exceptions\InvalidInterfaceException;
38
-use EventEspresso\core\services\loaders\LoaderFactory;
39 36
 use EventEspresso\core\services\loaders\LoaderInterface;
40 37
 use InvalidArgumentException;
41 38
 
Please login to merge, or discard this patch.
Doc Comments   +4 added lines, -5 removed lines patch added patch discarded remove patch
@@ -125,7 +125,6 @@  discard block
 block discarded – undo
125 125
     /**
126 126
      * @param string $table_column
127 127
      * @param string $nice_name
128
-     * @param string $timezone_string
129 128
      * @param bool   $nullable
130 129
      * @param string $default_value
131 130
      * @throws EE_Error
@@ -170,7 +169,7 @@  discard block
 block discarded – undo
170 169
      * @param string $table_column
171 170
      * @param string $nice_name
172 171
      * @param bool   $nullable
173
-     * @param null   $default_value
172
+     * @param integer   $default_value
174 173
      * @return EE_DB_Only_Int_Field
175 174
      */
176 175
     public function createDbOnlyIntField($table_column, $nice_name, $nullable, $default_value = null)
@@ -280,7 +279,7 @@  discard block
 block discarded – undo
280 279
      * @param string $table_column
281 280
      * @param string $nice_name
282 281
      * @param bool   $nullable
283
-     * @param null   $default_value
282
+     * @param integer   $default_value
284 283
      * @param string $model_name
285 284
      * @return EE_Foreign_Key_Int_Field
286 285
      */
@@ -297,7 +296,7 @@  discard block
 block discarded – undo
297 296
      * @param string $table_column
298 297
      * @param string $nice_name
299 298
      * @param bool   $nullable
300
-     * @param null   $default_value
299
+     * @param string   $default_value
301 300
      * @param string $model_name
302 301
      * @return EE_Foreign_Key_String_Field
303 302
      */
@@ -533,7 +532,7 @@  discard block
 block discarded – undo
533 532
      * @param string $table_column
534 533
      * @param string $nice_name
535 534
      * @param bool   $nullable
536
-     * @param mixed  $default_value
535
+     * @param string  $default_value
537 536
      * @param array  $values                            If additional stati are to be used other than the default WP
538 537
      *                                                  statuses, then they can be registered via this property. The
539 538
      *                                                  format of the array should be as follows: array(
Please login to merge, or discard this patch.
Indentation   +543 added lines, -543 removed lines patch added patch discarded remove patch
@@ -51,547 +51,547 @@
 block discarded – undo
51 51
 class ModelFieldFactory
52 52
 {
53 53
 
54
-    /**
55
-     * @var LoaderInterface $loader
56
-     */
57
-    private $loader;
58
-
59
-
60
-    /**
61
-     * ModelFieldFactory constructor.
62
-     *
63
-     * @param LoaderInterface $loader
64
-     */
65
-    public function __construct(LoaderInterface $loader)
66
-    {
67
-        $this->loader = $loader;
68
-    }
69
-
70
-
71
-    /**
72
-     * @param string $table_column
73
-     * @param string $nice_name
74
-     * @param bool   $nullable
75
-     * @param null   $default_value
76
-     * @return EE_All_Caps_Text_Field
77
-     */
78
-    public function createAllCapsTextField($table_column, $nice_name, $nullable, $default_value = null)
79
-    {
80
-        return $this->loader->getNew(
81
-            'EE_All_Caps_Text_Field',
82
-            array($table_column, $nice_name, $nullable, $default_value)
83
-        );
84
-    }
85
-
86
-
87
-    /**
88
-     * @param string $table_column
89
-     * @param string $nice_name
90
-     * @param bool   $nullable
91
-     * @param null   $default_value
92
-     * @param string $model_name
93
-     * @return EE_Any_Foreign_Model_Name_Field
94
-     */
95
-    public function createAnyForeignModelNameField(
96
-        $table_column,
97
-        $nice_name,
98
-        $nullable,
99
-        $default_value = null,
100
-        $model_name
101
-    ) {
102
-        return $this->loader->getNew(
103
-            'EE_Any_Foreign_Model_Name_Field',
104
-            array($table_column, $nice_name, $nullable, $default_value, $model_name)
105
-        );
106
-    }
107
-
108
-
109
-    /**
110
-     * @param string $table_column
111
-     * @param string $nice_name
112
-     * @param bool   $nullable
113
-     * @param null   $default_value
114
-     * @return EE_Boolean_Field
115
-     */
116
-    public function createBooleanField($table_column, $nice_name, $nullable, $default_value = null)
117
-    {
118
-        return $this->loader->getNew(
119
-            'EE_Boolean_Field',
120
-            array($table_column, $nice_name, $nullable, $default_value)
121
-        );
122
-    }
123
-
124
-
125
-    /**
126
-     * @param string $table_column
127
-     * @param string $nice_name
128
-     * @param string $timezone_string
129
-     * @param bool   $nullable
130
-     * @param string $default_value
131
-     * @throws EE_Error
132
-     * @throws InvalidArgumentException
133
-     * @return EE_Datetime_Field
134
-     */
135
-    public function createDatetimeField(
136
-        $table_column,
137
-        $nice_name,
138
-        $nullable = false,
139
-        $default_value = EE_Datetime_Field::now
140
-    ) {
141
-        return $this->loader->getNew(
142
-            'EE_Datetime_Field',
143
-            array(
144
-                $table_column,
145
-                $nice_name,
146
-                $nullable,
147
-                $default_value,
148
-            )
149
-        );
150
-    }
151
-
152
-
153
-    /**
154
-     * @param string $table_column
155
-     * @param string $nice_name
156
-     * @param bool   $nullable
157
-     * @param null   $default_value
158
-     * @return EE_DB_Only_Float_Field
159
-     */
160
-    public function createDbOnlyFloatField($table_column, $nice_name, $nullable, $default_value = null)
161
-    {
162
-        return $this->loader->getNew(
163
-            'EE_DB_Only_Float_Field',
164
-            array($table_column, $nice_name, $nullable, $default_value)
165
-        );
166
-    }
167
-
168
-
169
-    /**
170
-     * @param string $table_column
171
-     * @param string $nice_name
172
-     * @param bool   $nullable
173
-     * @param null   $default_value
174
-     * @return EE_DB_Only_Int_Field
175
-     */
176
-    public function createDbOnlyIntField($table_column, $nice_name, $nullable, $default_value = null)
177
-    {
178
-        return $this->loader->getNew(
179
-            'EE_DB_Only_Int_Field',
180
-            array($table_column, $nice_name, $nullable, $default_value)
181
-        );
182
-    }
183
-
184
-
185
-    /**
186
-     * @param string $table_column
187
-     * @param string $nice_name
188
-     * @param bool   $nullable
189
-     * @param null   $default_value
190
-     * @return EE_DB_Only_Text_Field
191
-     */
192
-    public function createDbOnlyTextField($table_column, $nice_name, $nullable, $default_value = null)
193
-    {
194
-        return $this->loader->getNew(
195
-            'EE_DB_Only_Text_Field',
196
-            array($table_column, $nice_name, $nullable, $default_value)
197
-        );
198
-    }
199
-
200
-
201
-    /**
202
-     * @param string $table_column
203
-     * @param string $nice_name
204
-     * @param bool   $nullable
205
-     * @param string $default_value
206
-     * @return EE_Email_Field
207
-     */
208
-    public function createEmailField($table_column, $nice_name, $nullable = true, $default_value = '')
209
-    {
210
-        return $this->loader->getNew(
211
-            'EE_Email_Field',
212
-            array($table_column, $nice_name, $nullable, $default_value)
213
-        );
214
-    }
215
-
216
-
217
-    /**
218
-     * @param string $table_column
219
-     * @param string $nice_name
220
-     * @param bool   $nullable
221
-     * @param null   $default_value
222
-     * @param array  $allowed_enum_values keys are values to be used in the DB,
223
-     *                                    values are how they should be displayed
224
-     * @return EE_Enum_Integer_Field
225
-     */
226
-    public function createEnumIntegerField(
227
-        $table_column,
228
-        $nice_name,
229
-        $nullable,
230
-        $default_value = null,
231
-        array $allowed_enum_values
232
-    ) {
233
-        return $this->loader->getNew(
234
-            'EE_Enum_Integer_Field',
235
-            array($table_column, $nice_name, $nullable, $default_value, $allowed_enum_values)
236
-        );
237
-    }
238
-
239
-
240
-    /**
241
-     * @param string $table_column
242
-     * @param string $nice_name
243
-     * @param bool   $nullable
244
-     * @param null   $default_value
245
-     * @param array  $allowed_enum_values keys are values to be used in the DB,
246
-     *                                    values are how they should be displayed
247
-     * @return EE_Enum_Text_Field
248
-     */
249
-    public function createEnumTextField(
250
-        $table_column,
251
-        $nice_name,
252
-        $nullable,
253
-        $default_value,
254
-        array $allowed_enum_values
255
-    ) {
256
-        return $this->loader->getNew(
257
-            'EE_Enum_Text_Field',
258
-            array($table_column, $nice_name, $nullable, $default_value, $allowed_enum_values)
259
-        );
260
-    }
261
-
262
-
263
-    /**
264
-     * @param string $table_column
265
-     * @param string $nice_name
266
-     * @param bool   $nullable
267
-     * @param null   $default_value
268
-     * @return EE_Float_Field
269
-     */
270
-    public function createFloatField($table_column, $nice_name, $nullable, $default_value = null)
271
-    {
272
-        return $this->loader->getNew(
273
-            'EE_Float_Field',
274
-            array($table_column, $nice_name, $nullable, $default_value)
275
-        );
276
-    }
277
-
278
-
279
-    /**
280
-     * @param string $table_column
281
-     * @param string $nice_name
282
-     * @param bool   $nullable
283
-     * @param null   $default_value
284
-     * @param string $model_name
285
-     * @return EE_Foreign_Key_Int_Field
286
-     */
287
-    public function createForeignKeyIntField($table_column, $nice_name, $nullable, $default_value, $model_name)
288
-    {
289
-        return $this->loader->getNew(
290
-            'EE_Foreign_Key_Int_Field',
291
-            array($table_column, $nice_name, $nullable, $default_value, $model_name)
292
-        );
293
-    }
294
-
295
-
296
-    /**
297
-     * @param string $table_column
298
-     * @param string $nice_name
299
-     * @param bool   $nullable
300
-     * @param null   $default_value
301
-     * @param string $model_name
302
-     * @return EE_Foreign_Key_String_Field
303
-     */
304
-    public function createForeignKeyStringField(
305
-        $table_column,
306
-        $nice_name,
307
-        $nullable,
308
-        $default_value,
309
-        $model_name
310
-    ) {
311
-        return $this->loader->getNew(
312
-            'EE_Foreign_Key_String_Field',
313
-            array($table_column, $nice_name, $nullable, $default_value, $model_name)
314
-        );
315
-    }
316
-
317
-
318
-    /**
319
-     * @param string $table_column
320
-     * @param string $nice_name
321
-     * @param bool   $nullable
322
-     * @param null   $default_value
323
-     * @return EE_Full_HTML_Field
324
-     */
325
-    public function createFullHtmlField($table_column, $nice_name, $nullable, $default_value = null)
326
-    {
327
-        return $this->loader->getNew(
328
-            'EE_Full_HTML_Field',
329
-            array($table_column, $nice_name, $nullable, $default_value)
330
-        );
331
-    }
332
-
333
-
334
-    /**
335
-     * @param string $table_column
336
-     * @param string $nice_name
337
-     * @param bool   $nullable
338
-     * @param null   $default_value
339
-     * @return EE_Infinite_Integer_Field
340
-     */
341
-    public function createInfiniteIntegerField($table_column, $nice_name, $nullable, $default_value = null)
342
-    {
343
-        return $this->loader->getNew(
344
-            'EE_Infinite_Integer_Field',
345
-            array($table_column, $nice_name, $nullable, $default_value)
346
-        );
347
-    }
348
-
349
-
350
-    /**
351
-     * @param string  $table_column
352
-     * @param string  $nice_name
353
-     * @param bool    $nullable
354
-     * @param integer $default_value
355
-     * @return EE_Integer_Field
356
-     */
357
-    public function createIntegerField($table_column, $nice_name, $nullable = false, $default_value = 0)
358
-    {
359
-        return $this->loader->getNew(
360
-            'EE_Integer_Field',
361
-            array($table_column, $nice_name, $nullable, $default_value)
362
-        );
363
-    }
364
-
365
-
366
-    /**
367
-     * @param string $table_column
368
-     * @param string $nice_name
369
-     * @param bool   $nullable
370
-     * @param null   $default_value
371
-     * @return EE_Maybe_Serialized_Simple_HTML_Field
372
-     */
373
-    public function createMaybeSerializedSimpleHtmlField($table_column, $nice_name, $nullable, $default_value = null)
374
-    {
375
-        return $this->loader->getNew(
376
-            'EE_Maybe_Serialized_Simple_HTML_Field',
377
-            array($table_column, $nice_name, $nullable, $default_value)
378
-        );
379
-    }
380
-
381
-
382
-    /**
383
-     * @param string $table_column
384
-     * @param string $nice_name
385
-     * @param bool   $nullable
386
-     * @param null   $default_value
387
-     * @return EE_Maybe_Serialized_Text_Field
388
-     */
389
-    public function createMaybeSerializedTextField($table_column, $nice_name, $nullable, $default_value = null)
390
-    {
391
-        return $this->loader->getNew(
392
-            'EE_Maybe_Serialized_Text_Field',
393
-            array($table_column, $nice_name, $nullable, $default_value)
394
-        );
395
-    }
396
-
397
-
398
-    /**
399
-     * @param string $table_column
400
-     * @param string $nice_name
401
-     * @param bool   $nullable
402
-     * @param null   $default_value
403
-     * @return EE_Money_Field
404
-     */
405
-    public function createMoneyField($table_column, $nice_name, $nullable, $default_value = null)
406
-    {
407
-        return $this->loader->getNew(
408
-            'EE_Money_Field',
409
-            array($table_column, $nice_name, $nullable, $default_value)
410
-        );
411
-    }
412
-
413
-
414
-    /**
415
-     * @param string $table_column
416
-     * @param string $nice_name
417
-     * @param bool   $nullable
418
-     * @param string $default_value
419
-     * @return EE_Plain_Text_Field
420
-     */
421
-    public function createPlainTextField($table_column, $nice_name, $nullable = true, $default_value = '')
422
-    {
423
-        return $this->loader->getNew(
424
-            'EE_Plain_Text_Field',
425
-            array($table_column, $nice_name, $nullable, $default_value)
426
-        );
427
-    }
428
-
429
-
430
-    /**
431
-     * @param string $table_column
432
-     * @param string $nice_name
433
-     * @param bool   $nullable
434
-     * @param null   $default_value
435
-     * @return EE_Post_Content_Field
436
-     */
437
-    public function createPostContentField($table_column, $nice_name, $nullable, $default_value = null)
438
-    {
439
-        return $this->loader->getNew(
440
-            'EE_Post_Content_Field',
441
-            array($table_column, $nice_name, $nullable, $default_value)
442
-        );
443
-    }
444
-
445
-
446
-    /**
447
-     * @param string $table_column
448
-     * @param string $nice_name
449
-     * @return EE_Primary_Key_Int_Field
450
-     */
451
-    public function createPrimaryKeyIntField($table_column, $nice_name)
452
-    {
453
-        return $this->loader->getNew('EE_Primary_Key_Int_Field', array($table_column, $nice_name));
454
-    }
455
-
456
-
457
-    /**
458
-     * @param string $table_column
459
-     * @param string $nice_name
460
-     * @return EE_Primary_Key_String_Field
461
-     */
462
-    public function createPrimaryKeyStringField($table_column, $nice_name)
463
-    {
464
-        return $this->loader->getNew('EE_Primary_Key_String_Field', array($table_column, $nice_name));
465
-    }
466
-
467
-
468
-    /**
469
-     * @param string $table_column
470
-     * @param string $nice_name
471
-     * @param bool   $nullable
472
-     * @param null   $default_value
473
-     * @return EE_Serialized_Text_Field
474
-     */
475
-    public function createSerializedTextField($table_column, $nice_name, $nullable, $default_value = null)
476
-    {
477
-        return $this->loader->getNew(
478
-            'EE_Serialized_Text_Field',
479
-            array($table_column, $nice_name, $nullable, $default_value)
480
-        );
481
-    }
482
-
483
-
484
-    /**
485
-     * @param string $table_column
486
-     * @param string $nice_name
487
-     * @param bool   $nullable
488
-     * @param null   $default_value
489
-     * @return EE_Simple_HTML_Field
490
-     */
491
-    public function createSimpleHtmlField($table_column, $nice_name, $nullable, $default_value = null)
492
-    {
493
-        return $this->loader->getNew(
494
-            'EE_Simple_HTML_Field',
495
-            array($table_column, $nice_name, $nullable, $default_value)
496
-        );
497
-    }
498
-
499
-
500
-    /**
501
-     * @param string $table_column
502
-     * @param string $nice_name
503
-     * @param bool   $nullable
504
-     * @param null   $default_value
505
-     * @return EE_Slug_Field
506
-     */
507
-    public function createSlugField($table_column, $nice_name, $nullable = false, $default_value = null)
508
-    {
509
-        return $this->loader->getNew(
510
-            'EE_Slug_Field',
511
-            array($table_column, $nice_name, $nullable, $default_value)
512
-        );
513
-    }
514
-
515
-
516
-    /**
517
-     * @param string $table_column
518
-     * @param string $nice_name
519
-     * @param bool   $nullable
520
-     * @param null   $default_value
521
-     * @return EE_Trashed_Flag_Field
522
-     */
523
-    public function createTrashedFlagField($table_column, $nice_name, $nullable, $default_value = null)
524
-    {
525
-        return $this->loader->getNew(
526
-            'EE_Trashed_Flag_Field',
527
-            array($table_column, $nice_name, $nullable, $default_value)
528
-        );
529
-    }
530
-
531
-
532
-    /**
533
-     * @param string $table_column
534
-     * @param string $nice_name
535
-     * @param bool   $nullable
536
-     * @param mixed  $default_value
537
-     * @param array  $values                            If additional stati are to be used other than the default WP
538
-     *                                                  statuses, then they can be registered via this property. The
539
-     *                                                  format of the array should be as follows: array(
540
-     *                                                  'status_reference' => array(
541
-     *                                                  'label' => __('Status Reference Label', 'event_espresso'),
542
-     *                                                  'public' => true,                 // whether this status should
543
-     *                                                  be shown on the frontend of the site
544
-     *                                                  'exclude_from_search' => false,   // whether this status should
545
-     *                                                  be excluded from wp searches
546
-     *                                                  'show_in_admin_all_list' => true, // whether this status is
547
-     *                                                  included in queries for the admin "all" view in list table
548
-     *                                                  views.
549
-     *                                                  'show_in_admin_status_list' => true, // show in the list of
550
-     *                                                  statuses with post counts at the top of the admin list tables
551
-     *                                                  (i.e. Status Reference(2) )
552
-     *                                                  'label_count' => _n_noop(
553
-     *                                                  'Status Reference <span class="count">(%s)</span>',
554
-     *                                                  'Status References <span class="count">(%s)</span>'
555
-     *                                                  ),                                   // the text to display on
556
-     *                                                  the admin screen
557
-     *                                                  ( or you won't see your status count ).
558
-     *                                                  )
559
-     *                                                  )
560
-     * @link http://codex.wordpress.org/Function_Reference/register_post_status for more info
561
-     * @return EE_WP_Post_Status_Field
562
-     */
563
-    public function createWpPostStatusField(
564
-        $table_column,
565
-        $nice_name,
566
-        $nullable,
567
-        $default_value = null,
568
-        array $values = array()
569
-    ) {
570
-        return $this->loader->getNew(
571
-            'EE_WP_Post_Status_Field',
572
-            array($table_column, $nice_name, $nullable, $default_value, $values)
573
-        );
574
-    }
575
-
576
-
577
-    /**
578
-     * @param string $post_type
579
-     * @return EE_WP_Post_Type_Field
580
-     */
581
-    public function createWpPostTypeField($post_type)
582
-    {
583
-        return $this->loader->getNew('EE_WP_Post_Type_Field', array($post_type));
584
-    }
585
-
586
-
587
-    /**
588
-     * @param string $table_column
589
-     * @param string $nice_name
590
-     * @param bool   $nullable
591
-     * @return EE_WP_User_Field
592
-     */
593
-    public function createWpUserField($table_column, $nice_name, $nullable)
594
-    {
595
-        return $this->loader->getNew('EE_WP_User_Field', array($table_column, $nice_name, $nullable));
596
-    }
54
+	/**
55
+	 * @var LoaderInterface $loader
56
+	 */
57
+	private $loader;
58
+
59
+
60
+	/**
61
+	 * ModelFieldFactory constructor.
62
+	 *
63
+	 * @param LoaderInterface $loader
64
+	 */
65
+	public function __construct(LoaderInterface $loader)
66
+	{
67
+		$this->loader = $loader;
68
+	}
69
+
70
+
71
+	/**
72
+	 * @param string $table_column
73
+	 * @param string $nice_name
74
+	 * @param bool   $nullable
75
+	 * @param null   $default_value
76
+	 * @return EE_All_Caps_Text_Field
77
+	 */
78
+	public function createAllCapsTextField($table_column, $nice_name, $nullable, $default_value = null)
79
+	{
80
+		return $this->loader->getNew(
81
+			'EE_All_Caps_Text_Field',
82
+			array($table_column, $nice_name, $nullable, $default_value)
83
+		);
84
+	}
85
+
86
+
87
+	/**
88
+	 * @param string $table_column
89
+	 * @param string $nice_name
90
+	 * @param bool   $nullable
91
+	 * @param null   $default_value
92
+	 * @param string $model_name
93
+	 * @return EE_Any_Foreign_Model_Name_Field
94
+	 */
95
+	public function createAnyForeignModelNameField(
96
+		$table_column,
97
+		$nice_name,
98
+		$nullable,
99
+		$default_value = null,
100
+		$model_name
101
+	) {
102
+		return $this->loader->getNew(
103
+			'EE_Any_Foreign_Model_Name_Field',
104
+			array($table_column, $nice_name, $nullable, $default_value, $model_name)
105
+		);
106
+	}
107
+
108
+
109
+	/**
110
+	 * @param string $table_column
111
+	 * @param string $nice_name
112
+	 * @param bool   $nullable
113
+	 * @param null   $default_value
114
+	 * @return EE_Boolean_Field
115
+	 */
116
+	public function createBooleanField($table_column, $nice_name, $nullable, $default_value = null)
117
+	{
118
+		return $this->loader->getNew(
119
+			'EE_Boolean_Field',
120
+			array($table_column, $nice_name, $nullable, $default_value)
121
+		);
122
+	}
123
+
124
+
125
+	/**
126
+	 * @param string $table_column
127
+	 * @param string $nice_name
128
+	 * @param string $timezone_string
129
+	 * @param bool   $nullable
130
+	 * @param string $default_value
131
+	 * @throws EE_Error
132
+	 * @throws InvalidArgumentException
133
+	 * @return EE_Datetime_Field
134
+	 */
135
+	public function createDatetimeField(
136
+		$table_column,
137
+		$nice_name,
138
+		$nullable = false,
139
+		$default_value = EE_Datetime_Field::now
140
+	) {
141
+		return $this->loader->getNew(
142
+			'EE_Datetime_Field',
143
+			array(
144
+				$table_column,
145
+				$nice_name,
146
+				$nullable,
147
+				$default_value,
148
+			)
149
+		);
150
+	}
151
+
152
+
153
+	/**
154
+	 * @param string $table_column
155
+	 * @param string $nice_name
156
+	 * @param bool   $nullable
157
+	 * @param null   $default_value
158
+	 * @return EE_DB_Only_Float_Field
159
+	 */
160
+	public function createDbOnlyFloatField($table_column, $nice_name, $nullable, $default_value = null)
161
+	{
162
+		return $this->loader->getNew(
163
+			'EE_DB_Only_Float_Field',
164
+			array($table_column, $nice_name, $nullable, $default_value)
165
+		);
166
+	}
167
+
168
+
169
+	/**
170
+	 * @param string $table_column
171
+	 * @param string $nice_name
172
+	 * @param bool   $nullable
173
+	 * @param null   $default_value
174
+	 * @return EE_DB_Only_Int_Field
175
+	 */
176
+	public function createDbOnlyIntField($table_column, $nice_name, $nullable, $default_value = null)
177
+	{
178
+		return $this->loader->getNew(
179
+			'EE_DB_Only_Int_Field',
180
+			array($table_column, $nice_name, $nullable, $default_value)
181
+		);
182
+	}
183
+
184
+
185
+	/**
186
+	 * @param string $table_column
187
+	 * @param string $nice_name
188
+	 * @param bool   $nullable
189
+	 * @param null   $default_value
190
+	 * @return EE_DB_Only_Text_Field
191
+	 */
192
+	public function createDbOnlyTextField($table_column, $nice_name, $nullable, $default_value = null)
193
+	{
194
+		return $this->loader->getNew(
195
+			'EE_DB_Only_Text_Field',
196
+			array($table_column, $nice_name, $nullable, $default_value)
197
+		);
198
+	}
199
+
200
+
201
+	/**
202
+	 * @param string $table_column
203
+	 * @param string $nice_name
204
+	 * @param bool   $nullable
205
+	 * @param string $default_value
206
+	 * @return EE_Email_Field
207
+	 */
208
+	public function createEmailField($table_column, $nice_name, $nullable = true, $default_value = '')
209
+	{
210
+		return $this->loader->getNew(
211
+			'EE_Email_Field',
212
+			array($table_column, $nice_name, $nullable, $default_value)
213
+		);
214
+	}
215
+
216
+
217
+	/**
218
+	 * @param string $table_column
219
+	 * @param string $nice_name
220
+	 * @param bool   $nullable
221
+	 * @param null   $default_value
222
+	 * @param array  $allowed_enum_values keys are values to be used in the DB,
223
+	 *                                    values are how they should be displayed
224
+	 * @return EE_Enum_Integer_Field
225
+	 */
226
+	public function createEnumIntegerField(
227
+		$table_column,
228
+		$nice_name,
229
+		$nullable,
230
+		$default_value = null,
231
+		array $allowed_enum_values
232
+	) {
233
+		return $this->loader->getNew(
234
+			'EE_Enum_Integer_Field',
235
+			array($table_column, $nice_name, $nullable, $default_value, $allowed_enum_values)
236
+		);
237
+	}
238
+
239
+
240
+	/**
241
+	 * @param string $table_column
242
+	 * @param string $nice_name
243
+	 * @param bool   $nullable
244
+	 * @param null   $default_value
245
+	 * @param array  $allowed_enum_values keys are values to be used in the DB,
246
+	 *                                    values are how they should be displayed
247
+	 * @return EE_Enum_Text_Field
248
+	 */
249
+	public function createEnumTextField(
250
+		$table_column,
251
+		$nice_name,
252
+		$nullable,
253
+		$default_value,
254
+		array $allowed_enum_values
255
+	) {
256
+		return $this->loader->getNew(
257
+			'EE_Enum_Text_Field',
258
+			array($table_column, $nice_name, $nullable, $default_value, $allowed_enum_values)
259
+		);
260
+	}
261
+
262
+
263
+	/**
264
+	 * @param string $table_column
265
+	 * @param string $nice_name
266
+	 * @param bool   $nullable
267
+	 * @param null   $default_value
268
+	 * @return EE_Float_Field
269
+	 */
270
+	public function createFloatField($table_column, $nice_name, $nullable, $default_value = null)
271
+	{
272
+		return $this->loader->getNew(
273
+			'EE_Float_Field',
274
+			array($table_column, $nice_name, $nullable, $default_value)
275
+		);
276
+	}
277
+
278
+
279
+	/**
280
+	 * @param string $table_column
281
+	 * @param string $nice_name
282
+	 * @param bool   $nullable
283
+	 * @param null   $default_value
284
+	 * @param string $model_name
285
+	 * @return EE_Foreign_Key_Int_Field
286
+	 */
287
+	public function createForeignKeyIntField($table_column, $nice_name, $nullable, $default_value, $model_name)
288
+	{
289
+		return $this->loader->getNew(
290
+			'EE_Foreign_Key_Int_Field',
291
+			array($table_column, $nice_name, $nullable, $default_value, $model_name)
292
+		);
293
+	}
294
+
295
+
296
+	/**
297
+	 * @param string $table_column
298
+	 * @param string $nice_name
299
+	 * @param bool   $nullable
300
+	 * @param null   $default_value
301
+	 * @param string $model_name
302
+	 * @return EE_Foreign_Key_String_Field
303
+	 */
304
+	public function createForeignKeyStringField(
305
+		$table_column,
306
+		$nice_name,
307
+		$nullable,
308
+		$default_value,
309
+		$model_name
310
+	) {
311
+		return $this->loader->getNew(
312
+			'EE_Foreign_Key_String_Field',
313
+			array($table_column, $nice_name, $nullable, $default_value, $model_name)
314
+		);
315
+	}
316
+
317
+
318
+	/**
319
+	 * @param string $table_column
320
+	 * @param string $nice_name
321
+	 * @param bool   $nullable
322
+	 * @param null   $default_value
323
+	 * @return EE_Full_HTML_Field
324
+	 */
325
+	public function createFullHtmlField($table_column, $nice_name, $nullable, $default_value = null)
326
+	{
327
+		return $this->loader->getNew(
328
+			'EE_Full_HTML_Field',
329
+			array($table_column, $nice_name, $nullable, $default_value)
330
+		);
331
+	}
332
+
333
+
334
+	/**
335
+	 * @param string $table_column
336
+	 * @param string $nice_name
337
+	 * @param bool   $nullable
338
+	 * @param null   $default_value
339
+	 * @return EE_Infinite_Integer_Field
340
+	 */
341
+	public function createInfiniteIntegerField($table_column, $nice_name, $nullable, $default_value = null)
342
+	{
343
+		return $this->loader->getNew(
344
+			'EE_Infinite_Integer_Field',
345
+			array($table_column, $nice_name, $nullable, $default_value)
346
+		);
347
+	}
348
+
349
+
350
+	/**
351
+	 * @param string  $table_column
352
+	 * @param string  $nice_name
353
+	 * @param bool    $nullable
354
+	 * @param integer $default_value
355
+	 * @return EE_Integer_Field
356
+	 */
357
+	public function createIntegerField($table_column, $nice_name, $nullable = false, $default_value = 0)
358
+	{
359
+		return $this->loader->getNew(
360
+			'EE_Integer_Field',
361
+			array($table_column, $nice_name, $nullable, $default_value)
362
+		);
363
+	}
364
+
365
+
366
+	/**
367
+	 * @param string $table_column
368
+	 * @param string $nice_name
369
+	 * @param bool   $nullable
370
+	 * @param null   $default_value
371
+	 * @return EE_Maybe_Serialized_Simple_HTML_Field
372
+	 */
373
+	public function createMaybeSerializedSimpleHtmlField($table_column, $nice_name, $nullable, $default_value = null)
374
+	{
375
+		return $this->loader->getNew(
376
+			'EE_Maybe_Serialized_Simple_HTML_Field',
377
+			array($table_column, $nice_name, $nullable, $default_value)
378
+		);
379
+	}
380
+
381
+
382
+	/**
383
+	 * @param string $table_column
384
+	 * @param string $nice_name
385
+	 * @param bool   $nullable
386
+	 * @param null   $default_value
387
+	 * @return EE_Maybe_Serialized_Text_Field
388
+	 */
389
+	public function createMaybeSerializedTextField($table_column, $nice_name, $nullable, $default_value = null)
390
+	{
391
+		return $this->loader->getNew(
392
+			'EE_Maybe_Serialized_Text_Field',
393
+			array($table_column, $nice_name, $nullable, $default_value)
394
+		);
395
+	}
396
+
397
+
398
+	/**
399
+	 * @param string $table_column
400
+	 * @param string $nice_name
401
+	 * @param bool   $nullable
402
+	 * @param null   $default_value
403
+	 * @return EE_Money_Field
404
+	 */
405
+	public function createMoneyField($table_column, $nice_name, $nullable, $default_value = null)
406
+	{
407
+		return $this->loader->getNew(
408
+			'EE_Money_Field',
409
+			array($table_column, $nice_name, $nullable, $default_value)
410
+		);
411
+	}
412
+
413
+
414
+	/**
415
+	 * @param string $table_column
416
+	 * @param string $nice_name
417
+	 * @param bool   $nullable
418
+	 * @param string $default_value
419
+	 * @return EE_Plain_Text_Field
420
+	 */
421
+	public function createPlainTextField($table_column, $nice_name, $nullable = true, $default_value = '')
422
+	{
423
+		return $this->loader->getNew(
424
+			'EE_Plain_Text_Field',
425
+			array($table_column, $nice_name, $nullable, $default_value)
426
+		);
427
+	}
428
+
429
+
430
+	/**
431
+	 * @param string $table_column
432
+	 * @param string $nice_name
433
+	 * @param bool   $nullable
434
+	 * @param null   $default_value
435
+	 * @return EE_Post_Content_Field
436
+	 */
437
+	public function createPostContentField($table_column, $nice_name, $nullable, $default_value = null)
438
+	{
439
+		return $this->loader->getNew(
440
+			'EE_Post_Content_Field',
441
+			array($table_column, $nice_name, $nullable, $default_value)
442
+		);
443
+	}
444
+
445
+
446
+	/**
447
+	 * @param string $table_column
448
+	 * @param string $nice_name
449
+	 * @return EE_Primary_Key_Int_Field
450
+	 */
451
+	public function createPrimaryKeyIntField($table_column, $nice_name)
452
+	{
453
+		return $this->loader->getNew('EE_Primary_Key_Int_Field', array($table_column, $nice_name));
454
+	}
455
+
456
+
457
+	/**
458
+	 * @param string $table_column
459
+	 * @param string $nice_name
460
+	 * @return EE_Primary_Key_String_Field
461
+	 */
462
+	public function createPrimaryKeyStringField($table_column, $nice_name)
463
+	{
464
+		return $this->loader->getNew('EE_Primary_Key_String_Field', array($table_column, $nice_name));
465
+	}
466
+
467
+
468
+	/**
469
+	 * @param string $table_column
470
+	 * @param string $nice_name
471
+	 * @param bool   $nullable
472
+	 * @param null   $default_value
473
+	 * @return EE_Serialized_Text_Field
474
+	 */
475
+	public function createSerializedTextField($table_column, $nice_name, $nullable, $default_value = null)
476
+	{
477
+		return $this->loader->getNew(
478
+			'EE_Serialized_Text_Field',
479
+			array($table_column, $nice_name, $nullable, $default_value)
480
+		);
481
+	}
482
+
483
+
484
+	/**
485
+	 * @param string $table_column
486
+	 * @param string $nice_name
487
+	 * @param bool   $nullable
488
+	 * @param null   $default_value
489
+	 * @return EE_Simple_HTML_Field
490
+	 */
491
+	public function createSimpleHtmlField($table_column, $nice_name, $nullable, $default_value = null)
492
+	{
493
+		return $this->loader->getNew(
494
+			'EE_Simple_HTML_Field',
495
+			array($table_column, $nice_name, $nullable, $default_value)
496
+		);
497
+	}
498
+
499
+
500
+	/**
501
+	 * @param string $table_column
502
+	 * @param string $nice_name
503
+	 * @param bool   $nullable
504
+	 * @param null   $default_value
505
+	 * @return EE_Slug_Field
506
+	 */
507
+	public function createSlugField($table_column, $nice_name, $nullable = false, $default_value = null)
508
+	{
509
+		return $this->loader->getNew(
510
+			'EE_Slug_Field',
511
+			array($table_column, $nice_name, $nullable, $default_value)
512
+		);
513
+	}
514
+
515
+
516
+	/**
517
+	 * @param string $table_column
518
+	 * @param string $nice_name
519
+	 * @param bool   $nullable
520
+	 * @param null   $default_value
521
+	 * @return EE_Trashed_Flag_Field
522
+	 */
523
+	public function createTrashedFlagField($table_column, $nice_name, $nullable, $default_value = null)
524
+	{
525
+		return $this->loader->getNew(
526
+			'EE_Trashed_Flag_Field',
527
+			array($table_column, $nice_name, $nullable, $default_value)
528
+		);
529
+	}
530
+
531
+
532
+	/**
533
+	 * @param string $table_column
534
+	 * @param string $nice_name
535
+	 * @param bool   $nullable
536
+	 * @param mixed  $default_value
537
+	 * @param array  $values                            If additional stati are to be used other than the default WP
538
+	 *                                                  statuses, then they can be registered via this property. The
539
+	 *                                                  format of the array should be as follows: array(
540
+	 *                                                  'status_reference' => array(
541
+	 *                                                  'label' => __('Status Reference Label', 'event_espresso'),
542
+	 *                                                  'public' => true,                 // whether this status should
543
+	 *                                                  be shown on the frontend of the site
544
+	 *                                                  'exclude_from_search' => false,   // whether this status should
545
+	 *                                                  be excluded from wp searches
546
+	 *                                                  'show_in_admin_all_list' => true, // whether this status is
547
+	 *                                                  included in queries for the admin "all" view in list table
548
+	 *                                                  views.
549
+	 *                                                  'show_in_admin_status_list' => true, // show in the list of
550
+	 *                                                  statuses with post counts at the top of the admin list tables
551
+	 *                                                  (i.e. Status Reference(2) )
552
+	 *                                                  'label_count' => _n_noop(
553
+	 *                                                  'Status Reference <span class="count">(%s)</span>',
554
+	 *                                                  'Status References <span class="count">(%s)</span>'
555
+	 *                                                  ),                                   // the text to display on
556
+	 *                                                  the admin screen
557
+	 *                                                  ( or you won't see your status count ).
558
+	 *                                                  )
559
+	 *                                                  )
560
+	 * @link http://codex.wordpress.org/Function_Reference/register_post_status for more info
561
+	 * @return EE_WP_Post_Status_Field
562
+	 */
563
+	public function createWpPostStatusField(
564
+		$table_column,
565
+		$nice_name,
566
+		$nullable,
567
+		$default_value = null,
568
+		array $values = array()
569
+	) {
570
+		return $this->loader->getNew(
571
+			'EE_WP_Post_Status_Field',
572
+			array($table_column, $nice_name, $nullable, $default_value, $values)
573
+		);
574
+	}
575
+
576
+
577
+	/**
578
+	 * @param string $post_type
579
+	 * @return EE_WP_Post_Type_Field
580
+	 */
581
+	public function createWpPostTypeField($post_type)
582
+	{
583
+		return $this->loader->getNew('EE_WP_Post_Type_Field', array($post_type));
584
+	}
585
+
586
+
587
+	/**
588
+	 * @param string $table_column
589
+	 * @param string $nice_name
590
+	 * @param bool   $nullable
591
+	 * @return EE_WP_User_Field
592
+	 */
593
+	public function createWpUserField($table_column, $nice_name, $nullable)
594
+	{
595
+		return $this->loader->getNew('EE_WP_User_Field', array($table_column, $nice_name, $nullable));
596
+	}
597 597
 }
Please login to merge, or discard this patch.
core/EE_Request_Handler.core.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 
276 276
 
277 277
     /**
278
-     * @param $string
278
+     * @param string $string
279 279
      * @return void
280 280
      */
281 281
     public function add_output($string)
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
 
328 328
 
329 329
     /**
330
-     * @return    mixed
330
+     * @return    boolean
331 331
      */
332 332
     public function is_espresso_page()
333 333
     {
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
     /**
390 390
      * remove param
391 391
      *
392
-     * @param $key
392
+     * @param string $key
393 393
      * @return    void
394 394
      */
395 395
     public function un_set($key)
Please login to merge, or discard this patch.
Indentation   +365 added lines, -365 removed lines patch added patch discarded remove patch
@@ -12,369 +12,369 @@
 block discarded – undo
12 12
 final class EE_Request_Handler implements InterminableInterface
13 13
 {
14 14
 
15
-    /**
16
-     * @var EE_Request $request
17
-     */
18
-    private $request;
19
-
20
-    /**
21
-     * @var array $_notice
22
-     */
23
-    private $_notice = array();
24
-
25
-    /**
26
-     * rendered output to be returned to WP
27
-     *
28
-     * @var string $_output
29
-     */
30
-    private $_output = '';
31
-
32
-    /**
33
-     * whether current request is via AJAX
34
-     *
35
-     * @var boolean $ajax
36
-     */
37
-    public $ajax = false;
38
-
39
-    /**
40
-     * whether current request is via AJAX from the frontend of the site
41
-     *
42
-     * @var boolean $front_ajax
43
-     */
44
-    public $front_ajax = false;
45
-
46
-
47
-    /**
48
-     * @param  EE_Request $request
49
-     */
50
-    public function __construct(EE_Request $request)
51
-    {
52
-        $this->request = $request;
53
-        $this->ajax = $this->request->ajax;
54
-        $this->front_ajax = $this->request->front_ajax;
55
-        do_action('AHEE__EE_Request_Handler__construct__complete');
56
-    }
57
-
58
-
59
-    /**
60
-     * @param WP $wp
61
-     * @return void
62
-     * @throws EE_Error
63
-     * @throws ReflectionException
64
-     */
65
-    public function parse_request($wp = null)
66
-    {
67
-        // if somebody forgot to provide us with WP, that's ok because its global
68
-        if (! $wp instanceof WP) {
69
-            global $wp;
70
-        }
71
-        $this->set_request_vars($wp);
72
-    }
73
-
74
-
75
-    /**
76
-     * @param WP $wp
77
-     * @return void
78
-     * @throws EE_Error
79
-     * @throws ReflectionException
80
-     */
81
-    public function set_request_vars($wp = null)
82
-    {
83
-        if (! is_admin()) {
84
-            // set request post_id
85
-            $this->request->set('post_id', $this->get_post_id_from_request($wp));
86
-            // set request post name
87
-            $this->request->set('post_name', $this->get_post_name_from_request($wp));
88
-            // set request post_type
89
-            $this->request->set('post_type', $this->get_post_type_from_request($wp));
90
-            // true or false ? is this page being used by EE ?
91
-            $this->set_espresso_page();
92
-        }
93
-    }
94
-
95
-
96
-    /**
97
-     * @param WP $wp
98
-     * @return int
99
-     */
100
-    public function get_post_id_from_request($wp = null)
101
-    {
102
-        if (! $wp instanceof WP) {
103
-            global $wp;
104
-        }
105
-        $post_id = null;
106
-        if (isset($wp->query_vars['p'])) {
107
-            $post_id = $wp->query_vars['p'];
108
-        }
109
-        if (! $post_id && isset($wp->query_vars['page_id'])) {
110
-            $post_id = $wp->query_vars['page_id'];
111
-        }
112
-        if (! $post_id && $wp->request !== null && is_numeric(basename($wp->request))) {
113
-            $post_id = basename($wp->request);
114
-        }
115
-        return $post_id;
116
-    }
117
-
118
-
119
-    /**
120
-     * @param WP $wp
121
-     * @return string
122
-     */
123
-    public function get_post_name_from_request($wp = null)
124
-    {
125
-        if (! $wp instanceof WP) {
126
-            global $wp;
127
-        }
128
-        $post_name = null;
129
-        if (isset($wp->query_vars['name']) && ! empty($wp->query_vars['name'])) {
130
-            $post_name = $wp->query_vars['name'];
131
-        }
132
-        if (! $post_name && isset($wp->query_vars['pagename']) && ! empty($wp->query_vars['pagename'])) {
133
-            $post_name = $wp->query_vars['pagename'];
134
-        }
135
-        if (! $post_name && $wp->request !== null && ! empty($wp->request)) {
136
-            $possible_post_name = basename($wp->request);
137
-            if (! is_numeric($possible_post_name)) {
138
-                /** @type WPDB $wpdb */
139
-                global $wpdb;
140
-                $SQL =
141
-                    "SELECT ID from {$wpdb->posts} WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND post_name=%s";
142
-                $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
143
-                if ($possible_post_name) {
144
-                    $post_name = $possible_post_name;
145
-                }
146
-            }
147
-        }
148
-        if (! $post_name && $this->get('post_id')) {
149
-            /** @type WPDB $wpdb */
150
-            global $wpdb;
151
-            $SQL =
152
-                "SELECT post_name from {$wpdb->posts} WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND ID=%d";
153
-            $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->get('post_id')));
154
-            if ($possible_post_name) {
155
-                $post_name = $possible_post_name;
156
-            }
157
-        }
158
-        return $post_name;
159
-    }
160
-
161
-
162
-    /**
163
-     * @param WP $wp
164
-     * @return mixed
165
-     */
166
-    public function get_post_type_from_request($wp = null)
167
-    {
168
-        if (! $wp instanceof WP) {
169
-            global $wp;
170
-        }
171
-        return isset($wp->query_vars['post_type'])
172
-            ? $wp->query_vars['post_type']
173
-            : null;
174
-    }
175
-
176
-
177
-    /**
178
-     * Just a helper method for getting the url for the displayed page.
179
-     *
180
-     * @param  WP $wp
181
-     * @return string
182
-     */
183
-    public function get_current_page_permalink($wp = null)
184
-    {
185
-        $post_id = $this->get_post_id_from_request($wp);
186
-        if ($post_id) {
187
-            $current_page_permalink = get_permalink($post_id);
188
-        } else {
189
-            if (! $wp instanceof WP) {
190
-                global $wp;
191
-            }
192
-            if ($wp->request) {
193
-                $current_page_permalink = site_url($wp->request);
194
-            } else {
195
-                $current_page_permalink = esc_url(site_url($_SERVER['REQUEST_URI']));
196
-            }
197
-        }
198
-        return $current_page_permalink;
199
-    }
200
-
201
-
202
-    /**
203
-     * @return bool
204
-     * @throws EE_Error
205
-     * @throws ReflectionException
206
-     */
207
-    public function test_for_espresso_page()
208
-    {
209
-        global $wp;
210
-        /** @type EE_CPT_Strategy $EE_CPT_Strategy */
211
-        $EE_CPT_Strategy = EE_Registry::instance()->load_core('CPT_Strategy');
212
-        $espresso_CPT_taxonomies = $EE_CPT_Strategy->get_CPT_taxonomies();
213
-        if (is_array($espresso_CPT_taxonomies)) {
214
-            foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
215
-                if (isset($wp->query_vars, $wp->query_vars[ $espresso_CPT_taxonomy ])) {
216
-                    return true;
217
-                }
218
-            }
219
-        }
220
-        // load espresso CPT endpoints
221
-        $espresso_CPT_endpoints = $EE_CPT_Strategy->get_CPT_endpoints();
222
-        $post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
223
-        $post_types = (array) $this->get('post_type');
224
-        foreach ($post_types as $post_type) {
225
-            // was a post name passed ?
226
-            if (isset($post_type_CPT_endpoints[ $post_type ])) {
227
-                // kk we know this is an espresso page, but is it a specific post ?
228
-                if (! $this->get('post_name')) {
229
-                    // there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
230
-                    $post_name = isset($post_type_CPT_endpoints[ $this->get('post_type') ])
231
-                        ? $post_type_CPT_endpoints[ $this->get('post_type') ]
232
-                        : '';
233
-                    // if the post type matches on of our then set the endpoint
234
-                    if ($post_name) {
235
-                        $this->set('post_name', $post_name);
236
-                    }
237
-                }
238
-                return true;
239
-            }
240
-        }
241
-        return false;
242
-    }
243
-
244
-    /**
245
-     * @param $key
246
-     * @param $value
247
-     * @return    void
248
-     */
249
-    public function set_notice($key, $value)
250
-    {
251
-        $this->_notice[ $key ] = $value;
252
-    }
253
-
254
-
255
-    /**
256
-     * @param $key
257
-     * @return    mixed
258
-     */
259
-    public function get_notice($key)
260
-    {
261
-        return isset($this->_notice[ $key ])
262
-            ? $this->_notice[ $key ]
263
-            : null;
264
-    }
265
-
266
-
267
-    /**
268
-     * @param $string
269
-     * @return void
270
-     */
271
-    public function add_output($string)
272
-    {
273
-        $this->_output .= $string;
274
-    }
275
-
276
-
277
-    /**
278
-     * @return string
279
-     */
280
-    public function get_output()
281
-    {
282
-        return $this->_output;
283
-    }
284
-
285
-
286
-    /**
287
-     * @param $item
288
-     * @param $key
289
-     */
290
-    public function sanitize_text_field_for_array_walk(&$item, &$key)
291
-    {
292
-        $item = strpos($item, 'email') !== false
293
-            ? sanitize_email($item)
294
-            : sanitize_text_field($item);
295
-    }
296
-
297
-
298
-    /**
299
-     * @param null|bool $value
300
-     * @return void
301
-     * @throws EE_Error
302
-     * @throws ReflectionException
303
-     */
304
-    public function set_espresso_page($value = null)
305
-    {
306
-        $this->request->set(
307
-            'is_espresso_page',
308
-            ! empty($value)
309
-                ? $value
310
-                : $this->test_for_espresso_page()
311
-        );
312
-    }
313
-
314
-
315
-    /**
316
-     * @return    mixed
317
-     */
318
-    public function is_espresso_page()
319
-    {
320
-        return $this->request->is_set('is_espresso_page');
321
-    }
322
-
323
-
324
-    /**
325
-     * returns contents of $_REQUEST
326
-     *
327
-     * @return array
328
-     */
329
-    public function params()
330
-    {
331
-        return $this->request->params();
332
-    }
333
-
334
-
335
-    /**
336
-     * @param      $key
337
-     * @param      $value
338
-     * @param bool $override_ee
339
-     * @return    void
340
-     */
341
-    public function set($key, $value, $override_ee = false)
342
-    {
343
-        $this->request->set($key, $value, $override_ee);
344
-    }
345
-
346
-
347
-    /**
348
-     * @param      $key
349
-     * @param null $default
350
-     * @return    mixed
351
-     */
352
-    public function get($key, $default = null)
353
-    {
354
-        return $this->request->get($key, $default);
355
-    }
356
-
357
-
358
-    /**
359
-     * check if param exists
360
-     *
361
-     * @param $key
362
-     * @return    boolean
363
-     */
364
-    public function is_set($key)
365
-    {
366
-        return $this->request->is_set($key);
367
-    }
368
-
369
-
370
-    /**
371
-     * remove param
372
-     *
373
-     * @param $key
374
-     * @return    void
375
-     */
376
-    public function un_set($key)
377
-    {
378
-        $this->request->un_set($key);
379
-    }
15
+	/**
16
+	 * @var EE_Request $request
17
+	 */
18
+	private $request;
19
+
20
+	/**
21
+	 * @var array $_notice
22
+	 */
23
+	private $_notice = array();
24
+
25
+	/**
26
+	 * rendered output to be returned to WP
27
+	 *
28
+	 * @var string $_output
29
+	 */
30
+	private $_output = '';
31
+
32
+	/**
33
+	 * whether current request is via AJAX
34
+	 *
35
+	 * @var boolean $ajax
36
+	 */
37
+	public $ajax = false;
38
+
39
+	/**
40
+	 * whether current request is via AJAX from the frontend of the site
41
+	 *
42
+	 * @var boolean $front_ajax
43
+	 */
44
+	public $front_ajax = false;
45
+
46
+
47
+	/**
48
+	 * @param  EE_Request $request
49
+	 */
50
+	public function __construct(EE_Request $request)
51
+	{
52
+		$this->request = $request;
53
+		$this->ajax = $this->request->ajax;
54
+		$this->front_ajax = $this->request->front_ajax;
55
+		do_action('AHEE__EE_Request_Handler__construct__complete');
56
+	}
57
+
58
+
59
+	/**
60
+	 * @param WP $wp
61
+	 * @return void
62
+	 * @throws EE_Error
63
+	 * @throws ReflectionException
64
+	 */
65
+	public function parse_request($wp = null)
66
+	{
67
+		// if somebody forgot to provide us with WP, that's ok because its global
68
+		if (! $wp instanceof WP) {
69
+			global $wp;
70
+		}
71
+		$this->set_request_vars($wp);
72
+	}
73
+
74
+
75
+	/**
76
+	 * @param WP $wp
77
+	 * @return void
78
+	 * @throws EE_Error
79
+	 * @throws ReflectionException
80
+	 */
81
+	public function set_request_vars($wp = null)
82
+	{
83
+		if (! is_admin()) {
84
+			// set request post_id
85
+			$this->request->set('post_id', $this->get_post_id_from_request($wp));
86
+			// set request post name
87
+			$this->request->set('post_name', $this->get_post_name_from_request($wp));
88
+			// set request post_type
89
+			$this->request->set('post_type', $this->get_post_type_from_request($wp));
90
+			// true or false ? is this page being used by EE ?
91
+			$this->set_espresso_page();
92
+		}
93
+	}
94
+
95
+
96
+	/**
97
+	 * @param WP $wp
98
+	 * @return int
99
+	 */
100
+	public function get_post_id_from_request($wp = null)
101
+	{
102
+		if (! $wp instanceof WP) {
103
+			global $wp;
104
+		}
105
+		$post_id = null;
106
+		if (isset($wp->query_vars['p'])) {
107
+			$post_id = $wp->query_vars['p'];
108
+		}
109
+		if (! $post_id && isset($wp->query_vars['page_id'])) {
110
+			$post_id = $wp->query_vars['page_id'];
111
+		}
112
+		if (! $post_id && $wp->request !== null && is_numeric(basename($wp->request))) {
113
+			$post_id = basename($wp->request);
114
+		}
115
+		return $post_id;
116
+	}
117
+
118
+
119
+	/**
120
+	 * @param WP $wp
121
+	 * @return string
122
+	 */
123
+	public function get_post_name_from_request($wp = null)
124
+	{
125
+		if (! $wp instanceof WP) {
126
+			global $wp;
127
+		}
128
+		$post_name = null;
129
+		if (isset($wp->query_vars['name']) && ! empty($wp->query_vars['name'])) {
130
+			$post_name = $wp->query_vars['name'];
131
+		}
132
+		if (! $post_name && isset($wp->query_vars['pagename']) && ! empty($wp->query_vars['pagename'])) {
133
+			$post_name = $wp->query_vars['pagename'];
134
+		}
135
+		if (! $post_name && $wp->request !== null && ! empty($wp->request)) {
136
+			$possible_post_name = basename($wp->request);
137
+			if (! is_numeric($possible_post_name)) {
138
+				/** @type WPDB $wpdb */
139
+				global $wpdb;
140
+				$SQL =
141
+					"SELECT ID from {$wpdb->posts} WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND post_name=%s";
142
+				$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
143
+				if ($possible_post_name) {
144
+					$post_name = $possible_post_name;
145
+				}
146
+			}
147
+		}
148
+		if (! $post_name && $this->get('post_id')) {
149
+			/** @type WPDB $wpdb */
150
+			global $wpdb;
151
+			$SQL =
152
+				"SELECT post_name from {$wpdb->posts} WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND ID=%d";
153
+			$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->get('post_id')));
154
+			if ($possible_post_name) {
155
+				$post_name = $possible_post_name;
156
+			}
157
+		}
158
+		return $post_name;
159
+	}
160
+
161
+
162
+	/**
163
+	 * @param WP $wp
164
+	 * @return mixed
165
+	 */
166
+	public function get_post_type_from_request($wp = null)
167
+	{
168
+		if (! $wp instanceof WP) {
169
+			global $wp;
170
+		}
171
+		return isset($wp->query_vars['post_type'])
172
+			? $wp->query_vars['post_type']
173
+			: null;
174
+	}
175
+
176
+
177
+	/**
178
+	 * Just a helper method for getting the url for the displayed page.
179
+	 *
180
+	 * @param  WP $wp
181
+	 * @return string
182
+	 */
183
+	public function get_current_page_permalink($wp = null)
184
+	{
185
+		$post_id = $this->get_post_id_from_request($wp);
186
+		if ($post_id) {
187
+			$current_page_permalink = get_permalink($post_id);
188
+		} else {
189
+			if (! $wp instanceof WP) {
190
+				global $wp;
191
+			}
192
+			if ($wp->request) {
193
+				$current_page_permalink = site_url($wp->request);
194
+			} else {
195
+				$current_page_permalink = esc_url(site_url($_SERVER['REQUEST_URI']));
196
+			}
197
+		}
198
+		return $current_page_permalink;
199
+	}
200
+
201
+
202
+	/**
203
+	 * @return bool
204
+	 * @throws EE_Error
205
+	 * @throws ReflectionException
206
+	 */
207
+	public function test_for_espresso_page()
208
+	{
209
+		global $wp;
210
+		/** @type EE_CPT_Strategy $EE_CPT_Strategy */
211
+		$EE_CPT_Strategy = EE_Registry::instance()->load_core('CPT_Strategy');
212
+		$espresso_CPT_taxonomies = $EE_CPT_Strategy->get_CPT_taxonomies();
213
+		if (is_array($espresso_CPT_taxonomies)) {
214
+			foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
215
+				if (isset($wp->query_vars, $wp->query_vars[ $espresso_CPT_taxonomy ])) {
216
+					return true;
217
+				}
218
+			}
219
+		}
220
+		// load espresso CPT endpoints
221
+		$espresso_CPT_endpoints = $EE_CPT_Strategy->get_CPT_endpoints();
222
+		$post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
223
+		$post_types = (array) $this->get('post_type');
224
+		foreach ($post_types as $post_type) {
225
+			// was a post name passed ?
226
+			if (isset($post_type_CPT_endpoints[ $post_type ])) {
227
+				// kk we know this is an espresso page, but is it a specific post ?
228
+				if (! $this->get('post_name')) {
229
+					// there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
230
+					$post_name = isset($post_type_CPT_endpoints[ $this->get('post_type') ])
231
+						? $post_type_CPT_endpoints[ $this->get('post_type') ]
232
+						: '';
233
+					// if the post type matches on of our then set the endpoint
234
+					if ($post_name) {
235
+						$this->set('post_name', $post_name);
236
+					}
237
+				}
238
+				return true;
239
+			}
240
+		}
241
+		return false;
242
+	}
243
+
244
+	/**
245
+	 * @param $key
246
+	 * @param $value
247
+	 * @return    void
248
+	 */
249
+	public function set_notice($key, $value)
250
+	{
251
+		$this->_notice[ $key ] = $value;
252
+	}
253
+
254
+
255
+	/**
256
+	 * @param $key
257
+	 * @return    mixed
258
+	 */
259
+	public function get_notice($key)
260
+	{
261
+		return isset($this->_notice[ $key ])
262
+			? $this->_notice[ $key ]
263
+			: null;
264
+	}
265
+
266
+
267
+	/**
268
+	 * @param $string
269
+	 * @return void
270
+	 */
271
+	public function add_output($string)
272
+	{
273
+		$this->_output .= $string;
274
+	}
275
+
276
+
277
+	/**
278
+	 * @return string
279
+	 */
280
+	public function get_output()
281
+	{
282
+		return $this->_output;
283
+	}
284
+
285
+
286
+	/**
287
+	 * @param $item
288
+	 * @param $key
289
+	 */
290
+	public function sanitize_text_field_for_array_walk(&$item, &$key)
291
+	{
292
+		$item = strpos($item, 'email') !== false
293
+			? sanitize_email($item)
294
+			: sanitize_text_field($item);
295
+	}
296
+
297
+
298
+	/**
299
+	 * @param null|bool $value
300
+	 * @return void
301
+	 * @throws EE_Error
302
+	 * @throws ReflectionException
303
+	 */
304
+	public function set_espresso_page($value = null)
305
+	{
306
+		$this->request->set(
307
+			'is_espresso_page',
308
+			! empty($value)
309
+				? $value
310
+				: $this->test_for_espresso_page()
311
+		);
312
+	}
313
+
314
+
315
+	/**
316
+	 * @return    mixed
317
+	 */
318
+	public function is_espresso_page()
319
+	{
320
+		return $this->request->is_set('is_espresso_page');
321
+	}
322
+
323
+
324
+	/**
325
+	 * returns contents of $_REQUEST
326
+	 *
327
+	 * @return array
328
+	 */
329
+	public function params()
330
+	{
331
+		return $this->request->params();
332
+	}
333
+
334
+
335
+	/**
336
+	 * @param      $key
337
+	 * @param      $value
338
+	 * @param bool $override_ee
339
+	 * @return    void
340
+	 */
341
+	public function set($key, $value, $override_ee = false)
342
+	{
343
+		$this->request->set($key, $value, $override_ee);
344
+	}
345
+
346
+
347
+	/**
348
+	 * @param      $key
349
+	 * @param null $default
350
+	 * @return    mixed
351
+	 */
352
+	public function get($key, $default = null)
353
+	{
354
+		return $this->request->get($key, $default);
355
+	}
356
+
357
+
358
+	/**
359
+	 * check if param exists
360
+	 *
361
+	 * @param $key
362
+	 * @return    boolean
363
+	 */
364
+	public function is_set($key)
365
+	{
366
+		return $this->request->is_set($key);
367
+	}
368
+
369
+
370
+	/**
371
+	 * remove param
372
+	 *
373
+	 * @param $key
374
+	 * @return    void
375
+	 */
376
+	public function un_set($key)
377
+	{
378
+		$this->request->un_set($key);
379
+	}
380 380
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
     public function parse_request($wp = null)
66 66
     {
67 67
         // if somebody forgot to provide us with WP, that's ok because its global
68
-        if (! $wp instanceof WP) {
68
+        if ( ! $wp instanceof WP) {
69 69
             global $wp;
70 70
         }
71 71
         $this->set_request_vars($wp);
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
      */
81 81
     public function set_request_vars($wp = null)
82 82
     {
83
-        if (! is_admin()) {
83
+        if ( ! is_admin()) {
84 84
             // set request post_id
85 85
             $this->request->set('post_id', $this->get_post_id_from_request($wp));
86 86
             // set request post name
@@ -99,17 +99,17 @@  discard block
 block discarded – undo
99 99
      */
100 100
     public function get_post_id_from_request($wp = null)
101 101
     {
102
-        if (! $wp instanceof WP) {
102
+        if ( ! $wp instanceof WP) {
103 103
             global $wp;
104 104
         }
105 105
         $post_id = null;
106 106
         if (isset($wp->query_vars['p'])) {
107 107
             $post_id = $wp->query_vars['p'];
108 108
         }
109
-        if (! $post_id && isset($wp->query_vars['page_id'])) {
109
+        if ( ! $post_id && isset($wp->query_vars['page_id'])) {
110 110
             $post_id = $wp->query_vars['page_id'];
111 111
         }
112
-        if (! $post_id && $wp->request !== null && is_numeric(basename($wp->request))) {
112
+        if ( ! $post_id && $wp->request !== null && is_numeric(basename($wp->request))) {
113 113
             $post_id = basename($wp->request);
114 114
         }
115 115
         return $post_id;
@@ -122,19 +122,19 @@  discard block
 block discarded – undo
122 122
      */
123 123
     public function get_post_name_from_request($wp = null)
124 124
     {
125
-        if (! $wp instanceof WP) {
125
+        if ( ! $wp instanceof WP) {
126 126
             global $wp;
127 127
         }
128 128
         $post_name = null;
129 129
         if (isset($wp->query_vars['name']) && ! empty($wp->query_vars['name'])) {
130 130
             $post_name = $wp->query_vars['name'];
131 131
         }
132
-        if (! $post_name && isset($wp->query_vars['pagename']) && ! empty($wp->query_vars['pagename'])) {
132
+        if ( ! $post_name && isset($wp->query_vars['pagename']) && ! empty($wp->query_vars['pagename'])) {
133 133
             $post_name = $wp->query_vars['pagename'];
134 134
         }
135
-        if (! $post_name && $wp->request !== null && ! empty($wp->request)) {
135
+        if ( ! $post_name && $wp->request !== null && ! empty($wp->request)) {
136 136
             $possible_post_name = basename($wp->request);
137
-            if (! is_numeric($possible_post_name)) {
137
+            if ( ! is_numeric($possible_post_name)) {
138 138
                 /** @type WPDB $wpdb */
139 139
                 global $wpdb;
140 140
                 $SQL =
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
                 }
146 146
             }
147 147
         }
148
-        if (! $post_name && $this->get('post_id')) {
148
+        if ( ! $post_name && $this->get('post_id')) {
149 149
             /** @type WPDB $wpdb */
150 150
             global $wpdb;
151 151
             $SQL =
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
      */
166 166
     public function get_post_type_from_request($wp = null)
167 167
     {
168
-        if (! $wp instanceof WP) {
168
+        if ( ! $wp instanceof WP) {
169 169
             global $wp;
170 170
         }
171 171
         return isset($wp->query_vars['post_type'])
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
         if ($post_id) {
187 187
             $current_page_permalink = get_permalink($post_id);
188 188
         } else {
189
-            if (! $wp instanceof WP) {
189
+            if ( ! $wp instanceof WP) {
190 190
                 global $wp;
191 191
             }
192 192
             if ($wp->request) {
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
         $espresso_CPT_taxonomies = $EE_CPT_Strategy->get_CPT_taxonomies();
213 213
         if (is_array($espresso_CPT_taxonomies)) {
214 214
             foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
215
-                if (isset($wp->query_vars, $wp->query_vars[ $espresso_CPT_taxonomy ])) {
215
+                if (isset($wp->query_vars, $wp->query_vars[$espresso_CPT_taxonomy])) {
216 216
                     return true;
217 217
                 }
218 218
             }
@@ -223,12 +223,12 @@  discard block
 block discarded – undo
223 223
         $post_types = (array) $this->get('post_type');
224 224
         foreach ($post_types as $post_type) {
225 225
             // was a post name passed ?
226
-            if (isset($post_type_CPT_endpoints[ $post_type ])) {
226
+            if (isset($post_type_CPT_endpoints[$post_type])) {
227 227
                 // kk we know this is an espresso page, but is it a specific post ?
228
-                if (! $this->get('post_name')) {
228
+                if ( ! $this->get('post_name')) {
229 229
                     // there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
230
-                    $post_name = isset($post_type_CPT_endpoints[ $this->get('post_type') ])
231
-                        ? $post_type_CPT_endpoints[ $this->get('post_type') ]
230
+                    $post_name = isset($post_type_CPT_endpoints[$this->get('post_type')])
231
+                        ? $post_type_CPT_endpoints[$this->get('post_type')]
232 232
                         : '';
233 233
                     // if the post type matches on of our then set the endpoint
234 234
                     if ($post_name) {
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
      */
249 249
     public function set_notice($key, $value)
250 250
     {
251
-        $this->_notice[ $key ] = $value;
251
+        $this->_notice[$key] = $value;
252 252
     }
253 253
 
254 254
 
@@ -258,8 +258,8 @@  discard block
 block discarded – undo
258 258
      */
259 259
     public function get_notice($key)
260 260
     {
261
-        return isset($this->_notice[ $key ])
262
-            ? $this->_notice[ $key ]
261
+        return isset($this->_notice[$key])
262
+            ? $this->_notice[$key]
263 263
             : null;
264 264
     }
265 265
 
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +15 added lines, -13 removed lines patch added patch discarded remove patch
@@ -967,7 +967,7 @@  discard block
 block discarded – undo
967 967
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
968 968
      * foreign key to the WP_User table)
969 969
      *
970
-     * @return string|boolean string on success, boolean false when there is no
970
+     * @return string|false string on success, boolean false when there is no
971 971
      * foreign key to the WP_User table
972 972
      */
973 973
     public function wp_user_field_name()
@@ -1072,7 +1072,7 @@  discard block
 block discarded – undo
1072 1072
      *
1073 1073
      * @param array  $query_params      like EEM_Base::get_all's $query_params
1074 1074
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1075
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1075
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1076 1076
      *                                  fields on the model, and the models we joined to in the query. However, you can
1077 1077
      *                                  override this and set the select to "*", or a specific column name, like
1078 1078
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1486,7 +1486,7 @@  discard block
 block discarded – undo
1486 1486
      * @param string $field_name The name of the field the formats are being retrieved for.
1487 1487
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1488 1488
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1489
-     * @return array formats in an array with the date format first, and the time format last.
1489
+     * @return string[] formats in an array with the date format first, and the time format last.
1490 1490
      */
1491 1491
     public function get_formats_for($field_name, $pretty = false)
1492 1492
     {
@@ -1521,7 +1521,7 @@  discard block
 block discarded – undo
1521 1521
      *                                 be returned.
1522 1522
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1523 1523
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1524
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1524
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1525 1525
      *                                 exception is triggered.
1526 1526
      */
1527 1527
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1561,7 +1561,7 @@  discard block
 block discarded – undo
1561 1561
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1562 1562
      *                                format is
1563 1563
      *                                'U', this is ignored.
1564
-     * @return DateTime
1564
+     * @return string
1565 1565
      * @throws EE_Error
1566 1566
      */
1567 1567
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -2426,7 +2426,7 @@  discard block
 block discarded – undo
2426 2426
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2427 2427
      * EEM_Base::$_db_verification_level
2428 2428
      *
2429
-     * @param $wpdb_method
2429
+     * @param string $wpdb_method
2430 2430
      * @param $arguments_to_provide
2431 2431
      * @return string
2432 2432
      */
@@ -2550,6 +2550,7 @@  discard block
 block discarded – undo
2550 2550
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2551 2551
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2552 2552
      *                             because these will be inserted in any new rows created as well.
2553
+     * @param EE_Base_Class $id_or_obj
2553 2554
      */
2554 2555
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2555 2556
     {
@@ -2560,7 +2561,7 @@  discard block
 block discarded – undo
2560 2561
 
2561 2562
 
2562 2563
     /**
2563
-     * @param mixed           $id_or_obj
2564
+     * @param EE_Base_Class           $id_or_obj
2564 2565
      * @param string          $relationName
2565 2566
      * @param array           $where_query_params
2566 2567
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2601,7 +2602,7 @@  discard block
 block discarded – undo
2601 2602
      * However, if the model objects can't be deleted because of blocking related model objects, then
2602 2603
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2603 2604
      *
2604
-     * @param EE_Base_Class|int|string $id_or_obj
2605
+     * @param EE_Base_Class $id_or_obj
2605 2606
      * @param string                   $model_name
2606 2607
      * @param array                    $query_params
2607 2608
      * @return int how many deleted
@@ -2622,7 +2623,7 @@  discard block
 block discarded – undo
2622 2623
      * the model objects can't be hard deleted because of blocking related model objects,
2623 2624
      * just does a soft-delete on them instead.
2624 2625
      *
2625
-     * @param EE_Base_Class|int|string $id_or_obj
2626
+     * @param EE_Base_Class $id_or_obj
2626 2627
      * @param string                   $model_name
2627 2628
      * @param array                    $query_params
2628 2629
      * @return int how many deleted
@@ -2679,6 +2680,7 @@  discard block
 block discarded – undo
2679 2680
      * @param string $model_name   like 'Event', or 'Registration'
2680 2681
      * @param array  $query_params like EEM_Base::get_all's
2681 2682
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2683
+     * @param EE_Base_Class $id_or_obj
2682 2684
      * @return float
2683 2685
      * @throws EE_Error
2684 2686
      */
@@ -3639,7 +3641,7 @@  discard block
 block discarded – undo
3639 3641
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3640 3642
      * We should use default where conditions on related models when they requested to use default where conditions
3641 3643
      * on all models, or specifically just on other related models
3642
-     * @param      $default_where_conditions_value
3644
+     * @param      string $default_where_conditions_value
3643 3645
      * @param bool $for_this_model false means this is for OTHER related models
3644 3646
      * @return bool
3645 3647
      */
@@ -3677,7 +3679,7 @@  discard block
 block discarded – undo
3677 3679
      * where conditions.
3678 3680
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3679 3681
      * on this model or others
3680
-     * @param      $default_where_conditions_value
3682
+     * @param      string $default_where_conditions_value
3681 3683
      * @param bool $for_this_model false means this is for OTHER related models
3682 3684
      * @return bool
3683 3685
      */
@@ -4732,7 +4734,7 @@  discard block
 block discarded – undo
4732 4734
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4733 4735
      * Eg, on EE_Answer that would be ANS_ID field object
4734 4736
      *
4735
-     * @param $field_obj
4737
+     * @param EE_Model_Field_Base $field_obj
4736 4738
      * @return boolean
4737 4739
      */
4738 4740
     public function is_primary_key_field($field_obj)
@@ -5450,7 +5452,7 @@  discard block
 block discarded – undo
5450 5452
     /**
5451 5453
      * Read comments for assume_values_already_prepared_by_model_object()
5452 5454
      *
5453
-     * @return int
5455
+     * @return boolean
5454 5456
      */
5455 5457
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5456 5458
     {
Please login to merge, or discard this patch.
Indentation   +6342 added lines, -6342 removed lines patch added patch discarded remove patch
@@ -34,6348 +34,6348 @@
 block discarded – undo
34 34
 abstract class EEM_Base extends EE_Base implements ResettableInterface
35 35
 {
36 36
 
37
-    /**
38
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
-     * They almost always WILL NOT, but it's not necessarily a requirement.
41
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
-     *
43
-     * @var boolean
44
-     */
45
-    private $_values_already_prepared_by_model_object = 0;
46
-
47
-    /**
48
-     * when $_values_already_prepared_by_model_object equals this, we assume
49
-     * the data is just like form input that needs to have the model fields'
50
-     * prepare_for_set and prepare_for_use_in_db called on it
51
-     */
52
-    const not_prepared_by_model_object = 0;
53
-
54
-    /**
55
-     * when $_values_already_prepared_by_model_object equals this, we
56
-     * assume this value is coming from a model object and doesn't need to have
57
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
58
-     */
59
-    const prepared_by_model_object = 1;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the values are already to be used in the database (ie no processing is done
64
-     * on them by the model's fields)
65
-     */
66
-    const prepared_for_use_in_db = 2;
67
-
68
-
69
-    protected $singular_item = 'Item';
70
-
71
-    protected $plural_item   = 'Items';
72
-
73
-    /**
74
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
-     */
76
-    protected $_tables;
77
-
78
-    /**
79
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
-     *
83
-     * @var \EE_Model_Field_Base[][] $_fields
84
-     */
85
-    protected $_fields;
86
-
87
-    /**
88
-     * array of different kinds of relations
89
-     *
90
-     * @var \EE_Model_Relation_Base[] $_model_relations
91
-     */
92
-    protected $_model_relations;
93
-
94
-    /**
95
-     * @var \EE_Index[] $_indexes
96
-     */
97
-    protected $_indexes = array();
98
-
99
-    /**
100
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
101
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
-     * by setting the same columns as used in these queries in the query yourself.
103
-     *
104
-     * @var EE_Default_Where_Conditions
105
-     */
106
-    protected $_default_where_conditions_strategy;
107
-
108
-    /**
109
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
-     * This is particularly useful when you want something between 'none' and 'default'
111
-     *
112
-     * @var EE_Default_Where_Conditions
113
-     */
114
-    protected $_minimum_where_conditions_strategy;
115
-
116
-    /**
117
-     * String describing how to find the "owner" of this model's objects.
118
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
-     * But when there isn't, this indicates which related model, or transiently-related model,
120
-     * has the foreign key to the wp_users table.
121
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
-     * related to events, and events have a foreign key to wp_users.
123
-     * On EEM_Transaction, this would be 'Transaction.Event'
124
-     *
125
-     * @var string
126
-     */
127
-    protected $_model_chain_to_wp_user = '';
128
-
129
-    /**
130
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
-     * don't need it (particularly CPT models)
132
-     *
133
-     * @var bool
134
-     */
135
-    protected $_ignore_where_strategy = false;
136
-
137
-    /**
138
-     * String used in caps relating to this model. Eg, if the caps relating to this
139
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
-     *
141
-     * @var string. If null it hasn't been initialized yet. If false then we
142
-     * have indicated capabilities don't apply to this
143
-     */
144
-    protected $_caps_slug = null;
145
-
146
-    /**
147
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
-     * and next-level keys are capability names, and each's value is a
149
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
-     * they specify which context to use (ie, frontend, backend, edit or delete)
151
-     * and then each capability in the corresponding sub-array that they're missing
152
-     * adds the where conditions onto the query.
153
-     *
154
-     * @var array
155
-     */
156
-    protected $_cap_restrictions = array(
157
-        self::caps_read       => array(),
158
-        self::caps_read_admin => array(),
159
-        self::caps_edit       => array(),
160
-        self::caps_delete     => array(),
161
-    );
162
-
163
-    /**
164
-     * Array defining which cap restriction generators to use to create default
165
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
166
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
-     * automatically set this to false (not just null).
169
-     *
170
-     * @var EE_Restriction_Generator_Base[]
171
-     */
172
-    protected $_cap_restriction_generators = array();
173
-
174
-    /**
175
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
-     */
177
-    const caps_read       = 'read';
178
-
179
-    const caps_read_admin = 'read_admin';
180
-
181
-    const caps_edit       = 'edit';
182
-
183
-    const caps_delete     = 'delete';
184
-
185
-    /**
186
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
-     * maps to 'read' because when looking for relevant permissions we're going to use
189
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
190
-     *
191
-     * @var array
192
-     */
193
-    protected $_cap_contexts_to_cap_action_map = array(
194
-        self::caps_read       => 'read',
195
-        self::caps_read_admin => 'read',
196
-        self::caps_edit       => 'edit',
197
-        self::caps_delete     => 'delete',
198
-    );
199
-
200
-    /**
201
-     * Timezone
202
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
-     * EE_Datetime_Field data type will have access to it.
206
-     *
207
-     * @var string
208
-     */
209
-    protected $_timezone;
210
-
211
-
212
-    /**
213
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
-     * multisite.
215
-     *
216
-     * @var int
217
-     */
218
-    protected static $_model_query_blog_id;
219
-
220
-    /**
221
-     * A copy of _fields, except the array keys are the model names pointed to by
222
-     * the field
223
-     *
224
-     * @var EE_Model_Field_Base[]
225
-     */
226
-    private $_cache_foreign_key_to_fields = array();
227
-
228
-    /**
229
-     * Cached list of all the fields on the model, indexed by their name
230
-     *
231
-     * @var EE_Model_Field_Base[]
232
-     */
233
-    private $_cached_fields = null;
234
-
235
-    /**
236
-     * Cached list of all the fields on the model, except those that are
237
-     * marked as only pertinent to the database
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cached_fields_non_db_only = null;
242
-
243
-    /**
244
-     * A cached reference to the primary key for quick lookup
245
-     *
246
-     * @var EE_Model_Field_Base
247
-     */
248
-    private $_primary_key_field = null;
249
-
250
-    /**
251
-     * Flag indicating whether this model has a primary key or not
252
-     *
253
-     * @var boolean
254
-     */
255
-    protected $_has_primary_key_field = null;
256
-
257
-    /**
258
-     * Whether or not this model is based off a table in WP core only (CPTs should set
259
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
-     * This should be true for models that deal with data that should exist independent of EE.
261
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
263
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
265
-     * @var boolean
266
-     */
267
-    protected $_wp_core_model = false;
268
-
269
-    /**
270
-     *    List of valid operators that can be used for querying.
271
-     * The keys are all operators we'll accept, the values are the real SQL
272
-     * operators used
273
-     *
274
-     * @var array
275
-     */
276
-    protected $_valid_operators = array(
277
-        '='           => '=',
278
-        '<='          => '<=',
279
-        '<'           => '<',
280
-        '>='          => '>=',
281
-        '>'           => '>',
282
-        '!='          => '!=',
283
-        'LIKE'        => 'LIKE',
284
-        'like'        => 'LIKE',
285
-        'NOT_LIKE'    => 'NOT LIKE',
286
-        'not_like'    => 'NOT LIKE',
287
-        'NOT LIKE'    => 'NOT LIKE',
288
-        'not like'    => 'NOT LIKE',
289
-        'IN'          => 'IN',
290
-        'in'          => 'IN',
291
-        'NOT_IN'      => 'NOT IN',
292
-        'not_in'      => 'NOT IN',
293
-        'NOT IN'      => 'NOT IN',
294
-        'not in'      => 'NOT IN',
295
-        'between'     => 'BETWEEN',
296
-        'BETWEEN'     => 'BETWEEN',
297
-        'IS_NOT_NULL' => 'IS NOT NULL',
298
-        'is_not_null' => 'IS NOT NULL',
299
-        'IS NOT NULL' => 'IS NOT NULL',
300
-        'is not null' => 'IS NOT NULL',
301
-        'IS_NULL'     => 'IS NULL',
302
-        'is_null'     => 'IS NULL',
303
-        'IS NULL'     => 'IS NULL',
304
-        'is null'     => 'IS NULL',
305
-        'REGEXP'      => 'REGEXP',
306
-        'regexp'      => 'REGEXP',
307
-        'NOT_REGEXP'  => 'NOT REGEXP',
308
-        'not_regexp'  => 'NOT REGEXP',
309
-        'NOT REGEXP'  => 'NOT REGEXP',
310
-        'not regexp'  => 'NOT REGEXP',
311
-    );
312
-
313
-    /**
314
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
-     *
316
-     * @var array
317
-     */
318
-    protected $_in_style_operators = array('IN', 'NOT IN');
319
-
320
-    /**
321
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
-     * '12-31-2012'"
323
-     *
324
-     * @var array
325
-     */
326
-    protected $_between_style_operators = array('BETWEEN');
327
-
328
-    /**
329
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
-     * @var array
331
-     */
332
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
-    /**
334
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
-     * on a join table.
336
-     *
337
-     * @var array
338
-     */
339
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
-
341
-    /**
342
-     * Allowed values for $query_params['order'] for ordering in queries
343
-     *
344
-     * @var array
345
-     */
346
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
-
348
-    /**
349
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
351
-     *
352
-     * @var array
353
-     */
354
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
-
356
-    /**
357
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
359
-     *
360
-     * @var array
361
-     */
362
-    private $_allowed_query_params = array(
363
-        0,
364
-        'limit',
365
-        'order_by',
366
-        'group_by',
367
-        'having',
368
-        'force_join',
369
-        'order',
370
-        'on_join_limit',
371
-        'default_where_conditions',
372
-        'caps',
373
-        'extra_selects'
374
-    );
375
-
376
-    /**
377
-     * All the data types that can be used in $wpdb->prepare statements.
378
-     *
379
-     * @var array
380
-     */
381
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
-
383
-    /**
384
-     * @var EE_Registry $EE
385
-     */
386
-    protected $EE = null;
387
-
388
-
389
-    /**
390
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
-     *
392
-     * @var int
393
-     */
394
-    protected $_show_next_x_db_queries = 0;
395
-
396
-    /**
397
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
-     * WHERE, GROUP_BY, etc.
400
-     *
401
-     * @var CustomSelects
402
-     */
403
-    protected $_custom_selections = array();
404
-
405
-    /**
406
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
-     * caches every model object we've fetched from the DB on this request
408
-     *
409
-     * @var array
410
-     */
411
-    protected $_entity_map;
412
-
413
-    /**
414
-     * @var LoaderInterface $loader
415
-     */
416
-    private static $loader;
417
-
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error(
520
-                sprintf(
521
-                    __(
522
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
523
-                        'event_espresso'
524
-                    ),
525
-                    get_class($this)
526
-                )
527
-            );
528
-        }
529
-        /**
530
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
531
-         */
532
-        if (empty(EEM_Base::$_model_query_blog_id)) {
533
-            EEM_Base::set_model_query_blog_id();
534
-        }
535
-        /**
536
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
537
-         * just use EE_Register_Model_Extension
538
-         *
539
-         * @var EE_Table_Base[] $_tables
540
-         */
541
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
542
-        foreach ($this->_tables as $table_alias => $table_obj) {
543
-            /** @var $table_obj EE_Table_Base */
544
-            $table_obj->_construct_finalize_with_alias($table_alias);
545
-            if ($table_obj instanceof EE_Secondary_Table) {
546
-                /** @var $table_obj EE_Secondary_Table */
547
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
548
-            }
549
-        }
550
-        /**
551
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
552
-         * EE_Register_Model_Extension
553
-         *
554
-         * @param EE_Model_Field_Base[] $_fields
555
-         */
556
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
557
-        $this->_invalidate_field_caches();
558
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
559
-            if (! array_key_exists($table_alias, $this->_tables)) {
560
-                throw new EE_Error(sprintf(__(
561
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
562
-                    'event_espresso'
563
-                ), $table_alias, implode(",", $this->_fields)));
564
-            }
565
-            foreach ($fields_for_table as $field_name => $field_obj) {
566
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
-                // primary key field base has a slightly different _construct_finalize
568
-                /** @var $field_obj EE_Model_Field_Base */
569
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
-            }
571
-        }
572
-        // everything is related to Extra_Meta
573
-        if (get_class($this) !== 'EEM_Extra_Meta') {
574
-            // make extra meta related to everything, but don't block deleting things just
575
-            // because they have related extra meta info. For now just orphan those extra meta
576
-            // in the future we should automatically delete them
577
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        // and change logs
580
-        if (get_class($this) !== 'EEM_Change_Log') {
581
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
-        }
583
-        /**
584
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
-         * EE_Register_Model_Extension
586
-         *
587
-         * @param EE_Model_Relation_Base[] $_model_relations
588
-         */
589
-        $this->_model_relations = (array) apply_filters(
590
-            'FHEE__' . get_class($this) . '__construct__model_relations',
591
-            $this->_model_relations
592
-        );
593
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
594
-            /** @var $relation_obj EE_Model_Relation_Base */
595
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
596
-        }
597
-        foreach ($this->_indexes as $index_name => $index_obj) {
598
-            /** @var $index_obj EE_Index */
599
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
600
-        }
601
-        $this->set_timezone($timezone);
602
-        // finalize default where condition strategy, or set default
603
-        if (! $this->_default_where_conditions_strategy) {
604
-            // nothing was set during child constructor, so set default
605
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
606
-        }
607
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
608
-        if (! $this->_minimum_where_conditions_strategy) {
609
-            // nothing was set during child constructor, so set default
610
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
611
-        }
612
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
613
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
614
-        // to indicate to NOT set it, set it to the logical default
615
-        if ($this->_caps_slug === null) {
616
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
617
-        }
618
-        // initialize the standard cap restriction generators if none were specified by the child constructor
619
-        if ($this->_cap_restriction_generators !== false) {
620
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
621
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
622
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
623
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
624
-                        new EE_Restriction_Generator_Protected(),
625
-                        $cap_context,
626
-                        $this
627
-                    );
628
-                }
629
-            }
630
-        }
631
-        // if there are cap restriction generators, use them to make the default cap restrictions
632
-        if ($this->_cap_restriction_generators !== false) {
633
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
634
-                if (! $generator_object) {
635
-                    continue;
636
-                }
637
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
638
-                    throw new EE_Error(
639
-                        sprintf(
640
-                            __(
641
-                                'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
642
-                                'event_espresso'
643
-                            ),
644
-                            $context,
645
-                            $this->get_this_model_name()
646
-                        )
647
-                    );
648
-                }
649
-                $action = $this->cap_action_for_context($context);
650
-                if (! $generator_object->construction_finalized()) {
651
-                    $generator_object->_construct_finalize($this, $action);
652
-                }
653
-            }
654
-        }
655
-        do_action('AHEE__' . get_class($this) . '__construct__end');
656
-    }
657
-
658
-
659
-
660
-    /**
661
-     * Used to set the $_model_query_blog_id static property.
662
-     *
663
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
664
-     *                      value for get_current_blog_id() will be used.
665
-     */
666
-    public static function set_model_query_blog_id($blog_id = 0)
667
-    {
668
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
669
-    }
670
-
671
-
672
-
673
-    /**
674
-     * Returns whatever is set as the internal $model_query_blog_id.
675
-     *
676
-     * @return int
677
-     */
678
-    public static function get_model_query_blog_id()
679
-    {
680
-        return EEM_Base::$_model_query_blog_id;
681
-    }
682
-
683
-
684
-
685
-    /**
686
-     * This function is a singleton method used to instantiate the Espresso_model object
687
-     *
688
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
689
-     *                                (and any incoming timezone data that gets saved).
690
-     *                                Note this just sends the timezone info to the date time model field objects.
691
-     *                                Default is NULL
692
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
693
-     * @return static (as in the concrete child class)
694
-     * @throws EE_Error
695
-     * @throws InvalidArgumentException
696
-     * @throws InvalidDataTypeException
697
-     * @throws InvalidInterfaceException
698
-     */
699
-    public static function instance($timezone = null)
700
-    {
701
-        // check if instance of Espresso_model already exists
702
-        if (! static::$_instance instanceof static) {
703
-            // instantiate Espresso_model
704
-            static::$_instance = new static(
705
-                $timezone,
706
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
707
-            );
708
-        }
709
-        // we might have a timezone set, let set_timezone decide what to do with it
710
-        static::$_instance->set_timezone($timezone);
711
-        // Espresso_model object
712
-        return static::$_instance;
713
-    }
714
-
715
-
716
-
717
-    /**
718
-     * resets the model and returns it
719
-     *
720
-     * @param null | string $timezone
721
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
722
-     * all its properties reset; if it wasn't instantiated, returns null)
723
-     * @throws EE_Error
724
-     * @throws ReflectionException
725
-     * @throws InvalidArgumentException
726
-     * @throws InvalidDataTypeException
727
-     * @throws InvalidInterfaceException
728
-     */
729
-    public static function reset($timezone = null)
730
-    {
731
-        if (static::$_instance instanceof EEM_Base) {
732
-            // let's try to NOT swap out the current instance for a new one
733
-            // because if someone has a reference to it, we can't remove their reference
734
-            // so it's best to keep using the same reference, but change the original object
735
-            // reset all its properties to their original values as defined in the class
736
-            $r = new ReflectionClass(get_class(static::$_instance));
737
-            $static_properties = $r->getStaticProperties();
738
-            foreach ($r->getDefaultProperties() as $property => $value) {
739
-                // don't set instance to null like it was originally,
740
-                // but it's static anyways, and we're ignoring static properties (for now at least)
741
-                if (! isset($static_properties[ $property ])) {
742
-                    static::$_instance->{$property} = $value;
743
-                }
744
-            }
745
-            // and then directly call its constructor again, like we would if we were creating a new one
746
-            static::$_instance->__construct(
747
-                $timezone,
748
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
749
-            );
750
-            return self::instance();
751
-        }
752
-        return null;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * @return LoaderInterface
759
-     * @throws InvalidArgumentException
760
-     * @throws InvalidDataTypeException
761
-     * @throws InvalidInterfaceException
762
-     */
763
-    private static function getLoader()
764
-    {
765
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
766
-            EEM_Base::$loader = LoaderFactory::getLoader();
767
-        }
768
-        return EEM_Base::$loader;
769
-    }
770
-
771
-
772
-
773
-    /**
774
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
775
-     *
776
-     * @param  boolean $translated return localized strings or JUST the array.
777
-     * @return array
778
-     * @throws EE_Error
779
-     * @throws InvalidArgumentException
780
-     * @throws InvalidDataTypeException
781
-     * @throws InvalidInterfaceException
782
-     */
783
-    public function status_array($translated = false)
784
-    {
785
-        if (! array_key_exists('Status', $this->_model_relations)) {
786
-            return array();
787
-        }
788
-        $model_name = $this->get_this_model_name();
789
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
790
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
791
-        $status_array = array();
792
-        foreach ($stati as $status) {
793
-            $status_array[ $status->ID() ] = $status->get('STS_code');
794
-        }
795
-        return $translated
796
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
797
-            : $status_array;
798
-    }
799
-
800
-
801
-
802
-    /**
803
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
804
-     *
805
-     * @param array $query_params             {
806
-     * @var array $0 (where) array {
807
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
808
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
809
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
810
-     *                                        conditions based on related models (and even
811
-     *                                        models-related-to-related-models) prepend the model's name onto the field
812
-     *                                        name. Eg,
813
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
814
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
815
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
816
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
817
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
818
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
819
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
820
-     *                                        to Venues (even when each of those models actually consisted of two
821
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
822
-     *                                        just having
823
-     *                                        "Venue.VNU_ID", you could have
824
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
825
-     *                                        events are related to Registrations, which are related to Attendees). You
826
-     *                                        can take it even further with
827
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
828
-     *                                        (from the default of '='), change the value to an numerically-indexed
829
-     *                                        array, where the first item in the list is the operator. eg: array(
830
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
831
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
832
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
833
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
834
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
835
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
836
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
837
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
838
-     *                                        the value is a field, simply provide a third array item (true) to the
839
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
840
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
841
-     *                                        Note: you can also use related model field names like you would any other
842
-     *                                        field name. eg:
843
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
844
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
845
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
846
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
847
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
848
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
849
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
850
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
851
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
852
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
853
-     *                                        "stick" until you specify an AND. eg
854
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
855
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
856
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
857
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
858
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
859
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
860
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
861
-     *                                        too, eg:
862
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
863
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
864
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
865
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
866
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
867
-     *                                        the OFFSET, the 2nd is the LIMIT
868
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
869
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
870
-     *                                        following format array('on_join_limit'
871
-     *                                        => array( 'table_alias', array(1,2) ) ).
872
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
873
-     *                                        values are either 'ASC' or 'DESC'.
874
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
875
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
876
-     *                                        DESC..." respectively. Like the
877
-     *                                        'where' conditions, these fields can be on related models. Eg
878
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
879
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
880
-     *                                        Attendee, Price, Datetime, etc.)
881
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
882
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
883
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
884
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
885
-     *                                        order by the primary key. Eg,
886
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
887
-     *                                        //(will join with the Datetime model's table(s) and order by its field
888
-     *                                        DTT_EVT_start) or
889
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
890
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
891
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
892
-     *                                        'group_by'=>'VNU_ID', or
893
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
894
-     *                                        if no
895
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
896
-     *                                        model's primary key (or combined primary keys). This avoids some
897
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
898
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
899
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
900
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
901
-     *                                        results)
902
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
903
-     *                                        array where values are models to be joined in the query.Eg
904
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
905
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
906
-     *                                        probably only want to do this in hopes of increasing efficiency, as
907
-     *                                        related models which belongs to the current model
908
-     *                                        (ie, the current model has a foreign key to them, like how Registration
909
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
910
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
911
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
912
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
913
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
914
-     *                                        default where conditions set it to 'other_models_only'. If you only want
915
-     *                                        this model's default where conditions added to the query, use
916
-     *                                        'this_model_only'. If you want to use all default where conditions
917
-     *                                        (default), set to 'all'.
918
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
919
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
920
-     *                                        everything? Or should we only show the current user items they should be
921
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
922
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
923
-     *                                        }
924
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
925
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
926
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
927
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
928
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
929
-     *                                        array( array(
930
-     *                                        'OR'=>array(
931
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
932
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
933
-     *                                        )
934
-     *                                        ),
935
-     *                                        'limit'=>10,
936
-     *                                        'group_by'=>'TXN_ID'
937
-     *                                        ));
938
-     *                                        get all the answers to the question titled "shirt size" for event with id
939
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
940
-     *                                        'Question.QST_display_text'=>'shirt size',
941
-     *                                        'Registration.Event.EVT_ID'=>12
942
-     *                                        ),
943
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
944
-     *                                        ));
945
-     * @throws EE_Error
946
-     */
947
-    public function get_all($query_params = array())
948
-    {
949
-        if (isset($query_params['limit'])
950
-            && ! isset($query_params['group_by'])
951
-        ) {
952
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
953
-        }
954
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
955
-    }
956
-
957
-
958
-
959
-    /**
960
-     * Modifies the query parameters so we only get back model objects
961
-     * that "belong" to the current user
962
-     *
963
-     * @param array $query_params @see EEM_Base::get_all()
964
-     * @return array like EEM_Base::get_all
965
-     */
966
-    public function alter_query_params_to_only_include_mine($query_params = array())
967
-    {
968
-        $wp_user_field_name = $this->wp_user_field_name();
969
-        if ($wp_user_field_name) {
970
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
971
-        }
972
-        return $query_params;
973
-    }
974
-
975
-
976
-
977
-    /**
978
-     * Returns the name of the field's name that points to the WP_User table
979
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
980
-     * foreign key to the WP_User table)
981
-     *
982
-     * @return string|boolean string on success, boolean false when there is no
983
-     * foreign key to the WP_User table
984
-     */
985
-    public function wp_user_field_name()
986
-    {
987
-        try {
988
-            if (! empty($this->_model_chain_to_wp_user)) {
989
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
990
-                $last_model_name = end($models_to_follow_to_wp_users);
991
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
992
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
993
-            } else {
994
-                $model_with_fk_to_wp_users = $this;
995
-                $model_chain_to_wp_user = '';
996
-            }
997
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
998
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
999
-        } catch (EE_Error $e) {
1000
-            return false;
1001
-        }
1002
-    }
1003
-
1004
-
1005
-
1006
-    /**
1007
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
1008
-     * (or transiently-related model) has a foreign key to the wp_users table;
1009
-     * useful for finding if model objects of this type are 'owned' by the current user.
1010
-     * This is an empty string when the foreign key is on this model and when it isn't,
1011
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
1012
-     * (or transiently-related model)
1013
-     *
1014
-     * @return string
1015
-     */
1016
-    public function model_chain_to_wp_user()
1017
-    {
1018
-        return $this->_model_chain_to_wp_user;
1019
-    }
1020
-
1021
-
1022
-
1023
-    /**
1024
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1025
-     * like how registrations don't have a foreign key to wp_users, but the
1026
-     * events they are for are), or is unrelated to wp users.
1027
-     * generally available
1028
-     *
1029
-     * @return boolean
1030
-     */
1031
-    public function is_owned()
1032
-    {
1033
-        if ($this->model_chain_to_wp_user()) {
1034
-            return true;
1035
-        }
1036
-        try {
1037
-            $this->get_foreign_key_to('WP_User');
1038
-            return true;
1039
-        } catch (EE_Error $e) {
1040
-            return false;
1041
-        }
1042
-    }
1043
-
1044
-
1045
-    /**
1046
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1047
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1048
-     * the model)
1049
-     *
1050
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1051
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1052
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1053
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1054
-     *                                  override this and set the select to "*", or a specific column name, like
1055
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1056
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1057
-     *                                  the aliases used to refer to this selection, and values are to be
1058
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1059
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1060
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1061
-     * @throws EE_Error
1062
-     * @throws InvalidArgumentException
1063
-     */
1064
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1065
-    {
1066
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1067
-        ;
1068
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1069
-        $select_expressions = $columns_to_select === null
1070
-            ? $this->_construct_default_select_sql($model_query_info)
1071
-            : '';
1072
-        if ($this->_custom_selections instanceof CustomSelects) {
1073
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1074
-            $select_expressions .= $select_expressions
1075
-                ? ', ' . $custom_expressions
1076
-                : $custom_expressions;
1077
-        }
1078
-
1079
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1080
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1081
-    }
1082
-
1083
-
1084
-    /**
1085
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1086
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1087
-     * method of including extra select information.
1088
-     *
1089
-     * @param array             $query_params
1090
-     * @param null|array|string $columns_to_select
1091
-     * @return null|CustomSelects
1092
-     * @throws InvalidArgumentException
1093
-     */
1094
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1095
-    {
1096
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1097
-            return null;
1098
-        }
1099
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1100
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1101
-        return new CustomSelects($selects);
1102
-    }
1103
-
1104
-
1105
-
1106
-    /**
1107
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1108
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1109
-     * take care of joins, field preparation etc.
1110
-     *
1111
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1112
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1113
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1114
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1115
-     *                                  override this and set the select to "*", or a specific column name, like
1116
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1117
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1118
-     *                                  the aliases used to refer to this selection, and values are to be
1119
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1120
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1121
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1122
-     * @throws EE_Error
1123
-     */
1124
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1125
-    {
1126
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1127
-    }
1128
-
1129
-
1130
-
1131
-    /**
1132
-     * For creating a custom select statement
1133
-     *
1134
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1135
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1136
-     *                                 SQL, and 1=>is the datatype
1137
-     * @throws EE_Error
1138
-     * @return string
1139
-     */
1140
-    private function _construct_select_from_input($columns_to_select)
1141
-    {
1142
-        if (is_array($columns_to_select)) {
1143
-            $select_sql_array = array();
1144
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1145
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1146
-                    throw new EE_Error(
1147
-                        sprintf(
1148
-                            __(
1149
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1150
-                                'event_espresso'
1151
-                            ),
1152
-                            $selection_and_datatype,
1153
-                            $alias
1154
-                        )
1155
-                    );
1156
-                }
1157
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1158
-                    throw new EE_Error(
1159
-                        sprintf(
1160
-                            esc_html__(
1161
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1162
-                                'event_espresso'
1163
-                            ),
1164
-                            $selection_and_datatype[1],
1165
-                            $selection_and_datatype[0],
1166
-                            $alias,
1167
-                            implode(', ', $this->_valid_wpdb_data_types)
1168
-                        )
1169
-                    );
1170
-                }
1171
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1172
-            }
1173
-            $columns_to_select_string = implode(', ', $select_sql_array);
1174
-        } else {
1175
-            $columns_to_select_string = $columns_to_select;
1176
-        }
1177
-        return $columns_to_select_string;
1178
-    }
1179
-
1180
-
1181
-
1182
-    /**
1183
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1184
-     *
1185
-     * @return string
1186
-     * @throws EE_Error
1187
-     */
1188
-    public function primary_key_name()
1189
-    {
1190
-        return $this->get_primary_key_field()->get_name();
1191
-    }
1192
-
1193
-
1194
-
1195
-    /**
1196
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1197
-     * If there is no primary key on this model, $id is treated as primary key string
1198
-     *
1199
-     * @param mixed $id int or string, depending on the type of the model's primary key
1200
-     * @return EE_Base_Class
1201
-     */
1202
-    public function get_one_by_ID($id)
1203
-    {
1204
-        if ($this->get_from_entity_map($id)) {
1205
-            return $this->get_from_entity_map($id);
1206
-        }
1207
-        return $this->get_one(
1208
-            $this->alter_query_params_to_restrict_by_ID(
1209
-                $id,
1210
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1211
-            )
1212
-        );
1213
-    }
1214
-
1215
-
1216
-
1217
-    /**
1218
-     * Alters query parameters to only get items with this ID are returned.
1219
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1220
-     * or could just be a simple primary key ID
1221
-     *
1222
-     * @param int   $id
1223
-     * @param array $query_params
1224
-     * @return array of normal query params, @see EEM_Base::get_all
1225
-     * @throws EE_Error
1226
-     */
1227
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1228
-    {
1229
-        if (! isset($query_params[0])) {
1230
-            $query_params[0] = array();
1231
-        }
1232
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1233
-        if ($conditions_from_id === null) {
1234
-            $query_params[0][ $this->primary_key_name() ] = $id;
1235
-        } else {
1236
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1237
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1238
-        }
1239
-        return $query_params;
1240
-    }
1241
-
1242
-
1243
-
1244
-    /**
1245
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1246
-     * array. If no item is found, null is returned.
1247
-     *
1248
-     * @param array $query_params like EEM_Base's $query_params variable.
1249
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1250
-     * @throws EE_Error
1251
-     */
1252
-    public function get_one($query_params = array())
1253
-    {
1254
-        if (! is_array($query_params)) {
1255
-            EE_Error::doing_it_wrong(
1256
-                'EEM_Base::get_one',
1257
-                sprintf(
1258
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1259
-                    gettype($query_params)
1260
-                ),
1261
-                '4.6.0'
1262
-            );
1263
-            $query_params = array();
1264
-        }
1265
-        $query_params['limit'] = 1;
1266
-        $items = $this->get_all($query_params);
1267
-        if (empty($items)) {
1268
-            return null;
1269
-        }
1270
-        return array_shift($items);
1271
-    }
1272
-
1273
-
1274
-
1275
-    /**
1276
-     * Returns the next x number of items in sequence from the given value as
1277
-     * found in the database matching the given query conditions.
1278
-     *
1279
-     * @param mixed $current_field_value    Value used for the reference point.
1280
-     * @param null  $field_to_order_by      What field is used for the
1281
-     *                                      reference point.
1282
-     * @param int   $limit                  How many to return.
1283
-     * @param array $query_params           Extra conditions on the query.
1284
-     * @param null  $columns_to_select      If left null, then an array of
1285
-     *                                      EE_Base_Class objects is returned,
1286
-     *                                      otherwise you can indicate just the
1287
-     *                                      columns you want returned.
1288
-     * @return EE_Base_Class[]|array
1289
-     * @throws EE_Error
1290
-     */
1291
-    public function next_x(
1292
-        $current_field_value,
1293
-        $field_to_order_by = null,
1294
-        $limit = 1,
1295
-        $query_params = array(),
1296
-        $columns_to_select = null
1297
-    ) {
1298
-        return $this->_get_consecutive(
1299
-            $current_field_value,
1300
-            '>',
1301
-            $field_to_order_by,
1302
-            $limit,
1303
-            $query_params,
1304
-            $columns_to_select
1305
-        );
1306
-    }
1307
-
1308
-
1309
-
1310
-    /**
1311
-     * Returns the previous x number of items in sequence from the given value
1312
-     * as found in the database matching the given query conditions.
1313
-     *
1314
-     * @param mixed $current_field_value    Value used for the reference point.
1315
-     * @param null  $field_to_order_by      What field is used for the
1316
-     *                                      reference point.
1317
-     * @param int   $limit                  How many to return.
1318
-     * @param array $query_params           Extra conditions on the query.
1319
-     * @param null  $columns_to_select      If left null, then an array of
1320
-     *                                      EE_Base_Class objects is returned,
1321
-     *                                      otherwise you can indicate just the
1322
-     *                                      columns you want returned.
1323
-     * @return EE_Base_Class[]|array
1324
-     * @throws EE_Error
1325
-     */
1326
-    public function previous_x(
1327
-        $current_field_value,
1328
-        $field_to_order_by = null,
1329
-        $limit = 1,
1330
-        $query_params = array(),
1331
-        $columns_to_select = null
1332
-    ) {
1333
-        return $this->_get_consecutive(
1334
-            $current_field_value,
1335
-            '<',
1336
-            $field_to_order_by,
1337
-            $limit,
1338
-            $query_params,
1339
-            $columns_to_select
1340
-        );
1341
-    }
1342
-
1343
-
1344
-
1345
-    /**
1346
-     * Returns the next item in sequence from the given value as found in the
1347
-     * database matching the given query conditions.
1348
-     *
1349
-     * @param mixed $current_field_value    Value used for the reference point.
1350
-     * @param null  $field_to_order_by      What field is used for the
1351
-     *                                      reference point.
1352
-     * @param array $query_params           Extra conditions on the query.
1353
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1354
-     *                                      object is returned, otherwise you
1355
-     *                                      can indicate just the columns you
1356
-     *                                      want and a single array indexed by
1357
-     *                                      the columns will be returned.
1358
-     * @return EE_Base_Class|null|array()
1359
-     * @throws EE_Error
1360
-     */
1361
-    public function next(
1362
-        $current_field_value,
1363
-        $field_to_order_by = null,
1364
-        $query_params = array(),
1365
-        $columns_to_select = null
1366
-    ) {
1367
-        $results = $this->_get_consecutive(
1368
-            $current_field_value,
1369
-            '>',
1370
-            $field_to_order_by,
1371
-            1,
1372
-            $query_params,
1373
-            $columns_to_select
1374
-        );
1375
-        return empty($results) ? null : reset($results);
1376
-    }
1377
-
1378
-
1379
-
1380
-    /**
1381
-     * Returns the previous item in sequence from the given value as found in
1382
-     * the database matching the given query conditions.
1383
-     *
1384
-     * @param mixed $current_field_value    Value used for the reference point.
1385
-     * @param null  $field_to_order_by      What field is used for the
1386
-     *                                      reference point.
1387
-     * @param array $query_params           Extra conditions on the query.
1388
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1389
-     *                                      object is returned, otherwise you
1390
-     *                                      can indicate just the columns you
1391
-     *                                      want and a single array indexed by
1392
-     *                                      the columns will be returned.
1393
-     * @return EE_Base_Class|null|array()
1394
-     * @throws EE_Error
1395
-     */
1396
-    public function previous(
1397
-        $current_field_value,
1398
-        $field_to_order_by = null,
1399
-        $query_params = array(),
1400
-        $columns_to_select = null
1401
-    ) {
1402
-        $results = $this->_get_consecutive(
1403
-            $current_field_value,
1404
-            '<',
1405
-            $field_to_order_by,
1406
-            1,
1407
-            $query_params,
1408
-            $columns_to_select
1409
-        );
1410
-        return empty($results) ? null : reset($results);
1411
-    }
1412
-
1413
-
1414
-
1415
-    /**
1416
-     * Returns the a consecutive number of items in sequence from the given
1417
-     * value as found in the database matching the given query conditions.
1418
-     *
1419
-     * @param mixed  $current_field_value   Value used for the reference point.
1420
-     * @param string $operand               What operand is used for the sequence.
1421
-     * @param string $field_to_order_by     What field is used for the reference point.
1422
-     * @param int    $limit                 How many to return.
1423
-     * @param array  $query_params          Extra conditions on the query.
1424
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1425
-     *                                      otherwise you can indicate just the columns you want returned.
1426
-     * @return EE_Base_Class[]|array
1427
-     * @throws EE_Error
1428
-     */
1429
-    protected function _get_consecutive(
1430
-        $current_field_value,
1431
-        $operand = '>',
1432
-        $field_to_order_by = null,
1433
-        $limit = 1,
1434
-        $query_params = array(),
1435
-        $columns_to_select = null
1436
-    ) {
1437
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1438
-        if (empty($field_to_order_by)) {
1439
-            if ($this->has_primary_key_field()) {
1440
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1441
-            } else {
1442
-                if (WP_DEBUG) {
1443
-                    throw new EE_Error(__(
1444
-                        'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1445
-                        'event_espresso'
1446
-                    ));
1447
-                }
1448
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1449
-                return array();
1450
-            }
1451
-        }
1452
-        if (! is_array($query_params)) {
1453
-            EE_Error::doing_it_wrong(
1454
-                'EEM_Base::_get_consecutive',
1455
-                sprintf(
1456
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1457
-                    gettype($query_params)
1458
-                ),
1459
-                '4.6.0'
1460
-            );
1461
-            $query_params = array();
1462
-        }
1463
-        // let's add the where query param for consecutive look up.
1464
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1465
-        $query_params['limit'] = $limit;
1466
-        // set direction
1467
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1468
-        $query_params['order_by'] = $operand === '>'
1469
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1470
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1471
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1472
-        if (empty($columns_to_select)) {
1473
-            return $this->get_all($query_params);
1474
-        }
1475
-        // getting just the fields
1476
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1477
-    }
1478
-
1479
-
1480
-
1481
-    /**
1482
-     * This sets the _timezone property after model object has been instantiated.
1483
-     *
1484
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1485
-     */
1486
-    public function set_timezone($timezone)
1487
-    {
1488
-        if ($timezone !== null) {
1489
-            $this->_timezone = $timezone;
1490
-        }
1491
-        // note we need to loop through relations and set the timezone on those objects as well.
1492
-        foreach ($this->_model_relations as $relation) {
1493
-            $relation->set_timezone($timezone);
1494
-        }
1495
-        // and finally we do the same for any datetime fields
1496
-        foreach ($this->_fields as $field) {
1497
-            if ($field instanceof EE_Datetime_Field) {
1498
-                $field->set_timezone($timezone);
1499
-            }
1500
-        }
1501
-    }
1502
-
1503
-
1504
-
1505
-    /**
1506
-     * This just returns whatever is set for the current timezone.
1507
-     *
1508
-     * @access public
1509
-     * @return string
1510
-     */
1511
-    public function get_timezone()
1512
-    {
1513
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1514
-        if (empty($this->_timezone)) {
1515
-            foreach ($this->_fields as $field) {
1516
-                if ($field instanceof EE_Datetime_Field) {
1517
-                    $this->set_timezone($field->get_timezone());
1518
-                    break;
1519
-                }
1520
-            }
1521
-        }
1522
-        // if timezone STILL empty then return the default timezone for the site.
1523
-        if (empty($this->_timezone)) {
1524
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1525
-        }
1526
-        return $this->_timezone;
1527
-    }
1528
-
1529
-
1530
-
1531
-    /**
1532
-     * This returns the date formats set for the given field name and also ensures that
1533
-     * $this->_timezone property is set correctly.
1534
-     *
1535
-     * @since 4.6.x
1536
-     * @param string $field_name The name of the field the formats are being retrieved for.
1537
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1538
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1539
-     * @return array formats in an array with the date format first, and the time format last.
1540
-     */
1541
-    public function get_formats_for($field_name, $pretty = false)
1542
-    {
1543
-        $field_settings = $this->field_settings_for($field_name);
1544
-        // if not a valid EE_Datetime_Field then throw error
1545
-        if (! $field_settings instanceof EE_Datetime_Field) {
1546
-            throw new EE_Error(sprintf(__(
1547
-                'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1548
-                'event_espresso'
1549
-            ), $field_name));
1550
-        }
1551
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1552
-        // the field.
1553
-        $this->_timezone = $field_settings->get_timezone();
1554
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1555
-    }
1556
-
1557
-
1558
-
1559
-    /**
1560
-     * This returns the current time in a format setup for a query on this model.
1561
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1562
-     * it will return:
1563
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1564
-     *  NOW
1565
-     *  - or a unix timestamp (equivalent to time())
1566
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1567
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1568
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1569
-     * @since 4.6.x
1570
-     * @param string $field_name       The field the current time is needed for.
1571
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1572
-     *                                 formatted string matching the set format for the field in the set timezone will
1573
-     *                                 be returned.
1574
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1575
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1576
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1577
-     *                                 exception is triggered.
1578
-     */
1579
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1580
-    {
1581
-        $formats = $this->get_formats_for($field_name);
1582
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1583
-        if ($timestamp) {
1584
-            return $DateTime->format('U');
1585
-        }
1586
-        // not returning timestamp, so return formatted string in timezone.
1587
-        switch ($what) {
1588
-            case 'time':
1589
-                return $DateTime->format($formats[1]);
1590
-                break;
1591
-            case 'date':
1592
-                return $DateTime->format($formats[0]);
1593
-                break;
1594
-            default:
1595
-                return $DateTime->format(implode(' ', $formats));
1596
-                break;
1597
-        }
1598
-    }
1599
-
1600
-
1601
-
1602
-    /**
1603
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1604
-     * for the model are.  Returns a DateTime object.
1605
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1606
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1607
-     * ignored.
1608
-     *
1609
-     * @param string $field_name      The field being setup.
1610
-     * @param string $timestring      The date time string being used.
1611
-     * @param string $incoming_format The format for the time string.
1612
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1613
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1614
-     *                                format is
1615
-     *                                'U', this is ignored.
1616
-     * @return DateTime
1617
-     * @throws EE_Error
1618
-     */
1619
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1620
-    {
1621
-        // just using this to ensure the timezone is set correctly internally
1622
-        $this->get_formats_for($field_name);
1623
-        // load EEH_DTT_Helper
1624
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1625
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1626
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1627
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1628
-    }
1629
-
1630
-
1631
-
1632
-    /**
1633
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1634
-     *
1635
-     * @return EE_Table_Base[]
1636
-     */
1637
-    public function get_tables()
1638
-    {
1639
-        return $this->_tables;
1640
-    }
1641
-
1642
-
1643
-
1644
-    /**
1645
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1646
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1647
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1648
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1649
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1650
-     * model object with EVT_ID = 1
1651
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1652
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1653
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1654
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1655
-     * are not specified)
1656
-     *
1657
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1658
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1659
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1660
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1661
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1662
-     *                                         ID=34, we'd use this method as follows:
1663
-     *                                         EEM_Transaction::instance()->update(
1664
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1665
-     *                                         array(array('TXN_ID'=>34)));
1666
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1667
-     *                                         in client code into what's expected to be stored on each field. Eg,
1668
-     *                                         consider updating Question's QST_admin_label field is of type
1669
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1670
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1671
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1672
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1673
-     *                                         TRUE, it is assumed that you've already called
1674
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1675
-     *                                         malicious javascript. However, if
1676
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1677
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1678
-     *                                         and every other field, before insertion. We provide this parameter
1679
-     *                                         because model objects perform their prepare_for_set function on all
1680
-     *                                         their values, and so don't need to be called again (and in many cases,
1681
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1682
-     *                                         prepare_for_set method...)
1683
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1684
-     *                                         in this model's entity map according to $fields_n_values that match
1685
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1686
-     *                                         by setting this to FALSE, but be aware that model objects being used
1687
-     *                                         could get out-of-sync with the database
1688
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1689
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1690
-     *                                         bad)
1691
-     * @throws EE_Error
1692
-     */
1693
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1694
-    {
1695
-        if (! is_array($query_params)) {
1696
-            EE_Error::doing_it_wrong(
1697
-                'EEM_Base::update',
1698
-                sprintf(
1699
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1700
-                    gettype($query_params)
1701
-                ),
1702
-                '4.6.0'
1703
-            );
1704
-            $query_params = array();
1705
-        }
1706
-        /**
1707
-         * Action called before a model update call has been made.
1708
-         *
1709
-         * @param EEM_Base $model
1710
-         * @param array    $fields_n_values the updated fields and their new values
1711
-         * @param array    $query_params    @see EEM_Base::get_all()
1712
-         */
1713
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1714
-        /**
1715
-         * Filters the fields about to be updated given the query parameters. You can provide the
1716
-         * $query_params to $this->get_all() to find exactly which records will be updated
1717
-         *
1718
-         * @param array    $fields_n_values fields and their new values
1719
-         * @param EEM_Base $model           the model being queried
1720
-         * @param array    $query_params    see EEM_Base::get_all()
1721
-         */
1722
-        $fields_n_values = (array) apply_filters(
1723
-            'FHEE__EEM_Base__update__fields_n_values',
1724
-            $fields_n_values,
1725
-            $this,
1726
-            $query_params
1727
-        );
1728
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1729
-        // to do that, for each table, verify that it's PK isn't null.
1730
-        $tables = $this->get_tables();
1731
-        // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1732
-        // NOTE: we should make this code more efficient by NOT querying twice
1733
-        // before the real update, but that needs to first go through ALPHA testing
1734
-        // as it's dangerous. says Mike August 8 2014
1735
-        // we want to make sure the default_where strategy is ignored
1736
-        $this->_ignore_where_strategy = true;
1737
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1738
-        foreach ($wpdb_select_results as $wpdb_result) {
1739
-            // type cast stdClass as array
1740
-            $wpdb_result = (array) $wpdb_result;
1741
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1742
-            if ($this->has_primary_key_field()) {
1743
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1744
-            } else {
1745
-                // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1746
-                $main_table_pk_value = null;
1747
-            }
1748
-            // if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1749
-            // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1750
-            if (count($tables) > 1) {
1751
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1752
-                // in that table, and so we'll want to insert one
1753
-                foreach ($tables as $table_obj) {
1754
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1755
-                    // if there is no private key for this table on the results, it means there's no entry
1756
-                    // in this table, right? so insert a row in the current table, using any fields available
1757
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1758
-                           && $wpdb_result[ $this_table_pk_column ])
1759
-                    ) {
1760
-                        $success = $this->_insert_into_specific_table(
1761
-                            $table_obj,
1762
-                            $fields_n_values,
1763
-                            $main_table_pk_value
1764
-                        );
1765
-                        // if we died here, report the error
1766
-                        if (! $success) {
1767
-                            return false;
1768
-                        }
1769
-                    }
1770
-                }
1771
-            }
1772
-            //              //and now check that if we have cached any models by that ID on the model, that
1773
-            //              //they also get updated properly
1774
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1775
-            //              if( $model_object ){
1776
-            //                  foreach( $fields_n_values as $field => $value ){
1777
-            //                      $model_object->set($field, $value);
1778
-            // let's make sure default_where strategy is followed now
1779
-            $this->_ignore_where_strategy = false;
1780
-        }
1781
-        // if we want to keep model objects in sync, AND
1782
-        // if this wasn't called from a model object (to update itself)
1783
-        // then we want to make sure we keep all the existing
1784
-        // model objects in sync with the db
1785
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1786
-            if ($this->has_primary_key_field()) {
1787
-                $model_objs_affected_ids = $this->get_col($query_params);
1788
-            } else {
1789
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1790
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1791
-                $model_objs_affected_ids = array();
1792
-                foreach ($models_affected_key_columns as $row) {
1793
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1794
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1795
-                }
1796
-            }
1797
-            if (! $model_objs_affected_ids) {
1798
-                // wait wait wait- if nothing was affected let's stop here
1799
-                return 0;
1800
-            }
1801
-            foreach ($model_objs_affected_ids as $id) {
1802
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1803
-                if ($model_obj_in_entity_map) {
1804
-                    foreach ($fields_n_values as $field => $new_value) {
1805
-                        $model_obj_in_entity_map->set($field, $new_value);
1806
-                    }
1807
-                }
1808
-            }
1809
-            // if there is a primary key on this model, we can now do a slight optimization
1810
-            if ($this->has_primary_key_field()) {
1811
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1812
-                $query_params = array(
1813
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1814
-                    'limit'                    => count($model_objs_affected_ids),
1815
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1816
-                );
1817
-            }
1818
-        }
1819
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1820
-        $SQL = "UPDATE "
1821
-               . $model_query_info->get_full_join_sql()
1822
-               . " SET "
1823
-               . $this->_construct_update_sql($fields_n_values)
1824
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1825
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1826
-        /**
1827
-         * Action called after a model update call has been made.
1828
-         *
1829
-         * @param EEM_Base $model
1830
-         * @param array    $fields_n_values the updated fields and their new values
1831
-         * @param array    $query_params    @see EEM_Base::get_all()
1832
-         * @param int      $rows_affected
1833
-         */
1834
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1835
-        return $rows_affected;// how many supposedly got updated
1836
-    }
1837
-
1838
-
1839
-
1840
-    /**
1841
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1842
-     * are teh values of the field specified (or by default the primary key field)
1843
-     * that matched the query params. Note that you should pass the name of the
1844
-     * model FIELD, not the database table's column name.
1845
-     *
1846
-     * @param array  $query_params @see EEM_Base::get_all()
1847
-     * @param string $field_to_select
1848
-     * @return array just like $wpdb->get_col()
1849
-     * @throws EE_Error
1850
-     */
1851
-    public function get_col($query_params = array(), $field_to_select = null)
1852
-    {
1853
-        if ($field_to_select) {
1854
-            $field = $this->field_settings_for($field_to_select);
1855
-        } elseif ($this->has_primary_key_field()) {
1856
-            $field = $this->get_primary_key_field();
1857
-        } else {
1858
-            // no primary key, just grab the first column
1859
-            $field = reset($this->field_settings());
1860
-        }
1861
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1862
-        $select_expressions = $field->get_qualified_column();
1863
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1864
-        return $this->_do_wpdb_query('get_col', array($SQL));
1865
-    }
1866
-
1867
-
1868
-
1869
-    /**
1870
-     * Returns a single column value for a single row from the database
1871
-     *
1872
-     * @param array  $query_params    @see EEM_Base::get_all()
1873
-     * @param string $field_to_select @see EEM_Base::get_col()
1874
-     * @return string
1875
-     * @throws EE_Error
1876
-     */
1877
-    public function get_var($query_params = array(), $field_to_select = null)
1878
-    {
1879
-        $query_params['limit'] = 1;
1880
-        $col = $this->get_col($query_params, $field_to_select);
1881
-        if (! empty($col)) {
1882
-            return reset($col);
1883
-        }
1884
-        return null;
1885
-    }
1886
-
1887
-
1888
-
1889
-    /**
1890
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1891
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1892
-     * injection, but currently no further filtering is done
1893
-     *
1894
-     * @global      $wpdb
1895
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1896
-     *                               be updated to in the DB
1897
-     * @return string of SQL
1898
-     * @throws EE_Error
1899
-     */
1900
-    public function _construct_update_sql($fields_n_values)
1901
-    {
1902
-        /** @type WPDB $wpdb */
1903
-        global $wpdb;
1904
-        $cols_n_values = array();
1905
-        foreach ($fields_n_values as $field_name => $value) {
1906
-            $field_obj = $this->field_settings_for($field_name);
1907
-            // if the value is NULL, we want to assign the value to that.
1908
-            // wpdb->prepare doesn't really handle that properly
1909
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1910
-            $value_sql = $prepared_value === null ? 'NULL'
1911
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1912
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1913
-        }
1914
-        return implode(",", $cols_n_values);
1915
-    }
1916
-
1917
-
1918
-
1919
-    /**
1920
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1921
-     * Performs a HARD delete, meaning the database row should always be removed,
1922
-     * not just have a flag field on it switched
1923
-     * Wrapper for EEM_Base::delete_permanently()
1924
-     *
1925
-     * @param mixed $id
1926
-     * @param boolean $allow_blocking
1927
-     * @return int the number of rows deleted
1928
-     * @throws EE_Error
1929
-     */
1930
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1931
-    {
1932
-        return $this->delete_permanently(
1933
-            array(
1934
-                array($this->get_primary_key_field()->get_name() => $id),
1935
-                'limit' => 1,
1936
-            ),
1937
-            $allow_blocking
1938
-        );
1939
-    }
1940
-
1941
-
1942
-
1943
-    /**
1944
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1945
-     * Wrapper for EEM_Base::delete()
1946
-     *
1947
-     * @param mixed $id
1948
-     * @param boolean $allow_blocking
1949
-     * @return int the number of rows deleted
1950
-     * @throws EE_Error
1951
-     */
1952
-    public function delete_by_ID($id, $allow_blocking = true)
1953
-    {
1954
-        return $this->delete(
1955
-            array(
1956
-                array($this->get_primary_key_field()->get_name() => $id),
1957
-                'limit' => 1,
1958
-            ),
1959
-            $allow_blocking
1960
-        );
1961
-    }
1962
-
1963
-
1964
-
1965
-    /**
1966
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1967
-     * meaning if the model has a field that indicates its been "trashed" or
1968
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1969
-     *
1970
-     * @see EEM_Base::delete_permanently
1971
-     * @param array   $query_params
1972
-     * @param boolean $allow_blocking
1973
-     * @return int how many rows got deleted
1974
-     * @throws EE_Error
1975
-     */
1976
-    public function delete($query_params, $allow_blocking = true)
1977
-    {
1978
-        return $this->delete_permanently($query_params, $allow_blocking);
1979
-    }
1980
-
1981
-
1982
-
1983
-    /**
1984
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1985
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1986
-     * as archived, not actually deleted
1987
-     *
1988
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1989
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1990
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1991
-     *                                deletes regardless of other objects which may depend on it. Its generally
1992
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1993
-     *                                DB
1994
-     * @return int how many rows got deleted
1995
-     * @throws EE_Error
1996
-     */
1997
-    public function delete_permanently($query_params, $allow_blocking = true)
1998
-    {
1999
-        /**
2000
-         * Action called just before performing a real deletion query. You can use the
2001
-         * model and its $query_params to find exactly which items will be deleted
2002
-         *
2003
-         * @param EEM_Base $model
2004
-         * @param array    $query_params   @see EEM_Base::get_all()
2005
-         * @param boolean  $allow_blocking whether or not to allow related model objects
2006
-         *                                 to block (prevent) this deletion
2007
-         */
2008
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
2009
-        // some MySQL databases may be running safe mode, which may restrict
2010
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
2011
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
2012
-        // to delete them
2013
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
2014
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2015
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
2016
-            $columns_and_ids_for_deleting
2017
-        );
2018
-        /**
2019
-         * Allows client code to act on the items being deleted before the query is actually executed.
2020
-         *
2021
-         * @param EEM_Base $this  The model instance being acted on.
2022
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2023
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
2024
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
2025
-         *                                                  derived from the incoming query parameters.
2026
-         *                                                  @see details on the structure of this array in the phpdocs
2027
-         *                                                  for the `_get_ids_for_delete_method`
2028
-         *
2029
-         */
2030
-        do_action(
2031
-            'AHEE__EEM_Base__delete__before_query',
2032
-            $this,
2033
-            $query_params,
2034
-            $allow_blocking,
2035
-            $columns_and_ids_for_deleting
2036
-        );
2037
-        if ($deletion_where_query_part) {
2038
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2039
-            $table_aliases = array_keys($this->_tables);
2040
-            $SQL = "DELETE "
2041
-                   . implode(", ", $table_aliases)
2042
-                   . " FROM "
2043
-                   . $model_query_info->get_full_join_sql()
2044
-                   . " WHERE "
2045
-                   . $deletion_where_query_part;
2046
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2047
-        } else {
2048
-            $rows_deleted = 0;
2049
-        }
2050
-
2051
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2052
-        // there was no error with the delete query.
2053
-        if ($this->has_primary_key_field()
2054
-            && $rows_deleted !== false
2055
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2056
-        ) {
2057
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2058
-            foreach ($ids_for_removal as $id) {
2059
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2060
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2061
-                }
2062
-            }
2063
-
2064
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2065
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2066
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2067
-            // (although it is possible).
2068
-            // Note this can be skipped by using the provided filter and returning false.
2069
-            if (apply_filters(
2070
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2071
-                ! $this instanceof EEM_Extra_Meta,
2072
-                $this
2073
-            )) {
2074
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2075
-                    0 => array(
2076
-                        'EXM_type' => $this->get_this_model_name(),
2077
-                        'OBJ_ID'   => array(
2078
-                            'IN',
2079
-                            $ids_for_removal
2080
-                        )
2081
-                    )
2082
-                ));
2083
-            }
2084
-        }
2085
-
2086
-        /**
2087
-         * Action called just after performing a real deletion query. Although at this point the
2088
-         * items should have been deleted
2089
-         *
2090
-         * @param EEM_Base $model
2091
-         * @param array    $query_params @see EEM_Base::get_all()
2092
-         * @param int      $rows_deleted
2093
-         */
2094
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2095
-        return $rows_deleted;// how many supposedly got deleted
2096
-    }
2097
-
2098
-
2099
-
2100
-    /**
2101
-     * Checks all the relations that throw error messages when there are blocking related objects
2102
-     * for related model objects. If there are any related model objects on those relations,
2103
-     * adds an EE_Error, and return true
2104
-     *
2105
-     * @param EE_Base_Class|int $this_model_obj_or_id
2106
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2107
-     *                                                 should be ignored when determining whether there are related
2108
-     *                                                 model objects which block this model object's deletion. Useful
2109
-     *                                                 if you know A is related to B and are considering deleting A,
2110
-     *                                                 but want to see if A has any other objects blocking its deletion
2111
-     *                                                 before removing the relation between A and B
2112
-     * @return boolean
2113
-     * @throws EE_Error
2114
-     */
2115
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2116
-    {
2117
-        // first, if $ignore_this_model_obj was supplied, get its model
2118
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2119
-            $ignored_model = $ignore_this_model_obj->get_model();
2120
-        } else {
2121
-            $ignored_model = null;
2122
-        }
2123
-        // now check all the relations of $this_model_obj_or_id and see if there
2124
-        // are any related model objects blocking it?
2125
-        $is_blocked = false;
2126
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2127
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2128
-                // if $ignore_this_model_obj was supplied, then for the query
2129
-                // on that model needs to be told to ignore $ignore_this_model_obj
2130
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2131
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2132
-                        array(
2133
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2134
-                                '!=',
2135
-                                $ignore_this_model_obj->ID(),
2136
-                            ),
2137
-                        ),
2138
-                    ));
2139
-                } else {
2140
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2141
-                }
2142
-                if ($related_model_objects) {
2143
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2144
-                    $is_blocked = true;
2145
-                }
2146
-            }
2147
-        }
2148
-        return $is_blocked;
2149
-    }
2150
-
2151
-
2152
-    /**
2153
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2154
-     * @param array $row_results_for_deleting
2155
-     * @param bool  $allow_blocking
2156
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2157
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2158
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2159
-     *                 deleted. Example:
2160
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2161
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2162
-     *                 where each element is a group of columns and values that get deleted. Example:
2163
-     *                      array(
2164
-     *                          0 => array(
2165
-     *                              'Term_Relationship.object_id' => 1
2166
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2167
-     *                          ),
2168
-     *                          1 => array(
2169
-     *                              'Term_Relationship.object_id' => 1
2170
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2171
-     *                          )
2172
-     *                      )
2173
-     * @throws EE_Error
2174
-     */
2175
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2176
-    {
2177
-        $ids_to_delete_indexed_by_column = array();
2178
-        if ($this->has_primary_key_field()) {
2179
-            $primary_table = $this->_get_main_table();
2180
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2181
-            $other_tables = $this->_get_other_tables();
2182
-            $ids_to_delete_indexed_by_column = $query = array();
2183
-            foreach ($row_results_for_deleting as $item_to_delete) {
2184
-                // before we mark this item for deletion,
2185
-                // make sure there's no related entities blocking its deletion (if we're checking)
2186
-                if ($allow_blocking
2187
-                    && $this->delete_is_blocked_by_related_models(
2188
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2189
-                    )
2190
-                ) {
2191
-                    continue;
2192
-                }
2193
-                // primary table deletes
2194
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2195
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2196
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2197
-                }
2198
-            }
2199
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2200
-            $fields = $this->get_combined_primary_key_fields();
2201
-            foreach ($row_results_for_deleting as $item_to_delete) {
2202
-                $ids_to_delete_indexed_by_column_for_row = array();
2203
-                foreach ($fields as $cpk_field) {
2204
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2205
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2206
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2207
-                    }
2208
-                }
2209
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2210
-            }
2211
-        } else {
2212
-            // so there's no primary key and no combined key...
2213
-            // sorry, can't help you
2214
-            throw new EE_Error(
2215
-                sprintf(
2216
-                    __(
2217
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2218
-                        "event_espresso"
2219
-                    ),
2220
-                    get_class($this)
2221
-                )
2222
-            );
2223
-        }
2224
-        return $ids_to_delete_indexed_by_column;
2225
-    }
2226
-
2227
-
2228
-    /**
2229
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2230
-     * the corresponding query_part for the query performing the delete.
2231
-     *
2232
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2233
-     * @return string
2234
-     * @throws EE_Error
2235
-     */
2236
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2237
-    {
2238
-        $query_part = '';
2239
-        if (empty($ids_to_delete_indexed_by_column)) {
2240
-            return $query_part;
2241
-        } elseif ($this->has_primary_key_field()) {
2242
-            $query = array();
2243
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2244
-                // make sure we have unique $ids
2245
-                $ids = array_unique($ids);
2246
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2247
-            }
2248
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2249
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2250
-            $ways_to_identify_a_row = array();
2251
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2252
-                $values_for_each_combined_primary_key_for_a_row = array();
2253
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2254
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2255
-                }
2256
-                $ways_to_identify_a_row[] = '('
2257
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2258
-                                            . ')';
2259
-            }
2260
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2261
-        }
2262
-        return $query_part;
2263
-    }
2264
-
2265
-
2266
-
2267
-    /**
2268
-     * Gets the model field by the fully qualified name
2269
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2270
-     * @return EE_Model_Field_Base
2271
-     */
2272
-    public function get_field_by_column($qualified_column_name)
2273
-    {
2274
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2275
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2276
-                return $field_obj;
2277
-            }
2278
-        }
2279
-        throw new EE_Error(
2280
-            sprintf(
2281
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2282
-                $this->get_this_model_name(),
2283
-                $qualified_column_name
2284
-            )
2285
-        );
2286
-    }
2287
-
2288
-
2289
-
2290
-    /**
2291
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2292
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2293
-     * column
2294
-     *
2295
-     * @param array  $query_params   like EEM_Base::get_all's
2296
-     * @param string $field_to_count field on model to count by (not column name)
2297
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2298
-     *                               that by the setting $distinct to TRUE;
2299
-     * @return int
2300
-     * @throws EE_Error
2301
-     */
2302
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2303
-    {
2304
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2305
-        if ($field_to_count) {
2306
-            $field_obj = $this->field_settings_for($field_to_count);
2307
-            $column_to_count = $field_obj->get_qualified_column();
2308
-        } elseif ($this->has_primary_key_field()) {
2309
-            $pk_field_obj = $this->get_primary_key_field();
2310
-            $column_to_count = $pk_field_obj->get_qualified_column();
2311
-        } else {
2312
-            // there's no primary key
2313
-            // if we're counting distinct items, and there's no primary key,
2314
-            // we need to list out the columns for distinction;
2315
-            // otherwise we can just use star
2316
-            if ($distinct) {
2317
-                $columns_to_use = array();
2318
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2319
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2320
-                }
2321
-                $column_to_count = implode(',', $columns_to_use);
2322
-            } else {
2323
-                $column_to_count = '*';
2324
-            }
2325
-        }
2326
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2327
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2328
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2329
-    }
2330
-
2331
-
2332
-
2333
-    /**
2334
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2335
-     *
2336
-     * @param array  $query_params like EEM_Base::get_all
2337
-     * @param string $field_to_sum name of field (array key in $_fields array)
2338
-     * @return float
2339
-     * @throws EE_Error
2340
-     */
2341
-    public function sum($query_params, $field_to_sum = null)
2342
-    {
2343
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2344
-        if ($field_to_sum) {
2345
-            $field_obj = $this->field_settings_for($field_to_sum);
2346
-        } else {
2347
-            $field_obj = $this->get_primary_key_field();
2348
-        }
2349
-        $column_to_count = $field_obj->get_qualified_column();
2350
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2351
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2352
-        $data_type = $field_obj->get_wpdb_data_type();
2353
-        if ($data_type === '%d' || $data_type === '%s') {
2354
-            return (float) $return_value;
2355
-        }
2356
-        // must be %f
2357
-        return (float) $return_value;
2358
-    }
2359
-
2360
-
2361
-
2362
-    /**
2363
-     * Just calls the specified method on $wpdb with the given arguments
2364
-     * Consolidates a little extra error handling code
2365
-     *
2366
-     * @param string $wpdb_method
2367
-     * @param array  $arguments_to_provide
2368
-     * @throws EE_Error
2369
-     * @global wpdb  $wpdb
2370
-     * @return mixed
2371
-     */
2372
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2373
-    {
2374
-        // if we're in maintenance mode level 2, DON'T run any queries
2375
-        // because level 2 indicates the database needs updating and
2376
-        // is probably out of sync with the code
2377
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2378
-            throw new EE_Error(sprintf(__(
2379
-                "Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2380
-                "event_espresso"
2381
-            )));
2382
-        }
2383
-        /** @type WPDB $wpdb */
2384
-        global $wpdb;
2385
-        if (! method_exists($wpdb, $wpdb_method)) {
2386
-            throw new EE_Error(sprintf(__(
2387
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2388
-                'event_espresso'
2389
-            ), $wpdb_method));
2390
-        }
2391
-        if (WP_DEBUG) {
2392
-            $old_show_errors_value = $wpdb->show_errors;
2393
-            $wpdb->show_errors(false);
2394
-        }
2395
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2396
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2397
-        if (WP_DEBUG) {
2398
-            $wpdb->show_errors($old_show_errors_value);
2399
-            if (! empty($wpdb->last_error)) {
2400
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2401
-            }
2402
-            if ($result === false) {
2403
-                throw new EE_Error(sprintf(__(
2404
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2405
-                    'event_espresso'
2406
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2407
-            }
2408
-        } elseif ($result === false) {
2409
-            EE_Error::add_error(
2410
-                sprintf(
2411
-                    __(
2412
-                        'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2413
-                        'event_espresso'
2414
-                    ),
2415
-                    $wpdb_method,
2416
-                    var_export($arguments_to_provide, true),
2417
-                    $wpdb->last_error
2418
-                ),
2419
-                __FILE__,
2420
-                __FUNCTION__,
2421
-                __LINE__
2422
-            );
2423
-        }
2424
-        return $result;
2425
-    }
2426
-
2427
-
2428
-
2429
-    /**
2430
-     * Attempts to run the indicated WPDB method with the provided arguments,
2431
-     * and if there's an error tries to verify the DB is correct. Uses
2432
-     * the static property EEM_Base::$_db_verification_level to determine whether
2433
-     * we should try to fix the EE core db, the addons, or just give up
2434
-     *
2435
-     * @param string $wpdb_method
2436
-     * @param array  $arguments_to_provide
2437
-     * @return mixed
2438
-     */
2439
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2440
-    {
2441
-        /** @type WPDB $wpdb */
2442
-        global $wpdb;
2443
-        $wpdb->last_error = null;
2444
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2445
-        // was there an error running the query? but we don't care on new activations
2446
-        // (we're going to setup the DB anyway on new activations)
2447
-        if (($result === false || ! empty($wpdb->last_error))
2448
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2449
-        ) {
2450
-            switch (EEM_Base::$_db_verification_level) {
2451
-                case EEM_Base::db_verified_none:
2452
-                    // let's double-check core's DB
2453
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2454
-                    break;
2455
-                case EEM_Base::db_verified_core:
2456
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2457
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2458
-                    break;
2459
-                case EEM_Base::db_verified_addons:
2460
-                    // ummmm... you in trouble
2461
-                    return $result;
2462
-                    break;
2463
-            }
2464
-            if (! empty($error_message)) {
2465
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2466
-                trigger_error($error_message);
2467
-            }
2468
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2469
-        }
2470
-        return $result;
2471
-    }
2472
-
2473
-
2474
-
2475
-    /**
2476
-     * Verifies the EE core database is up-to-date and records that we've done it on
2477
-     * EEM_Base::$_db_verification_level
2478
-     *
2479
-     * @param string $wpdb_method
2480
-     * @param array  $arguments_to_provide
2481
-     * @return string
2482
-     */
2483
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2484
-    {
2485
-        /** @type WPDB $wpdb */
2486
-        global $wpdb;
2487
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2488
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2489
-        $error_message = sprintf(
2490
-            __(
2491
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2492
-                'event_espresso'
2493
-            ),
2494
-            $wpdb->last_error,
2495
-            $wpdb_method,
2496
-            wp_json_encode($arguments_to_provide)
2497
-        );
2498
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2499
-        return $error_message;
2500
-    }
2501
-
2502
-
2503
-
2504
-    /**
2505
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2506
-     * EEM_Base::$_db_verification_level
2507
-     *
2508
-     * @param $wpdb_method
2509
-     * @param $arguments_to_provide
2510
-     * @return string
2511
-     */
2512
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2513
-    {
2514
-        /** @type WPDB $wpdb */
2515
-        global $wpdb;
2516
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2517
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2518
-        $error_message = sprintf(
2519
-            __(
2520
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2521
-                'event_espresso'
2522
-            ),
2523
-            $wpdb->last_error,
2524
-            $wpdb_method,
2525
-            wp_json_encode($arguments_to_provide)
2526
-        );
2527
-        EE_System::instance()->initialize_addons();
2528
-        return $error_message;
2529
-    }
2530
-
2531
-
2532
-
2533
-    /**
2534
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2535
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2536
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2537
-     * ..."
2538
-     *
2539
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2540
-     * @return string
2541
-     */
2542
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2543
-    {
2544
-        return " FROM " . $model_query_info->get_full_join_sql() .
2545
-               $model_query_info->get_where_sql() .
2546
-               $model_query_info->get_group_by_sql() .
2547
-               $model_query_info->get_having_sql() .
2548
-               $model_query_info->get_order_by_sql() .
2549
-               $model_query_info->get_limit_sql();
2550
-    }
2551
-
2552
-
2553
-
2554
-    /**
2555
-     * Set to easily debug the next X queries ran from this model.
2556
-     *
2557
-     * @param int $count
2558
-     */
2559
-    public function show_next_x_db_queries($count = 1)
2560
-    {
2561
-        $this->_show_next_x_db_queries = $count;
2562
-    }
2563
-
2564
-
2565
-
2566
-    /**
2567
-     * @param $sql_query
2568
-     */
2569
-    public function show_db_query_if_previously_requested($sql_query)
2570
-    {
2571
-        if ($this->_show_next_x_db_queries > 0) {
2572
-            echo $sql_query;
2573
-            $this->_show_next_x_db_queries--;
2574
-        }
2575
-    }
2576
-
2577
-
2578
-
2579
-    /**
2580
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2581
-     * There are the 3 cases:
2582
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2583
-     * $otherModelObject has no ID, it is first saved.
2584
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2585
-     * has no ID, it is first saved.
2586
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2587
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2588
-     * join table
2589
-     *
2590
-     * @param        EE_Base_Class                     /int $thisModelObject
2591
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2592
-     * @param string $relationName                     , key in EEM_Base::_relations
2593
-     *                                                 an attendee to a group, you also want to specify which role they
2594
-     *                                                 will have in that group. So you would use this parameter to
2595
-     *                                                 specify array('role-column-name'=>'role-id')
2596
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2597
-     *                                                 to for relation to methods that allow you to further specify
2598
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2599
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2600
-     *                                                 because these will be inserted in any new rows created as well.
2601
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2602
-     * @throws EE_Error
2603
-     */
2604
-    public function add_relationship_to(
2605
-        $id_or_obj,
2606
-        $other_model_id_or_obj,
2607
-        $relationName,
2608
-        $extra_join_model_fields_n_values = array()
2609
-    ) {
2610
-        $relation_obj = $this->related_settings_for($relationName);
2611
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2612
-    }
2613
-
2614
-
2615
-
2616
-    /**
2617
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2618
-     * There are the 3 cases:
2619
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2620
-     * error
2621
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2622
-     * an error
2623
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2624
-     *
2625
-     * @param        EE_Base_Class /int $id_or_obj
2626
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2627
-     * @param string $relationName key in EEM_Base::_relations
2628
-     * @return boolean of success
2629
-     * @throws EE_Error
2630
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2631
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2632
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2633
-     *                             because these will be inserted in any new rows created as well.
2634
-     */
2635
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2636
-    {
2637
-        $relation_obj = $this->related_settings_for($relationName);
2638
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2639
-    }
2640
-
2641
-
2642
-
2643
-    /**
2644
-     * @param mixed           $id_or_obj
2645
-     * @param string          $relationName
2646
-     * @param array           $where_query_params
2647
-     * @param EE_Base_Class[] objects to which relations were removed
2648
-     * @return \EE_Base_Class[]
2649
-     * @throws EE_Error
2650
-     */
2651
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2652
-    {
2653
-        $relation_obj = $this->related_settings_for($relationName);
2654
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2655
-    }
2656
-
2657
-
2658
-
2659
-    /**
2660
-     * Gets all the related items of the specified $model_name, using $query_params.
2661
-     * Note: by default, we remove the "default query params"
2662
-     * because we want to get even deleted items etc.
2663
-     *
2664
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2665
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2666
-     * @param array  $query_params like EEM_Base::get_all
2667
-     * @return EE_Base_Class[]
2668
-     * @throws EE_Error
2669
-     */
2670
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2671
-    {
2672
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2673
-        $relation_settings = $this->related_settings_for($model_name);
2674
-        return $relation_settings->get_all_related($model_obj, $query_params);
2675
-    }
2676
-
2677
-
2678
-
2679
-    /**
2680
-     * Deletes all the model objects across the relation indicated by $model_name
2681
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2682
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2683
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2684
-     *
2685
-     * @param EE_Base_Class|int|string $id_or_obj
2686
-     * @param string                   $model_name
2687
-     * @param array                    $query_params
2688
-     * @return int how many deleted
2689
-     * @throws EE_Error
2690
-     */
2691
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2692
-    {
2693
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2694
-        $relation_settings = $this->related_settings_for($model_name);
2695
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2696
-    }
2697
-
2698
-
2699
-
2700
-    /**
2701
-     * Hard deletes all the model objects across the relation indicated by $model_name
2702
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2703
-     * the model objects can't be hard deleted because of blocking related model objects,
2704
-     * just does a soft-delete on them instead.
2705
-     *
2706
-     * @param EE_Base_Class|int|string $id_or_obj
2707
-     * @param string                   $model_name
2708
-     * @param array                    $query_params
2709
-     * @return int how many deleted
2710
-     * @throws EE_Error
2711
-     */
2712
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2713
-    {
2714
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2715
-        $relation_settings = $this->related_settings_for($model_name);
2716
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2717
-    }
2718
-
2719
-
2720
-
2721
-    /**
2722
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2723
-     * unless otherwise specified in the $query_params
2724
-     *
2725
-     * @param        int             /EE_Base_Class $id_or_obj
2726
-     * @param string $model_name     like 'Event', or 'Registration'
2727
-     * @param array  $query_params   like EEM_Base::get_all's
2728
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2729
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2730
-     *                               that by the setting $distinct to TRUE;
2731
-     * @return int
2732
-     * @throws EE_Error
2733
-     */
2734
-    public function count_related(
2735
-        $id_or_obj,
2736
-        $model_name,
2737
-        $query_params = array(),
2738
-        $field_to_count = null,
2739
-        $distinct = false
2740
-    ) {
2741
-        $related_model = $this->get_related_model_obj($model_name);
2742
-        // we're just going to use the query params on the related model's normal get_all query,
2743
-        // except add a condition to say to match the current mod
2744
-        if (! isset($query_params['default_where_conditions'])) {
2745
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2746
-        }
2747
-        $this_model_name = $this->get_this_model_name();
2748
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2749
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2750
-        return $related_model->count($query_params, $field_to_count, $distinct);
2751
-    }
2752
-
2753
-
2754
-
2755
-    /**
2756
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2757
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2758
-     *
2759
-     * @param        int           /EE_Base_Class $id_or_obj
2760
-     * @param string $model_name   like 'Event', or 'Registration'
2761
-     * @param array  $query_params like EEM_Base::get_all's
2762
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2763
-     * @return float
2764
-     * @throws EE_Error
2765
-     */
2766
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2767
-    {
2768
-        $related_model = $this->get_related_model_obj($model_name);
2769
-        if (! is_array($query_params)) {
2770
-            EE_Error::doing_it_wrong(
2771
-                'EEM_Base::sum_related',
2772
-                sprintf(
2773
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2774
-                    gettype($query_params)
2775
-                ),
2776
-                '4.6.0'
2777
-            );
2778
-            $query_params = array();
2779
-        }
2780
-        // we're just going to use the query params on the related model's normal get_all query,
2781
-        // except add a condition to say to match the current mod
2782
-        if (! isset($query_params['default_where_conditions'])) {
2783
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2784
-        }
2785
-        $this_model_name = $this->get_this_model_name();
2786
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2787
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2788
-        return $related_model->sum($query_params, $field_to_sum);
2789
-    }
2790
-
2791
-
2792
-
2793
-    /**
2794
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2795
-     * $modelObject
2796
-     *
2797
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2798
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2799
-     * @param array               $query_params     like EEM_Base::get_all's
2800
-     * @return EE_Base_Class
2801
-     * @throws EE_Error
2802
-     */
2803
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2804
-    {
2805
-        $query_params['limit'] = 1;
2806
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2807
-        if ($results) {
2808
-            return array_shift($results);
2809
-        }
2810
-        return null;
2811
-    }
2812
-
2813
-
2814
-
2815
-    /**
2816
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2817
-     *
2818
-     * @return string
2819
-     */
2820
-    public function get_this_model_name()
2821
-    {
2822
-        return str_replace("EEM_", "", get_class($this));
2823
-    }
2824
-
2825
-
2826
-
2827
-    /**
2828
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2829
-     *
2830
-     * @return EE_Any_Foreign_Model_Name_Field
2831
-     * @throws EE_Error
2832
-     */
2833
-    public function get_field_containing_related_model_name()
2834
-    {
2835
-        foreach ($this->field_settings(true) as $field) {
2836
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2837
-                $field_with_model_name = $field;
2838
-            }
2839
-        }
2840
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2841
-            throw new EE_Error(sprintf(
2842
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2843
-                $this->get_this_model_name()
2844
-            ));
2845
-        }
2846
-        return $field_with_model_name;
2847
-    }
2848
-
2849
-
2850
-
2851
-    /**
2852
-     * Inserts a new entry into the database, for each table.
2853
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2854
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2855
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2856
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2857
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2858
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2859
-     *
2860
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2861
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2862
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2863
-     *                              of EEM_Base)
2864
-     * @return int new primary key on main table that got inserted
2865
-     * @throws EE_Error
2866
-     */
2867
-    public function insert($field_n_values)
2868
-    {
2869
-        /**
2870
-         * Filters the fields and their values before inserting an item using the models
2871
-         *
2872
-         * @param array    $fields_n_values keys are the fields and values are their new values
2873
-         * @param EEM_Base $model           the model used
2874
-         */
2875
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2876
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2877
-            $main_table = $this->_get_main_table();
2878
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2879
-            if ($new_id !== false) {
2880
-                foreach ($this->_get_other_tables() as $other_table) {
2881
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2882
-                }
2883
-            }
2884
-            /**
2885
-             * Done just after attempting to insert a new model object
2886
-             *
2887
-             * @param EEM_Base   $model           used
2888
-             * @param array      $fields_n_values fields and their values
2889
-             * @param int|string the              ID of the newly-inserted model object
2890
-             */
2891
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2892
-            return $new_id;
2893
-        }
2894
-        return false;
2895
-    }
2896
-
2897
-
2898
-
2899
-    /**
2900
-     * Checks that the result would satisfy the unique indexes on this model
2901
-     *
2902
-     * @param array  $field_n_values
2903
-     * @param string $action
2904
-     * @return boolean
2905
-     * @throws EE_Error
2906
-     */
2907
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2908
-    {
2909
-        foreach ($this->unique_indexes() as $index_name => $index) {
2910
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2911
-            if ($this->exists(array($uniqueness_where_params))) {
2912
-                EE_Error::add_error(
2913
-                    sprintf(
2914
-                        __(
2915
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2916
-                            "event_espresso"
2917
-                        ),
2918
-                        $action,
2919
-                        $this->_get_class_name(),
2920
-                        $index_name,
2921
-                        implode(",", $index->field_names()),
2922
-                        http_build_query($uniqueness_where_params)
2923
-                    ),
2924
-                    __FILE__,
2925
-                    __FUNCTION__,
2926
-                    __LINE__
2927
-                );
2928
-                return false;
2929
-            }
2930
-        }
2931
-        return true;
2932
-    }
2933
-
2934
-
2935
-
2936
-    /**
2937
-     * Checks the database for an item that conflicts (ie, if this item were
2938
-     * saved to the DB would break some uniqueness requirement, like a primary key
2939
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2940
-     * can be either an EE_Base_Class or an array of fields n values
2941
-     *
2942
-     * @param EE_Base_Class|array $obj_or_fields_array
2943
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2944
-     *                                                 when looking for conflicts
2945
-     *                                                 (ie, if false, we ignore the model object's primary key
2946
-     *                                                 when finding "conflicts". If true, it's also considered).
2947
-     *                                                 Only works for INT primary key,
2948
-     *                                                 STRING primary keys cannot be ignored
2949
-     * @throws EE_Error
2950
-     * @return EE_Base_Class|array
2951
-     */
2952
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2953
-    {
2954
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2955
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2956
-        } elseif (is_array($obj_or_fields_array)) {
2957
-            $fields_n_values = $obj_or_fields_array;
2958
-        } else {
2959
-            throw new EE_Error(
2960
-                sprintf(
2961
-                    __(
2962
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2963
-                        "event_espresso"
2964
-                    ),
2965
-                    get_class($this),
2966
-                    $obj_or_fields_array
2967
-                )
2968
-            );
2969
-        }
2970
-        $query_params = array();
2971
-        if ($this->has_primary_key_field()
2972
-            && ($include_primary_key
2973
-                || $this->get_primary_key_field()
2974
-                   instanceof
2975
-                   EE_Primary_Key_String_Field)
2976
-            && isset($fields_n_values[ $this->primary_key_name() ])
2977
-        ) {
2978
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2979
-        }
2980
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2981
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2982
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2983
-        }
2984
-        // if there is nothing to base this search on, then we shouldn't find anything
2985
-        if (empty($query_params)) {
2986
-            return array();
2987
-        }
2988
-        return $this->get_one($query_params);
2989
-    }
2990
-
2991
-
2992
-
2993
-    /**
2994
-     * Like count, but is optimized and returns a boolean instead of an int
2995
-     *
2996
-     * @param array $query_params
2997
-     * @return boolean
2998
-     * @throws EE_Error
2999
-     */
3000
-    public function exists($query_params)
3001
-    {
3002
-        $query_params['limit'] = 1;
3003
-        return $this->count($query_params) > 0;
3004
-    }
3005
-
3006
-
3007
-
3008
-    /**
3009
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
3010
-     *
3011
-     * @param int|string $id
3012
-     * @return boolean
3013
-     * @throws EE_Error
3014
-     */
3015
-    public function exists_by_ID($id)
3016
-    {
3017
-        return $this->exists(
3018
-            array(
3019
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3020
-                array(
3021
-                    $this->primary_key_name() => $id,
3022
-                ),
3023
-            )
3024
-        );
3025
-    }
3026
-
3027
-
3028
-
3029
-    /**
3030
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3031
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3032
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3033
-     * on the main table)
3034
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3035
-     * cases where we want to call it directly rather than via insert().
3036
-     *
3037
-     * @access   protected
3038
-     * @param EE_Table_Base $table
3039
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3040
-     *                                       float
3041
-     * @param int           $new_id          for now we assume only int keys
3042
-     * @throws EE_Error
3043
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3044
-     * @return int ID of new row inserted, or FALSE on failure
3045
-     */
3046
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3047
-    {
3048
-        global $wpdb;
3049
-        $insertion_col_n_values = array();
3050
-        $format_for_insertion = array();
3051
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
3052
-        foreach ($fields_on_table as $field_name => $field_obj) {
3053
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3054
-            if ($field_obj->is_auto_increment()) {
3055
-                continue;
3056
-            }
3057
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3058
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3059
-            if ($prepared_value !== null) {
3060
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3061
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3062
-            }
3063
-        }
3064
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3065
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3066
-            // so add the fk to the main table as a column
3067
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3068
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3069
-        }
3070
-        // insert the new entry
3071
-        $result = $this->_do_wpdb_query(
3072
-            'insert',
3073
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3074
-        );
3075
-        if ($result === false) {
3076
-            return false;
3077
-        }
3078
-        // ok, now what do we return for the ID of the newly-inserted thing?
3079
-        if ($this->has_primary_key_field()) {
3080
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3081
-                return $wpdb->insert_id;
3082
-            }
3083
-            // it's not an auto-increment primary key, so
3084
-            // it must have been supplied
3085
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3086
-        }
3087
-        // we can't return a  primary key because there is none. instead return
3088
-        // a unique string indicating this model
3089
-        return $this->get_index_primary_key_string($fields_n_values);
3090
-    }
3091
-
3092
-
3093
-
3094
-    /**
3095
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3096
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3097
-     * and there is no default, we pass it along. WPDB will take care of it)
3098
-     *
3099
-     * @param EE_Model_Field_Base $field_obj
3100
-     * @param array               $fields_n_values
3101
-     * @return mixed string|int|float depending on what the table column will be expecting
3102
-     * @throws EE_Error
3103
-     */
3104
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3105
-    {
3106
-        // if this field doesn't allow nullable, don't allow it
3107
-        if (! $field_obj->is_nullable()
3108
-            && (
3109
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3110
-                || $fields_n_values[ $field_obj->get_name() ] === null
3111
-            )
3112
-        ) {
3113
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3114
-        }
3115
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3116
-            ? $fields_n_values[ $field_obj->get_name() ]
3117
-            : null;
3118
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3119
-    }
3120
-
3121
-
3122
-
3123
-    /**
3124
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3125
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3126
-     * the field's prepare_for_set() method.
3127
-     *
3128
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3129
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3130
-     *                                   top of file)
3131
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3132
-     *                                   $value is a custom selection
3133
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3134
-     */
3135
-    private function _prepare_value_for_use_in_db($value, $field)
3136
-    {
3137
-        if ($field && $field instanceof EE_Model_Field_Base) {
3138
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3139
-            switch ($this->_values_already_prepared_by_model_object) {
3140
-                /** @noinspection PhpMissingBreakStatementInspection */
3141
-                case self::not_prepared_by_model_object:
3142
-                    $value = $field->prepare_for_set($value);
3143
-                // purposefully left out "return"
3144
-                case self::prepared_by_model_object:
3145
-                    /** @noinspection SuspiciousAssignmentsInspection */
3146
-                    $value = $field->prepare_for_use_in_db($value);
3147
-                case self::prepared_for_use_in_db:
3148
-                    // leave the value alone
3149
-            }
3150
-            return $value;
3151
-            // phpcs:enable
3152
-        }
3153
-        return $value;
3154
-    }
3155
-
3156
-
3157
-
3158
-    /**
3159
-     * Returns the main table on this model
3160
-     *
3161
-     * @return EE_Primary_Table
3162
-     * @throws EE_Error
3163
-     */
3164
-    protected function _get_main_table()
3165
-    {
3166
-        foreach ($this->_tables as $table) {
3167
-            if ($table instanceof EE_Primary_Table) {
3168
-                return $table;
3169
-            }
3170
-        }
3171
-        throw new EE_Error(sprintf(__(
3172
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3173
-            'event_espresso'
3174
-        ), get_class($this)));
3175
-    }
3176
-
3177
-
3178
-
3179
-    /**
3180
-     * table
3181
-     * returns EE_Primary_Table table name
3182
-     *
3183
-     * @return string
3184
-     * @throws EE_Error
3185
-     */
3186
-    public function table()
3187
-    {
3188
-        return $this->_get_main_table()->get_table_name();
3189
-    }
3190
-
3191
-
3192
-
3193
-    /**
3194
-     * table
3195
-     * returns first EE_Secondary_Table table name
3196
-     *
3197
-     * @return string
3198
-     */
3199
-    public function second_table()
3200
-    {
3201
-        // grab second table from tables array
3202
-        $second_table = end($this->_tables);
3203
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3204
-    }
3205
-
3206
-
3207
-
3208
-    /**
3209
-     * get_table_obj_by_alias
3210
-     * returns table name given it's alias
3211
-     *
3212
-     * @param string $table_alias
3213
-     * @return EE_Primary_Table | EE_Secondary_Table
3214
-     */
3215
-    public function get_table_obj_by_alias($table_alias = '')
3216
-    {
3217
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3218
-    }
3219
-
3220
-
3221
-
3222
-    /**
3223
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3224
-     *
3225
-     * @return EE_Secondary_Table[]
3226
-     */
3227
-    protected function _get_other_tables()
3228
-    {
3229
-        $other_tables = array();
3230
-        foreach ($this->_tables as $table_alias => $table) {
3231
-            if ($table instanceof EE_Secondary_Table) {
3232
-                $other_tables[ $table_alias ] = $table;
3233
-            }
3234
-        }
3235
-        return $other_tables;
3236
-    }
3237
-
3238
-
3239
-
3240
-    /**
3241
-     * Finds all the fields that correspond to the given table
3242
-     *
3243
-     * @param string $table_alias , array key in EEM_Base::_tables
3244
-     * @return EE_Model_Field_Base[]
3245
-     */
3246
-    public function _get_fields_for_table($table_alias)
3247
-    {
3248
-        return $this->_fields[ $table_alias ];
3249
-    }
3250
-
3251
-
3252
-
3253
-    /**
3254
-     * Recurses through all the where parameters, and finds all the related models we'll need
3255
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3256
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3257
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3258
-     * related Registration, Transaction, and Payment models.
3259
-     *
3260
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3261
-     * @return EE_Model_Query_Info_Carrier
3262
-     * @throws EE_Error
3263
-     */
3264
-    public function _extract_related_models_from_query($query_params)
3265
-    {
3266
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3267
-        if (array_key_exists(0, $query_params)) {
3268
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3269
-        }
3270
-        if (array_key_exists('group_by', $query_params)) {
3271
-            if (is_array($query_params['group_by'])) {
3272
-                $this->_extract_related_models_from_sub_params_array_values(
3273
-                    $query_params['group_by'],
3274
-                    $query_info_carrier,
3275
-                    'group_by'
3276
-                );
3277
-            } elseif (! empty($query_params['group_by'])) {
3278
-                $this->_extract_related_model_info_from_query_param(
3279
-                    $query_params['group_by'],
3280
-                    $query_info_carrier,
3281
-                    'group_by'
3282
-                );
3283
-            }
3284
-        }
3285
-        if (array_key_exists('having', $query_params)) {
3286
-            $this->_extract_related_models_from_sub_params_array_keys(
3287
-                $query_params[0],
3288
-                $query_info_carrier,
3289
-                'having'
3290
-            );
3291
-        }
3292
-        if (array_key_exists('order_by', $query_params)) {
3293
-            if (is_array($query_params['order_by'])) {
3294
-                $this->_extract_related_models_from_sub_params_array_keys(
3295
-                    $query_params['order_by'],
3296
-                    $query_info_carrier,
3297
-                    'order_by'
3298
-                );
3299
-            } elseif (! empty($query_params['order_by'])) {
3300
-                $this->_extract_related_model_info_from_query_param(
3301
-                    $query_params['order_by'],
3302
-                    $query_info_carrier,
3303
-                    'order_by'
3304
-                );
3305
-            }
3306
-        }
3307
-        if (array_key_exists('force_join', $query_params)) {
3308
-            $this->_extract_related_models_from_sub_params_array_values(
3309
-                $query_params['force_join'],
3310
-                $query_info_carrier,
3311
-                'force_join'
3312
-            );
3313
-        }
3314
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3315
-        return $query_info_carrier;
3316
-    }
3317
-
3318
-
3319
-
3320
-    /**
3321
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3322
-     *
3323
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3324
-     *                                                      $query_params['having']
3325
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3326
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3327
-     * @throws EE_Error
3328
-     * @return \EE_Model_Query_Info_Carrier
3329
-     */
3330
-    private function _extract_related_models_from_sub_params_array_keys(
3331
-        $sub_query_params,
3332
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3333
-        $query_param_type
3334
-    ) {
3335
-        if (! empty($sub_query_params)) {
3336
-            $sub_query_params = (array) $sub_query_params;
3337
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3338
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3339
-                $this->_extract_related_model_info_from_query_param(
3340
-                    $param,
3341
-                    $model_query_info_carrier,
3342
-                    $query_param_type
3343
-                );
3344
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3345
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3346
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3347
-                // of array('Registration.TXN_ID'=>23)
3348
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3349
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3350
-                    if (! is_array($possibly_array_of_params)) {
3351
-                        throw new EE_Error(sprintf(
3352
-                            __(
3353
-                                "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3354
-                                "event_espresso"
3355
-                            ),
3356
-                            $param,
3357
-                            $possibly_array_of_params
3358
-                        ));
3359
-                    }
3360
-                    $this->_extract_related_models_from_sub_params_array_keys(
3361
-                        $possibly_array_of_params,
3362
-                        $model_query_info_carrier,
3363
-                        $query_param_type
3364
-                    );
3365
-                } elseif ($query_param_type === 0 // ie WHERE
3366
-                          && is_array($possibly_array_of_params)
3367
-                          && isset($possibly_array_of_params[2])
3368
-                          && $possibly_array_of_params[2] == true
3369
-                ) {
3370
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3371
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3372
-                    // from which we should extract query parameters!
3373
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3374
-                        throw new EE_Error(sprintf(__(
3375
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3376
-                            "event_espresso"
3377
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3378
-                    }
3379
-                    $this->_extract_related_model_info_from_query_param(
3380
-                        $possibly_array_of_params[1],
3381
-                        $model_query_info_carrier,
3382
-                        $query_param_type
3383
-                    );
3384
-                }
3385
-            }
3386
-        }
3387
-        return $model_query_info_carrier;
3388
-    }
3389
-
3390
-
3391
-
3392
-    /**
3393
-     * For extracting related models from forced_joins, where the array values contain the info about what
3394
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3395
-     *
3396
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3397
-     *                                                      $query_params['having']
3398
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3399
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3400
-     * @throws EE_Error
3401
-     * @return \EE_Model_Query_Info_Carrier
3402
-     */
3403
-    private function _extract_related_models_from_sub_params_array_values(
3404
-        $sub_query_params,
3405
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3406
-        $query_param_type
3407
-    ) {
3408
-        if (! empty($sub_query_params)) {
3409
-            if (! is_array($sub_query_params)) {
3410
-                throw new EE_Error(sprintf(
3411
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3412
-                    $sub_query_params
3413
-                ));
3414
-            }
3415
-            foreach ($sub_query_params as $param) {
3416
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3417
-                $this->_extract_related_model_info_from_query_param(
3418
-                    $param,
3419
-                    $model_query_info_carrier,
3420
-                    $query_param_type
3421
-                );
3422
-            }
3423
-        }
3424
-        return $model_query_info_carrier;
3425
-    }
3426
-
3427
-
3428
-
3429
-    /**
3430
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3431
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3432
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3433
-     * but use them in a different order. Eg, we need to know what models we are querying
3434
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3435
-     * other models before we can finalize the where clause SQL.
3436
-     *
3437
-     * @param array $query_params
3438
-     * @throws EE_Error
3439
-     * @return EE_Model_Query_Info_Carrier
3440
-     */
3441
-    public function _create_model_query_info_carrier($query_params)
3442
-    {
3443
-        if (! is_array($query_params)) {
3444
-            EE_Error::doing_it_wrong(
3445
-                'EEM_Base::_create_model_query_info_carrier',
3446
-                sprintf(
3447
-                    __(
3448
-                        '$query_params should be an array, you passed a variable of type %s',
3449
-                        'event_espresso'
3450
-                    ),
3451
-                    gettype($query_params)
3452
-                ),
3453
-                '4.6.0'
3454
-            );
3455
-            $query_params = array();
3456
-        }
3457
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3458
-        // first check if we should alter the query to account for caps or not
3459
-        // because the caps might require us to do extra joins
3460
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3461
-            $query_params[0] = $where_query_params = array_replace_recursive(
3462
-                $where_query_params,
3463
-                $this->caps_where_conditions(
3464
-                    $query_params['caps']
3465
-                )
3466
-            );
3467
-        }
3468
-        $query_object = $this->_extract_related_models_from_query($query_params);
3469
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3470
-        foreach ($where_query_params as $key => $value) {
3471
-            if (is_int($key)) {
3472
-                throw new EE_Error(
3473
-                    sprintf(
3474
-                        __(
3475
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3476
-                            "event_espresso"
3477
-                        ),
3478
-                        $key,
3479
-                        var_export($value, true),
3480
-                        var_export($query_params, true),
3481
-                        get_class($this)
3482
-                    )
3483
-                );
3484
-            }
3485
-        }
3486
-        if (array_key_exists('default_where_conditions', $query_params)
3487
-            && ! empty($query_params['default_where_conditions'])
3488
-        ) {
3489
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3490
-        } else {
3491
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3492
-        }
3493
-        $where_query_params = array_merge(
3494
-            $this->_get_default_where_conditions_for_models_in_query(
3495
-                $query_object,
3496
-                $use_default_where_conditions,
3497
-                $where_query_params
3498
-            ),
3499
-            $where_query_params
3500
-        );
3501
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3502
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3503
-        // So we need to setup a subquery and use that for the main join.
3504
-        // Note for now this only works on the primary table for the model.
3505
-        // So for instance, you could set the limit array like this:
3506
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3507
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3508
-            $query_object->set_main_model_join_sql(
3509
-                $this->_construct_limit_join_select(
3510
-                    $query_params['on_join_limit'][0],
3511
-                    $query_params['on_join_limit'][1]
3512
-                )
3513
-            );
3514
-        }
3515
-        // set limit
3516
-        if (array_key_exists('limit', $query_params)) {
3517
-            if (is_array($query_params['limit'])) {
3518
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3519
-                    $e = sprintf(
3520
-                        __(
3521
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3522
-                            "event_espresso"
3523
-                        ),
3524
-                        http_build_query($query_params['limit'])
3525
-                    );
3526
-                    throw new EE_Error($e . "|" . $e);
3527
-                }
3528
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3529
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3530
-            } elseif (! empty($query_params['limit'])) {
3531
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3532
-            }
3533
-        }
3534
-        // set order by
3535
-        if (array_key_exists('order_by', $query_params)) {
3536
-            if (is_array($query_params['order_by'])) {
3537
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3538
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3539
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3540
-                if (array_key_exists('order', $query_params)) {
3541
-                    throw new EE_Error(
3542
-                        sprintf(
3543
-                            __(
3544
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3545
-                                "event_espresso"
3546
-                            ),
3547
-                            get_class($this),
3548
-                            implode(", ", array_keys($query_params['order_by'])),
3549
-                            implode(", ", $query_params['order_by']),
3550
-                            $query_params['order']
3551
-                        )
3552
-                    );
3553
-                }
3554
-                $this->_extract_related_models_from_sub_params_array_keys(
3555
-                    $query_params['order_by'],
3556
-                    $query_object,
3557
-                    'order_by'
3558
-                );
3559
-                // assume it's an array of fields to order by
3560
-                $order_array = array();
3561
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3562
-                    $order = $this->_extract_order($order);
3563
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3564
-                }
3565
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3566
-            } elseif (! empty($query_params['order_by'])) {
3567
-                $this->_extract_related_model_info_from_query_param(
3568
-                    $query_params['order_by'],
3569
-                    $query_object,
3570
-                    'order',
3571
-                    $query_params['order_by']
3572
-                );
3573
-                $order = isset($query_params['order'])
3574
-                    ? $this->_extract_order($query_params['order'])
3575
-                    : 'DESC';
3576
-                $query_object->set_order_by_sql(
3577
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3578
-                );
3579
-            }
3580
-        }
3581
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3582
-        if (! array_key_exists('order_by', $query_params)
3583
-            && array_key_exists('order', $query_params)
3584
-            && ! empty($query_params['order'])
3585
-        ) {
3586
-            $pk_field = $this->get_primary_key_field();
3587
-            $order = $this->_extract_order($query_params['order']);
3588
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3589
-        }
3590
-        // set group by
3591
-        if (array_key_exists('group_by', $query_params)) {
3592
-            if (is_array($query_params['group_by'])) {
3593
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3594
-                $group_by_array = array();
3595
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3596
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3597
-                }
3598
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3599
-            } elseif (! empty($query_params['group_by'])) {
3600
-                $query_object->set_group_by_sql(
3601
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3602
-                );
3603
-            }
3604
-        }
3605
-        // set having
3606
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3607
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3608
-        }
3609
-        // now, just verify they didn't pass anything wack
3610
-        foreach ($query_params as $query_key => $query_value) {
3611
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3612
-                throw new EE_Error(
3613
-                    sprintf(
3614
-                        __(
3615
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3616
-                            'event_espresso'
3617
-                        ),
3618
-                        $query_key,
3619
-                        get_class($this),
3620
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3621
-                        implode(',', $this->_allowed_query_params)
3622
-                    )
3623
-                );
3624
-            }
3625
-        }
3626
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3627
-        if (empty($main_model_join_sql)) {
3628
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3629
-        }
3630
-        return $query_object;
3631
-    }
3632
-
3633
-
3634
-
3635
-    /**
3636
-     * Gets the where conditions that should be imposed on the query based on the
3637
-     * context (eg reading frontend, backend, edit or delete).
3638
-     *
3639
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3640
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3641
-     * @throws EE_Error
3642
-     */
3643
-    public function caps_where_conditions($context = self::caps_read)
3644
-    {
3645
-        EEM_Base::verify_is_valid_cap_context($context);
3646
-        $cap_where_conditions = array();
3647
-        $cap_restrictions = $this->caps_missing($context);
3648
-        /**
3649
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3650
-         */
3651
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3652
-            $cap_where_conditions = array_replace_recursive(
3653
-                $cap_where_conditions,
3654
-                $restriction_if_no_cap->get_default_where_conditions()
3655
-            );
3656
-        }
3657
-        return apply_filters(
3658
-            'FHEE__EEM_Base__caps_where_conditions__return',
3659
-            $cap_where_conditions,
3660
-            $this,
3661
-            $context,
3662
-            $cap_restrictions
3663
-        );
3664
-    }
3665
-
3666
-
3667
-
3668
-    /**
3669
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3670
-     * otherwise throws an exception
3671
-     *
3672
-     * @param string $should_be_order_string
3673
-     * @return string either ASC, asc, DESC or desc
3674
-     * @throws EE_Error
3675
-     */
3676
-    private function _extract_order($should_be_order_string)
3677
-    {
3678
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3679
-            return $should_be_order_string;
3680
-        }
3681
-        throw new EE_Error(
3682
-            sprintf(
3683
-                __(
3684
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3685
-                    "event_espresso"
3686
-                ),
3687
-                get_class($this),
3688
-                $should_be_order_string
3689
-            )
3690
-        );
3691
-    }
3692
-
3693
-
3694
-
3695
-    /**
3696
-     * Looks at all the models which are included in this query, and asks each
3697
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3698
-     * so they can be merged
3699
-     *
3700
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3701
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3702
-     *                                                                  'none' means NO default where conditions will
3703
-     *                                                                  be used AT ALL during this query.
3704
-     *                                                                  'other_models_only' means default where
3705
-     *                                                                  conditions from other models will be used, but
3706
-     *                                                                  not for this primary model. 'all', the default,
3707
-     *                                                                  means default where conditions will apply as
3708
-     *                                                                  normal
3709
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3710
-     * @throws EE_Error
3711
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3712
-     */
3713
-    private function _get_default_where_conditions_for_models_in_query(
3714
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3715
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3716
-        $where_query_params = array()
3717
-    ) {
3718
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3719
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3720
-            throw new EE_Error(sprintf(
3721
-                __(
3722
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3723
-                    "event_espresso"
3724
-                ),
3725
-                $use_default_where_conditions,
3726
-                implode(", ", $allowed_used_default_where_conditions_values)
3727
-            ));
3728
-        }
3729
-        $universal_query_params = array();
3730
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3731
-            $universal_query_params = $this->_get_default_where_conditions();
3732
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3733
-            $universal_query_params = $this->_get_minimum_where_conditions();
3734
-        }
3735
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3736
-            $related_model = $this->get_related_model_obj($model_name);
3737
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3738
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3739
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3740
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3741
-            } else {
3742
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3743
-                continue;
3744
-            }
3745
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3746
-                $related_model_universal_where_params,
3747
-                $where_query_params,
3748
-                $related_model,
3749
-                $model_relation_path
3750
-            );
3751
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3752
-                $universal_query_params,
3753
-                $overrides
3754
-            );
3755
-        }
3756
-        return $universal_query_params;
3757
-    }
3758
-
3759
-
3760
-
3761
-    /**
3762
-     * Determines whether or not we should use default where conditions for the model in question
3763
-     * (this model, or other related models).
3764
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3765
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3766
-     * We should use default where conditions on related models when they requested to use default where conditions
3767
-     * on all models, or specifically just on other related models
3768
-     * @param      $default_where_conditions_value
3769
-     * @param bool $for_this_model false means this is for OTHER related models
3770
-     * @return bool
3771
-     */
3772
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3773
-    {
3774
-        return (
3775
-                   $for_this_model
3776
-                   && in_array(
3777
-                       $default_where_conditions_value,
3778
-                       array(
3779
-                           EEM_Base::default_where_conditions_all,
3780
-                           EEM_Base::default_where_conditions_this_only,
3781
-                           EEM_Base::default_where_conditions_minimum_others,
3782
-                       ),
3783
-                       true
3784
-                   )
3785
-               )
3786
-               || (
3787
-                   ! $for_this_model
3788
-                   && in_array(
3789
-                       $default_where_conditions_value,
3790
-                       array(
3791
-                           EEM_Base::default_where_conditions_all,
3792
-                           EEM_Base::default_where_conditions_others_only,
3793
-                       ),
3794
-                       true
3795
-                   )
3796
-               );
3797
-    }
3798
-
3799
-    /**
3800
-     * Determines whether or not we should use default minimum conditions for the model in question
3801
-     * (this model, or other related models).
3802
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3803
-     * where conditions.
3804
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3805
-     * on this model or others
3806
-     * @param      $default_where_conditions_value
3807
-     * @param bool $for_this_model false means this is for OTHER related models
3808
-     * @return bool
3809
-     */
3810
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3811
-    {
3812
-        return (
3813
-                   $for_this_model
3814
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3815
-               )
3816
-               || (
3817
-                   ! $for_this_model
3818
-                   && in_array(
3819
-                       $default_where_conditions_value,
3820
-                       array(
3821
-                           EEM_Base::default_where_conditions_minimum_others,
3822
-                           EEM_Base::default_where_conditions_minimum_all,
3823
-                       ),
3824
-                       true
3825
-                   )
3826
-               );
3827
-    }
3828
-
3829
-
3830
-    /**
3831
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3832
-     * then we also add a special where condition which allows for that model's primary key
3833
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3834
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3835
-     *
3836
-     * @param array    $default_where_conditions
3837
-     * @param array    $provided_where_conditions
3838
-     * @param EEM_Base $model
3839
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3840
-     * @return array like EEM_Base::get_all's $query_params[0]
3841
-     * @throws EE_Error
3842
-     */
3843
-    private function _override_defaults_or_make_null_friendly(
3844
-        $default_where_conditions,
3845
-        $provided_where_conditions,
3846
-        $model,
3847
-        $model_relation_path
3848
-    ) {
3849
-        $null_friendly_where_conditions = array();
3850
-        $none_overridden = true;
3851
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3852
-        foreach ($default_where_conditions as $key => $val) {
3853
-            if (isset($provided_where_conditions[ $key ])) {
3854
-                $none_overridden = false;
3855
-            } else {
3856
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3857
-            }
3858
-        }
3859
-        if ($none_overridden && $default_where_conditions) {
3860
-            if ($model->has_primary_key_field()) {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3862
-                                                                                . "."
3863
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3864
-            }/*else{
37
+	/**
38
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
41
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
+	 *
43
+	 * @var boolean
44
+	 */
45
+	private $_values_already_prepared_by_model_object = 0;
46
+
47
+	/**
48
+	 * when $_values_already_prepared_by_model_object equals this, we assume
49
+	 * the data is just like form input that needs to have the model fields'
50
+	 * prepare_for_set and prepare_for_use_in_db called on it
51
+	 */
52
+	const not_prepared_by_model_object = 0;
53
+
54
+	/**
55
+	 * when $_values_already_prepared_by_model_object equals this, we
56
+	 * assume this value is coming from a model object and doesn't need to have
57
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
58
+	 */
59
+	const prepared_by_model_object = 1;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the values are already to be used in the database (ie no processing is done
64
+	 * on them by the model's fields)
65
+	 */
66
+	const prepared_for_use_in_db = 2;
67
+
68
+
69
+	protected $singular_item = 'Item';
70
+
71
+	protected $plural_item   = 'Items';
72
+
73
+	/**
74
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
+	 */
76
+	protected $_tables;
77
+
78
+	/**
79
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
+	 *
83
+	 * @var \EE_Model_Field_Base[][] $_fields
84
+	 */
85
+	protected $_fields;
86
+
87
+	/**
88
+	 * array of different kinds of relations
89
+	 *
90
+	 * @var \EE_Model_Relation_Base[] $_model_relations
91
+	 */
92
+	protected $_model_relations;
93
+
94
+	/**
95
+	 * @var \EE_Index[] $_indexes
96
+	 */
97
+	protected $_indexes = array();
98
+
99
+	/**
100
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
101
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
+	 * by setting the same columns as used in these queries in the query yourself.
103
+	 *
104
+	 * @var EE_Default_Where_Conditions
105
+	 */
106
+	protected $_default_where_conditions_strategy;
107
+
108
+	/**
109
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
+	 * This is particularly useful when you want something between 'none' and 'default'
111
+	 *
112
+	 * @var EE_Default_Where_Conditions
113
+	 */
114
+	protected $_minimum_where_conditions_strategy;
115
+
116
+	/**
117
+	 * String describing how to find the "owner" of this model's objects.
118
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
+	 * But when there isn't, this indicates which related model, or transiently-related model,
120
+	 * has the foreign key to the wp_users table.
121
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
+	 * related to events, and events have a foreign key to wp_users.
123
+	 * On EEM_Transaction, this would be 'Transaction.Event'
124
+	 *
125
+	 * @var string
126
+	 */
127
+	protected $_model_chain_to_wp_user = '';
128
+
129
+	/**
130
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
+	 * don't need it (particularly CPT models)
132
+	 *
133
+	 * @var bool
134
+	 */
135
+	protected $_ignore_where_strategy = false;
136
+
137
+	/**
138
+	 * String used in caps relating to this model. Eg, if the caps relating to this
139
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
+	 *
141
+	 * @var string. If null it hasn't been initialized yet. If false then we
142
+	 * have indicated capabilities don't apply to this
143
+	 */
144
+	protected $_caps_slug = null;
145
+
146
+	/**
147
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
+	 * and next-level keys are capability names, and each's value is a
149
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
151
+	 * and then each capability in the corresponding sub-array that they're missing
152
+	 * adds the where conditions onto the query.
153
+	 *
154
+	 * @var array
155
+	 */
156
+	protected $_cap_restrictions = array(
157
+		self::caps_read       => array(),
158
+		self::caps_read_admin => array(),
159
+		self::caps_edit       => array(),
160
+		self::caps_delete     => array(),
161
+	);
162
+
163
+	/**
164
+	 * Array defining which cap restriction generators to use to create default
165
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
166
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
+	 * automatically set this to false (not just null).
169
+	 *
170
+	 * @var EE_Restriction_Generator_Base[]
171
+	 */
172
+	protected $_cap_restriction_generators = array();
173
+
174
+	/**
175
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
+	 */
177
+	const caps_read       = 'read';
178
+
179
+	const caps_read_admin = 'read_admin';
180
+
181
+	const caps_edit       = 'edit';
182
+
183
+	const caps_delete     = 'delete';
184
+
185
+	/**
186
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
+	 * maps to 'read' because when looking for relevant permissions we're going to use
189
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
190
+	 *
191
+	 * @var array
192
+	 */
193
+	protected $_cap_contexts_to_cap_action_map = array(
194
+		self::caps_read       => 'read',
195
+		self::caps_read_admin => 'read',
196
+		self::caps_edit       => 'edit',
197
+		self::caps_delete     => 'delete',
198
+	);
199
+
200
+	/**
201
+	 * Timezone
202
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
+	 * EE_Datetime_Field data type will have access to it.
206
+	 *
207
+	 * @var string
208
+	 */
209
+	protected $_timezone;
210
+
211
+
212
+	/**
213
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
+	 * multisite.
215
+	 *
216
+	 * @var int
217
+	 */
218
+	protected static $_model_query_blog_id;
219
+
220
+	/**
221
+	 * A copy of _fields, except the array keys are the model names pointed to by
222
+	 * the field
223
+	 *
224
+	 * @var EE_Model_Field_Base[]
225
+	 */
226
+	private $_cache_foreign_key_to_fields = array();
227
+
228
+	/**
229
+	 * Cached list of all the fields on the model, indexed by their name
230
+	 *
231
+	 * @var EE_Model_Field_Base[]
232
+	 */
233
+	private $_cached_fields = null;
234
+
235
+	/**
236
+	 * Cached list of all the fields on the model, except those that are
237
+	 * marked as only pertinent to the database
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cached_fields_non_db_only = null;
242
+
243
+	/**
244
+	 * A cached reference to the primary key for quick lookup
245
+	 *
246
+	 * @var EE_Model_Field_Base
247
+	 */
248
+	private $_primary_key_field = null;
249
+
250
+	/**
251
+	 * Flag indicating whether this model has a primary key or not
252
+	 *
253
+	 * @var boolean
254
+	 */
255
+	protected $_has_primary_key_field = null;
256
+
257
+	/**
258
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
259
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
+	 * This should be true for models that deal with data that should exist independent of EE.
261
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
263
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
265
+	 * @var boolean
266
+	 */
267
+	protected $_wp_core_model = false;
268
+
269
+	/**
270
+	 *    List of valid operators that can be used for querying.
271
+	 * The keys are all operators we'll accept, the values are the real SQL
272
+	 * operators used
273
+	 *
274
+	 * @var array
275
+	 */
276
+	protected $_valid_operators = array(
277
+		'='           => '=',
278
+		'<='          => '<=',
279
+		'<'           => '<',
280
+		'>='          => '>=',
281
+		'>'           => '>',
282
+		'!='          => '!=',
283
+		'LIKE'        => 'LIKE',
284
+		'like'        => 'LIKE',
285
+		'NOT_LIKE'    => 'NOT LIKE',
286
+		'not_like'    => 'NOT LIKE',
287
+		'NOT LIKE'    => 'NOT LIKE',
288
+		'not like'    => 'NOT LIKE',
289
+		'IN'          => 'IN',
290
+		'in'          => 'IN',
291
+		'NOT_IN'      => 'NOT IN',
292
+		'not_in'      => 'NOT IN',
293
+		'NOT IN'      => 'NOT IN',
294
+		'not in'      => 'NOT IN',
295
+		'between'     => 'BETWEEN',
296
+		'BETWEEN'     => 'BETWEEN',
297
+		'IS_NOT_NULL' => 'IS NOT NULL',
298
+		'is_not_null' => 'IS NOT NULL',
299
+		'IS NOT NULL' => 'IS NOT NULL',
300
+		'is not null' => 'IS NOT NULL',
301
+		'IS_NULL'     => 'IS NULL',
302
+		'is_null'     => 'IS NULL',
303
+		'IS NULL'     => 'IS NULL',
304
+		'is null'     => 'IS NULL',
305
+		'REGEXP'      => 'REGEXP',
306
+		'regexp'      => 'REGEXP',
307
+		'NOT_REGEXP'  => 'NOT REGEXP',
308
+		'not_regexp'  => 'NOT REGEXP',
309
+		'NOT REGEXP'  => 'NOT REGEXP',
310
+		'not regexp'  => 'NOT REGEXP',
311
+	);
312
+
313
+	/**
314
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
+	 *
316
+	 * @var array
317
+	 */
318
+	protected $_in_style_operators = array('IN', 'NOT IN');
319
+
320
+	/**
321
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
+	 * '12-31-2012'"
323
+	 *
324
+	 * @var array
325
+	 */
326
+	protected $_between_style_operators = array('BETWEEN');
327
+
328
+	/**
329
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
+	 * @var array
331
+	 */
332
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
+	/**
334
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
+	 * on a join table.
336
+	 *
337
+	 * @var array
338
+	 */
339
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
+
341
+	/**
342
+	 * Allowed values for $query_params['order'] for ordering in queries
343
+	 *
344
+	 * @var array
345
+	 */
346
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
+
348
+	/**
349
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
351
+	 *
352
+	 * @var array
353
+	 */
354
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
+
356
+	/**
357
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
359
+	 *
360
+	 * @var array
361
+	 */
362
+	private $_allowed_query_params = array(
363
+		0,
364
+		'limit',
365
+		'order_by',
366
+		'group_by',
367
+		'having',
368
+		'force_join',
369
+		'order',
370
+		'on_join_limit',
371
+		'default_where_conditions',
372
+		'caps',
373
+		'extra_selects'
374
+	);
375
+
376
+	/**
377
+	 * All the data types that can be used in $wpdb->prepare statements.
378
+	 *
379
+	 * @var array
380
+	 */
381
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
+
383
+	/**
384
+	 * @var EE_Registry $EE
385
+	 */
386
+	protected $EE = null;
387
+
388
+
389
+	/**
390
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
+	 *
392
+	 * @var int
393
+	 */
394
+	protected $_show_next_x_db_queries = 0;
395
+
396
+	/**
397
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
+	 * WHERE, GROUP_BY, etc.
400
+	 *
401
+	 * @var CustomSelects
402
+	 */
403
+	protected $_custom_selections = array();
404
+
405
+	/**
406
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
+	 * caches every model object we've fetched from the DB on this request
408
+	 *
409
+	 * @var array
410
+	 */
411
+	protected $_entity_map;
412
+
413
+	/**
414
+	 * @var LoaderInterface $loader
415
+	 */
416
+	private static $loader;
417
+
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error(
520
+				sprintf(
521
+					__(
522
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
523
+						'event_espresso'
524
+					),
525
+					get_class($this)
526
+				)
527
+			);
528
+		}
529
+		/**
530
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
531
+		 */
532
+		if (empty(EEM_Base::$_model_query_blog_id)) {
533
+			EEM_Base::set_model_query_blog_id();
534
+		}
535
+		/**
536
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
537
+		 * just use EE_Register_Model_Extension
538
+		 *
539
+		 * @var EE_Table_Base[] $_tables
540
+		 */
541
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
542
+		foreach ($this->_tables as $table_alias => $table_obj) {
543
+			/** @var $table_obj EE_Table_Base */
544
+			$table_obj->_construct_finalize_with_alias($table_alias);
545
+			if ($table_obj instanceof EE_Secondary_Table) {
546
+				/** @var $table_obj EE_Secondary_Table */
547
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
548
+			}
549
+		}
550
+		/**
551
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
552
+		 * EE_Register_Model_Extension
553
+		 *
554
+		 * @param EE_Model_Field_Base[] $_fields
555
+		 */
556
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
557
+		$this->_invalidate_field_caches();
558
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
559
+			if (! array_key_exists($table_alias, $this->_tables)) {
560
+				throw new EE_Error(sprintf(__(
561
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
562
+					'event_espresso'
563
+				), $table_alias, implode(",", $this->_fields)));
564
+			}
565
+			foreach ($fields_for_table as $field_name => $field_obj) {
566
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
+				// primary key field base has a slightly different _construct_finalize
568
+				/** @var $field_obj EE_Model_Field_Base */
569
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
+			}
571
+		}
572
+		// everything is related to Extra_Meta
573
+		if (get_class($this) !== 'EEM_Extra_Meta') {
574
+			// make extra meta related to everything, but don't block deleting things just
575
+			// because they have related extra meta info. For now just orphan those extra meta
576
+			// in the future we should automatically delete them
577
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		// and change logs
580
+		if (get_class($this) !== 'EEM_Change_Log') {
581
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
+		}
583
+		/**
584
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
+		 * EE_Register_Model_Extension
586
+		 *
587
+		 * @param EE_Model_Relation_Base[] $_model_relations
588
+		 */
589
+		$this->_model_relations = (array) apply_filters(
590
+			'FHEE__' . get_class($this) . '__construct__model_relations',
591
+			$this->_model_relations
592
+		);
593
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
594
+			/** @var $relation_obj EE_Model_Relation_Base */
595
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
596
+		}
597
+		foreach ($this->_indexes as $index_name => $index_obj) {
598
+			/** @var $index_obj EE_Index */
599
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
600
+		}
601
+		$this->set_timezone($timezone);
602
+		// finalize default where condition strategy, or set default
603
+		if (! $this->_default_where_conditions_strategy) {
604
+			// nothing was set during child constructor, so set default
605
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
606
+		}
607
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
608
+		if (! $this->_minimum_where_conditions_strategy) {
609
+			// nothing was set during child constructor, so set default
610
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
611
+		}
612
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
613
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
614
+		// to indicate to NOT set it, set it to the logical default
615
+		if ($this->_caps_slug === null) {
616
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
617
+		}
618
+		// initialize the standard cap restriction generators if none were specified by the child constructor
619
+		if ($this->_cap_restriction_generators !== false) {
620
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
621
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
622
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
623
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
624
+						new EE_Restriction_Generator_Protected(),
625
+						$cap_context,
626
+						$this
627
+					);
628
+				}
629
+			}
630
+		}
631
+		// if there are cap restriction generators, use them to make the default cap restrictions
632
+		if ($this->_cap_restriction_generators !== false) {
633
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
634
+				if (! $generator_object) {
635
+					continue;
636
+				}
637
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
638
+					throw new EE_Error(
639
+						sprintf(
640
+							__(
641
+								'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
642
+								'event_espresso'
643
+							),
644
+							$context,
645
+							$this->get_this_model_name()
646
+						)
647
+					);
648
+				}
649
+				$action = $this->cap_action_for_context($context);
650
+				if (! $generator_object->construction_finalized()) {
651
+					$generator_object->_construct_finalize($this, $action);
652
+				}
653
+			}
654
+		}
655
+		do_action('AHEE__' . get_class($this) . '__construct__end');
656
+	}
657
+
658
+
659
+
660
+	/**
661
+	 * Used to set the $_model_query_blog_id static property.
662
+	 *
663
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
664
+	 *                      value for get_current_blog_id() will be used.
665
+	 */
666
+	public static function set_model_query_blog_id($blog_id = 0)
667
+	{
668
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
669
+	}
670
+
671
+
672
+
673
+	/**
674
+	 * Returns whatever is set as the internal $model_query_blog_id.
675
+	 *
676
+	 * @return int
677
+	 */
678
+	public static function get_model_query_blog_id()
679
+	{
680
+		return EEM_Base::$_model_query_blog_id;
681
+	}
682
+
683
+
684
+
685
+	/**
686
+	 * This function is a singleton method used to instantiate the Espresso_model object
687
+	 *
688
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
689
+	 *                                (and any incoming timezone data that gets saved).
690
+	 *                                Note this just sends the timezone info to the date time model field objects.
691
+	 *                                Default is NULL
692
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
693
+	 * @return static (as in the concrete child class)
694
+	 * @throws EE_Error
695
+	 * @throws InvalidArgumentException
696
+	 * @throws InvalidDataTypeException
697
+	 * @throws InvalidInterfaceException
698
+	 */
699
+	public static function instance($timezone = null)
700
+	{
701
+		// check if instance of Espresso_model already exists
702
+		if (! static::$_instance instanceof static) {
703
+			// instantiate Espresso_model
704
+			static::$_instance = new static(
705
+				$timezone,
706
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
707
+			);
708
+		}
709
+		// we might have a timezone set, let set_timezone decide what to do with it
710
+		static::$_instance->set_timezone($timezone);
711
+		// Espresso_model object
712
+		return static::$_instance;
713
+	}
714
+
715
+
716
+
717
+	/**
718
+	 * resets the model and returns it
719
+	 *
720
+	 * @param null | string $timezone
721
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
722
+	 * all its properties reset; if it wasn't instantiated, returns null)
723
+	 * @throws EE_Error
724
+	 * @throws ReflectionException
725
+	 * @throws InvalidArgumentException
726
+	 * @throws InvalidDataTypeException
727
+	 * @throws InvalidInterfaceException
728
+	 */
729
+	public static function reset($timezone = null)
730
+	{
731
+		if (static::$_instance instanceof EEM_Base) {
732
+			// let's try to NOT swap out the current instance for a new one
733
+			// because if someone has a reference to it, we can't remove their reference
734
+			// so it's best to keep using the same reference, but change the original object
735
+			// reset all its properties to their original values as defined in the class
736
+			$r = new ReflectionClass(get_class(static::$_instance));
737
+			$static_properties = $r->getStaticProperties();
738
+			foreach ($r->getDefaultProperties() as $property => $value) {
739
+				// don't set instance to null like it was originally,
740
+				// but it's static anyways, and we're ignoring static properties (for now at least)
741
+				if (! isset($static_properties[ $property ])) {
742
+					static::$_instance->{$property} = $value;
743
+				}
744
+			}
745
+			// and then directly call its constructor again, like we would if we were creating a new one
746
+			static::$_instance->__construct(
747
+				$timezone,
748
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
749
+			);
750
+			return self::instance();
751
+		}
752
+		return null;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * @return LoaderInterface
759
+	 * @throws InvalidArgumentException
760
+	 * @throws InvalidDataTypeException
761
+	 * @throws InvalidInterfaceException
762
+	 */
763
+	private static function getLoader()
764
+	{
765
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
766
+			EEM_Base::$loader = LoaderFactory::getLoader();
767
+		}
768
+		return EEM_Base::$loader;
769
+	}
770
+
771
+
772
+
773
+	/**
774
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
775
+	 *
776
+	 * @param  boolean $translated return localized strings or JUST the array.
777
+	 * @return array
778
+	 * @throws EE_Error
779
+	 * @throws InvalidArgumentException
780
+	 * @throws InvalidDataTypeException
781
+	 * @throws InvalidInterfaceException
782
+	 */
783
+	public function status_array($translated = false)
784
+	{
785
+		if (! array_key_exists('Status', $this->_model_relations)) {
786
+			return array();
787
+		}
788
+		$model_name = $this->get_this_model_name();
789
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
790
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
791
+		$status_array = array();
792
+		foreach ($stati as $status) {
793
+			$status_array[ $status->ID() ] = $status->get('STS_code');
794
+		}
795
+		return $translated
796
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
797
+			: $status_array;
798
+	}
799
+
800
+
801
+
802
+	/**
803
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
804
+	 *
805
+	 * @param array $query_params             {
806
+	 * @var array $0 (where) array {
807
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
808
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
809
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
810
+	 *                                        conditions based on related models (and even
811
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
812
+	 *                                        name. Eg,
813
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
814
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
815
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
816
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
817
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
818
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
819
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
820
+	 *                                        to Venues (even when each of those models actually consisted of two
821
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
822
+	 *                                        just having
823
+	 *                                        "Venue.VNU_ID", you could have
824
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
825
+	 *                                        events are related to Registrations, which are related to Attendees). You
826
+	 *                                        can take it even further with
827
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
828
+	 *                                        (from the default of '='), change the value to an numerically-indexed
829
+	 *                                        array, where the first item in the list is the operator. eg: array(
830
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
831
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
832
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
833
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
834
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
835
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
836
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
837
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
838
+	 *                                        the value is a field, simply provide a third array item (true) to the
839
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
840
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
841
+	 *                                        Note: you can also use related model field names like you would any other
842
+	 *                                        field name. eg:
843
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
844
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
845
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
846
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
847
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
848
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
849
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
850
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
851
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
852
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
853
+	 *                                        "stick" until you specify an AND. eg
854
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
855
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
856
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
857
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
858
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
859
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
860
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
861
+	 *                                        too, eg:
862
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
863
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
864
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
865
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
866
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
867
+	 *                                        the OFFSET, the 2nd is the LIMIT
868
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
869
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
870
+	 *                                        following format array('on_join_limit'
871
+	 *                                        => array( 'table_alias', array(1,2) ) ).
872
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
873
+	 *                                        values are either 'ASC' or 'DESC'.
874
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
875
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
876
+	 *                                        DESC..." respectively. Like the
877
+	 *                                        'where' conditions, these fields can be on related models. Eg
878
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
879
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
880
+	 *                                        Attendee, Price, Datetime, etc.)
881
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
882
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
883
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
884
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
885
+	 *                                        order by the primary key. Eg,
886
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
887
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
888
+	 *                                        DTT_EVT_start) or
889
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
890
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
891
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
892
+	 *                                        'group_by'=>'VNU_ID', or
893
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
894
+	 *                                        if no
895
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
896
+	 *                                        model's primary key (or combined primary keys). This avoids some
897
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
898
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
899
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
900
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
901
+	 *                                        results)
902
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
903
+	 *                                        array where values are models to be joined in the query.Eg
904
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
905
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
906
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
907
+	 *                                        related models which belongs to the current model
908
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
909
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
910
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
911
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
912
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
913
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
914
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
915
+	 *                                        this model's default where conditions added to the query, use
916
+	 *                                        'this_model_only'. If you want to use all default where conditions
917
+	 *                                        (default), set to 'all'.
918
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
919
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
920
+	 *                                        everything? Or should we only show the current user items they should be
921
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
922
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
923
+	 *                                        }
924
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
925
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
926
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
927
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
928
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
929
+	 *                                        array( array(
930
+	 *                                        'OR'=>array(
931
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
932
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
933
+	 *                                        )
934
+	 *                                        ),
935
+	 *                                        'limit'=>10,
936
+	 *                                        'group_by'=>'TXN_ID'
937
+	 *                                        ));
938
+	 *                                        get all the answers to the question titled "shirt size" for event with id
939
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
940
+	 *                                        'Question.QST_display_text'=>'shirt size',
941
+	 *                                        'Registration.Event.EVT_ID'=>12
942
+	 *                                        ),
943
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
944
+	 *                                        ));
945
+	 * @throws EE_Error
946
+	 */
947
+	public function get_all($query_params = array())
948
+	{
949
+		if (isset($query_params['limit'])
950
+			&& ! isset($query_params['group_by'])
951
+		) {
952
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
953
+		}
954
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
955
+	}
956
+
957
+
958
+
959
+	/**
960
+	 * Modifies the query parameters so we only get back model objects
961
+	 * that "belong" to the current user
962
+	 *
963
+	 * @param array $query_params @see EEM_Base::get_all()
964
+	 * @return array like EEM_Base::get_all
965
+	 */
966
+	public function alter_query_params_to_only_include_mine($query_params = array())
967
+	{
968
+		$wp_user_field_name = $this->wp_user_field_name();
969
+		if ($wp_user_field_name) {
970
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
971
+		}
972
+		return $query_params;
973
+	}
974
+
975
+
976
+
977
+	/**
978
+	 * Returns the name of the field's name that points to the WP_User table
979
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
980
+	 * foreign key to the WP_User table)
981
+	 *
982
+	 * @return string|boolean string on success, boolean false when there is no
983
+	 * foreign key to the WP_User table
984
+	 */
985
+	public function wp_user_field_name()
986
+	{
987
+		try {
988
+			if (! empty($this->_model_chain_to_wp_user)) {
989
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
990
+				$last_model_name = end($models_to_follow_to_wp_users);
991
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
992
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
993
+			} else {
994
+				$model_with_fk_to_wp_users = $this;
995
+				$model_chain_to_wp_user = '';
996
+			}
997
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
998
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
999
+		} catch (EE_Error $e) {
1000
+			return false;
1001
+		}
1002
+	}
1003
+
1004
+
1005
+
1006
+	/**
1007
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
1008
+	 * (or transiently-related model) has a foreign key to the wp_users table;
1009
+	 * useful for finding if model objects of this type are 'owned' by the current user.
1010
+	 * This is an empty string when the foreign key is on this model and when it isn't,
1011
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
1012
+	 * (or transiently-related model)
1013
+	 *
1014
+	 * @return string
1015
+	 */
1016
+	public function model_chain_to_wp_user()
1017
+	{
1018
+		return $this->_model_chain_to_wp_user;
1019
+	}
1020
+
1021
+
1022
+
1023
+	/**
1024
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1025
+	 * like how registrations don't have a foreign key to wp_users, but the
1026
+	 * events they are for are), or is unrelated to wp users.
1027
+	 * generally available
1028
+	 *
1029
+	 * @return boolean
1030
+	 */
1031
+	public function is_owned()
1032
+	{
1033
+		if ($this->model_chain_to_wp_user()) {
1034
+			return true;
1035
+		}
1036
+		try {
1037
+			$this->get_foreign_key_to('WP_User');
1038
+			return true;
1039
+		} catch (EE_Error $e) {
1040
+			return false;
1041
+		}
1042
+	}
1043
+
1044
+
1045
+	/**
1046
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1047
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1048
+	 * the model)
1049
+	 *
1050
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1051
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1052
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1053
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1054
+	 *                                  override this and set the select to "*", or a specific column name, like
1055
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1056
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1057
+	 *                                  the aliases used to refer to this selection, and values are to be
1058
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1059
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1060
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1061
+	 * @throws EE_Error
1062
+	 * @throws InvalidArgumentException
1063
+	 */
1064
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1065
+	{
1066
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1067
+		;
1068
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1069
+		$select_expressions = $columns_to_select === null
1070
+			? $this->_construct_default_select_sql($model_query_info)
1071
+			: '';
1072
+		if ($this->_custom_selections instanceof CustomSelects) {
1073
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1074
+			$select_expressions .= $select_expressions
1075
+				? ', ' . $custom_expressions
1076
+				: $custom_expressions;
1077
+		}
1078
+
1079
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1080
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1081
+	}
1082
+
1083
+
1084
+	/**
1085
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1086
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1087
+	 * method of including extra select information.
1088
+	 *
1089
+	 * @param array             $query_params
1090
+	 * @param null|array|string $columns_to_select
1091
+	 * @return null|CustomSelects
1092
+	 * @throws InvalidArgumentException
1093
+	 */
1094
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1095
+	{
1096
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1097
+			return null;
1098
+		}
1099
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1100
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1101
+		return new CustomSelects($selects);
1102
+	}
1103
+
1104
+
1105
+
1106
+	/**
1107
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1108
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1109
+	 * take care of joins, field preparation etc.
1110
+	 *
1111
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1112
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1113
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1114
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1115
+	 *                                  override this and set the select to "*", or a specific column name, like
1116
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1117
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1118
+	 *                                  the aliases used to refer to this selection, and values are to be
1119
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1120
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1121
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1122
+	 * @throws EE_Error
1123
+	 */
1124
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1125
+	{
1126
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1127
+	}
1128
+
1129
+
1130
+
1131
+	/**
1132
+	 * For creating a custom select statement
1133
+	 *
1134
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1135
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1136
+	 *                                 SQL, and 1=>is the datatype
1137
+	 * @throws EE_Error
1138
+	 * @return string
1139
+	 */
1140
+	private function _construct_select_from_input($columns_to_select)
1141
+	{
1142
+		if (is_array($columns_to_select)) {
1143
+			$select_sql_array = array();
1144
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1145
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1146
+					throw new EE_Error(
1147
+						sprintf(
1148
+							__(
1149
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1150
+								'event_espresso'
1151
+							),
1152
+							$selection_and_datatype,
1153
+							$alias
1154
+						)
1155
+					);
1156
+				}
1157
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1158
+					throw new EE_Error(
1159
+						sprintf(
1160
+							esc_html__(
1161
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1162
+								'event_espresso'
1163
+							),
1164
+							$selection_and_datatype[1],
1165
+							$selection_and_datatype[0],
1166
+							$alias,
1167
+							implode(', ', $this->_valid_wpdb_data_types)
1168
+						)
1169
+					);
1170
+				}
1171
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1172
+			}
1173
+			$columns_to_select_string = implode(', ', $select_sql_array);
1174
+		} else {
1175
+			$columns_to_select_string = $columns_to_select;
1176
+		}
1177
+		return $columns_to_select_string;
1178
+	}
1179
+
1180
+
1181
+
1182
+	/**
1183
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1184
+	 *
1185
+	 * @return string
1186
+	 * @throws EE_Error
1187
+	 */
1188
+	public function primary_key_name()
1189
+	{
1190
+		return $this->get_primary_key_field()->get_name();
1191
+	}
1192
+
1193
+
1194
+
1195
+	/**
1196
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1197
+	 * If there is no primary key on this model, $id is treated as primary key string
1198
+	 *
1199
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1200
+	 * @return EE_Base_Class
1201
+	 */
1202
+	public function get_one_by_ID($id)
1203
+	{
1204
+		if ($this->get_from_entity_map($id)) {
1205
+			return $this->get_from_entity_map($id);
1206
+		}
1207
+		return $this->get_one(
1208
+			$this->alter_query_params_to_restrict_by_ID(
1209
+				$id,
1210
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1211
+			)
1212
+		);
1213
+	}
1214
+
1215
+
1216
+
1217
+	/**
1218
+	 * Alters query parameters to only get items with this ID are returned.
1219
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1220
+	 * or could just be a simple primary key ID
1221
+	 *
1222
+	 * @param int   $id
1223
+	 * @param array $query_params
1224
+	 * @return array of normal query params, @see EEM_Base::get_all
1225
+	 * @throws EE_Error
1226
+	 */
1227
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1228
+	{
1229
+		if (! isset($query_params[0])) {
1230
+			$query_params[0] = array();
1231
+		}
1232
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1233
+		if ($conditions_from_id === null) {
1234
+			$query_params[0][ $this->primary_key_name() ] = $id;
1235
+		} else {
1236
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1237
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1238
+		}
1239
+		return $query_params;
1240
+	}
1241
+
1242
+
1243
+
1244
+	/**
1245
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1246
+	 * array. If no item is found, null is returned.
1247
+	 *
1248
+	 * @param array $query_params like EEM_Base's $query_params variable.
1249
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1250
+	 * @throws EE_Error
1251
+	 */
1252
+	public function get_one($query_params = array())
1253
+	{
1254
+		if (! is_array($query_params)) {
1255
+			EE_Error::doing_it_wrong(
1256
+				'EEM_Base::get_one',
1257
+				sprintf(
1258
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1259
+					gettype($query_params)
1260
+				),
1261
+				'4.6.0'
1262
+			);
1263
+			$query_params = array();
1264
+		}
1265
+		$query_params['limit'] = 1;
1266
+		$items = $this->get_all($query_params);
1267
+		if (empty($items)) {
1268
+			return null;
1269
+		}
1270
+		return array_shift($items);
1271
+	}
1272
+
1273
+
1274
+
1275
+	/**
1276
+	 * Returns the next x number of items in sequence from the given value as
1277
+	 * found in the database matching the given query conditions.
1278
+	 *
1279
+	 * @param mixed $current_field_value    Value used for the reference point.
1280
+	 * @param null  $field_to_order_by      What field is used for the
1281
+	 *                                      reference point.
1282
+	 * @param int   $limit                  How many to return.
1283
+	 * @param array $query_params           Extra conditions on the query.
1284
+	 * @param null  $columns_to_select      If left null, then an array of
1285
+	 *                                      EE_Base_Class objects is returned,
1286
+	 *                                      otherwise you can indicate just the
1287
+	 *                                      columns you want returned.
1288
+	 * @return EE_Base_Class[]|array
1289
+	 * @throws EE_Error
1290
+	 */
1291
+	public function next_x(
1292
+		$current_field_value,
1293
+		$field_to_order_by = null,
1294
+		$limit = 1,
1295
+		$query_params = array(),
1296
+		$columns_to_select = null
1297
+	) {
1298
+		return $this->_get_consecutive(
1299
+			$current_field_value,
1300
+			'>',
1301
+			$field_to_order_by,
1302
+			$limit,
1303
+			$query_params,
1304
+			$columns_to_select
1305
+		);
1306
+	}
1307
+
1308
+
1309
+
1310
+	/**
1311
+	 * Returns the previous x number of items in sequence from the given value
1312
+	 * as found in the database matching the given query conditions.
1313
+	 *
1314
+	 * @param mixed $current_field_value    Value used for the reference point.
1315
+	 * @param null  $field_to_order_by      What field is used for the
1316
+	 *                                      reference point.
1317
+	 * @param int   $limit                  How many to return.
1318
+	 * @param array $query_params           Extra conditions on the query.
1319
+	 * @param null  $columns_to_select      If left null, then an array of
1320
+	 *                                      EE_Base_Class objects is returned,
1321
+	 *                                      otherwise you can indicate just the
1322
+	 *                                      columns you want returned.
1323
+	 * @return EE_Base_Class[]|array
1324
+	 * @throws EE_Error
1325
+	 */
1326
+	public function previous_x(
1327
+		$current_field_value,
1328
+		$field_to_order_by = null,
1329
+		$limit = 1,
1330
+		$query_params = array(),
1331
+		$columns_to_select = null
1332
+	) {
1333
+		return $this->_get_consecutive(
1334
+			$current_field_value,
1335
+			'<',
1336
+			$field_to_order_by,
1337
+			$limit,
1338
+			$query_params,
1339
+			$columns_to_select
1340
+		);
1341
+	}
1342
+
1343
+
1344
+
1345
+	/**
1346
+	 * Returns the next item in sequence from the given value as found in the
1347
+	 * database matching the given query conditions.
1348
+	 *
1349
+	 * @param mixed $current_field_value    Value used for the reference point.
1350
+	 * @param null  $field_to_order_by      What field is used for the
1351
+	 *                                      reference point.
1352
+	 * @param array $query_params           Extra conditions on the query.
1353
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1354
+	 *                                      object is returned, otherwise you
1355
+	 *                                      can indicate just the columns you
1356
+	 *                                      want and a single array indexed by
1357
+	 *                                      the columns will be returned.
1358
+	 * @return EE_Base_Class|null|array()
1359
+	 * @throws EE_Error
1360
+	 */
1361
+	public function next(
1362
+		$current_field_value,
1363
+		$field_to_order_by = null,
1364
+		$query_params = array(),
1365
+		$columns_to_select = null
1366
+	) {
1367
+		$results = $this->_get_consecutive(
1368
+			$current_field_value,
1369
+			'>',
1370
+			$field_to_order_by,
1371
+			1,
1372
+			$query_params,
1373
+			$columns_to_select
1374
+		);
1375
+		return empty($results) ? null : reset($results);
1376
+	}
1377
+
1378
+
1379
+
1380
+	/**
1381
+	 * Returns the previous item in sequence from the given value as found in
1382
+	 * the database matching the given query conditions.
1383
+	 *
1384
+	 * @param mixed $current_field_value    Value used for the reference point.
1385
+	 * @param null  $field_to_order_by      What field is used for the
1386
+	 *                                      reference point.
1387
+	 * @param array $query_params           Extra conditions on the query.
1388
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1389
+	 *                                      object is returned, otherwise you
1390
+	 *                                      can indicate just the columns you
1391
+	 *                                      want and a single array indexed by
1392
+	 *                                      the columns will be returned.
1393
+	 * @return EE_Base_Class|null|array()
1394
+	 * @throws EE_Error
1395
+	 */
1396
+	public function previous(
1397
+		$current_field_value,
1398
+		$field_to_order_by = null,
1399
+		$query_params = array(),
1400
+		$columns_to_select = null
1401
+	) {
1402
+		$results = $this->_get_consecutive(
1403
+			$current_field_value,
1404
+			'<',
1405
+			$field_to_order_by,
1406
+			1,
1407
+			$query_params,
1408
+			$columns_to_select
1409
+		);
1410
+		return empty($results) ? null : reset($results);
1411
+	}
1412
+
1413
+
1414
+
1415
+	/**
1416
+	 * Returns the a consecutive number of items in sequence from the given
1417
+	 * value as found in the database matching the given query conditions.
1418
+	 *
1419
+	 * @param mixed  $current_field_value   Value used for the reference point.
1420
+	 * @param string $operand               What operand is used for the sequence.
1421
+	 * @param string $field_to_order_by     What field is used for the reference point.
1422
+	 * @param int    $limit                 How many to return.
1423
+	 * @param array  $query_params          Extra conditions on the query.
1424
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1425
+	 *                                      otherwise you can indicate just the columns you want returned.
1426
+	 * @return EE_Base_Class[]|array
1427
+	 * @throws EE_Error
1428
+	 */
1429
+	protected function _get_consecutive(
1430
+		$current_field_value,
1431
+		$operand = '>',
1432
+		$field_to_order_by = null,
1433
+		$limit = 1,
1434
+		$query_params = array(),
1435
+		$columns_to_select = null
1436
+	) {
1437
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1438
+		if (empty($field_to_order_by)) {
1439
+			if ($this->has_primary_key_field()) {
1440
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1441
+			} else {
1442
+				if (WP_DEBUG) {
1443
+					throw new EE_Error(__(
1444
+						'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1445
+						'event_espresso'
1446
+					));
1447
+				}
1448
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1449
+				return array();
1450
+			}
1451
+		}
1452
+		if (! is_array($query_params)) {
1453
+			EE_Error::doing_it_wrong(
1454
+				'EEM_Base::_get_consecutive',
1455
+				sprintf(
1456
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1457
+					gettype($query_params)
1458
+				),
1459
+				'4.6.0'
1460
+			);
1461
+			$query_params = array();
1462
+		}
1463
+		// let's add the where query param for consecutive look up.
1464
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1465
+		$query_params['limit'] = $limit;
1466
+		// set direction
1467
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1468
+		$query_params['order_by'] = $operand === '>'
1469
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1470
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1471
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1472
+		if (empty($columns_to_select)) {
1473
+			return $this->get_all($query_params);
1474
+		}
1475
+		// getting just the fields
1476
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1477
+	}
1478
+
1479
+
1480
+
1481
+	/**
1482
+	 * This sets the _timezone property after model object has been instantiated.
1483
+	 *
1484
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1485
+	 */
1486
+	public function set_timezone($timezone)
1487
+	{
1488
+		if ($timezone !== null) {
1489
+			$this->_timezone = $timezone;
1490
+		}
1491
+		// note we need to loop through relations and set the timezone on those objects as well.
1492
+		foreach ($this->_model_relations as $relation) {
1493
+			$relation->set_timezone($timezone);
1494
+		}
1495
+		// and finally we do the same for any datetime fields
1496
+		foreach ($this->_fields as $field) {
1497
+			if ($field instanceof EE_Datetime_Field) {
1498
+				$field->set_timezone($timezone);
1499
+			}
1500
+		}
1501
+	}
1502
+
1503
+
1504
+
1505
+	/**
1506
+	 * This just returns whatever is set for the current timezone.
1507
+	 *
1508
+	 * @access public
1509
+	 * @return string
1510
+	 */
1511
+	public function get_timezone()
1512
+	{
1513
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1514
+		if (empty($this->_timezone)) {
1515
+			foreach ($this->_fields as $field) {
1516
+				if ($field instanceof EE_Datetime_Field) {
1517
+					$this->set_timezone($field->get_timezone());
1518
+					break;
1519
+				}
1520
+			}
1521
+		}
1522
+		// if timezone STILL empty then return the default timezone for the site.
1523
+		if (empty($this->_timezone)) {
1524
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1525
+		}
1526
+		return $this->_timezone;
1527
+	}
1528
+
1529
+
1530
+
1531
+	/**
1532
+	 * This returns the date formats set for the given field name and also ensures that
1533
+	 * $this->_timezone property is set correctly.
1534
+	 *
1535
+	 * @since 4.6.x
1536
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1537
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1538
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1539
+	 * @return array formats in an array with the date format first, and the time format last.
1540
+	 */
1541
+	public function get_formats_for($field_name, $pretty = false)
1542
+	{
1543
+		$field_settings = $this->field_settings_for($field_name);
1544
+		// if not a valid EE_Datetime_Field then throw error
1545
+		if (! $field_settings instanceof EE_Datetime_Field) {
1546
+			throw new EE_Error(sprintf(__(
1547
+				'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1548
+				'event_espresso'
1549
+			), $field_name));
1550
+		}
1551
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1552
+		// the field.
1553
+		$this->_timezone = $field_settings->get_timezone();
1554
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1555
+	}
1556
+
1557
+
1558
+
1559
+	/**
1560
+	 * This returns the current time in a format setup for a query on this model.
1561
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1562
+	 * it will return:
1563
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1564
+	 *  NOW
1565
+	 *  - or a unix timestamp (equivalent to time())
1566
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1567
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1568
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1569
+	 * @since 4.6.x
1570
+	 * @param string $field_name       The field the current time is needed for.
1571
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1572
+	 *                                 formatted string matching the set format for the field in the set timezone will
1573
+	 *                                 be returned.
1574
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1575
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1576
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1577
+	 *                                 exception is triggered.
1578
+	 */
1579
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1580
+	{
1581
+		$formats = $this->get_formats_for($field_name);
1582
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1583
+		if ($timestamp) {
1584
+			return $DateTime->format('U');
1585
+		}
1586
+		// not returning timestamp, so return formatted string in timezone.
1587
+		switch ($what) {
1588
+			case 'time':
1589
+				return $DateTime->format($formats[1]);
1590
+				break;
1591
+			case 'date':
1592
+				return $DateTime->format($formats[0]);
1593
+				break;
1594
+			default:
1595
+				return $DateTime->format(implode(' ', $formats));
1596
+				break;
1597
+		}
1598
+	}
1599
+
1600
+
1601
+
1602
+	/**
1603
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1604
+	 * for the model are.  Returns a DateTime object.
1605
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1606
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1607
+	 * ignored.
1608
+	 *
1609
+	 * @param string $field_name      The field being setup.
1610
+	 * @param string $timestring      The date time string being used.
1611
+	 * @param string $incoming_format The format for the time string.
1612
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1613
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1614
+	 *                                format is
1615
+	 *                                'U', this is ignored.
1616
+	 * @return DateTime
1617
+	 * @throws EE_Error
1618
+	 */
1619
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1620
+	{
1621
+		// just using this to ensure the timezone is set correctly internally
1622
+		$this->get_formats_for($field_name);
1623
+		// load EEH_DTT_Helper
1624
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1625
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1626
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1627
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1628
+	}
1629
+
1630
+
1631
+
1632
+	/**
1633
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1634
+	 *
1635
+	 * @return EE_Table_Base[]
1636
+	 */
1637
+	public function get_tables()
1638
+	{
1639
+		return $this->_tables;
1640
+	}
1641
+
1642
+
1643
+
1644
+	/**
1645
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1646
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1647
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1648
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1649
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1650
+	 * model object with EVT_ID = 1
1651
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1652
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1653
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1654
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1655
+	 * are not specified)
1656
+	 *
1657
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1658
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1659
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1660
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1661
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1662
+	 *                                         ID=34, we'd use this method as follows:
1663
+	 *                                         EEM_Transaction::instance()->update(
1664
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1665
+	 *                                         array(array('TXN_ID'=>34)));
1666
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1667
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1668
+	 *                                         consider updating Question's QST_admin_label field is of type
1669
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1670
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1671
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1672
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1673
+	 *                                         TRUE, it is assumed that you've already called
1674
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1675
+	 *                                         malicious javascript. However, if
1676
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1677
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1678
+	 *                                         and every other field, before insertion. We provide this parameter
1679
+	 *                                         because model objects perform their prepare_for_set function on all
1680
+	 *                                         their values, and so don't need to be called again (and in many cases,
1681
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1682
+	 *                                         prepare_for_set method...)
1683
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1684
+	 *                                         in this model's entity map according to $fields_n_values that match
1685
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1686
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1687
+	 *                                         could get out-of-sync with the database
1688
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1689
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1690
+	 *                                         bad)
1691
+	 * @throws EE_Error
1692
+	 */
1693
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1694
+	{
1695
+		if (! is_array($query_params)) {
1696
+			EE_Error::doing_it_wrong(
1697
+				'EEM_Base::update',
1698
+				sprintf(
1699
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1700
+					gettype($query_params)
1701
+				),
1702
+				'4.6.0'
1703
+			);
1704
+			$query_params = array();
1705
+		}
1706
+		/**
1707
+		 * Action called before a model update call has been made.
1708
+		 *
1709
+		 * @param EEM_Base $model
1710
+		 * @param array    $fields_n_values the updated fields and their new values
1711
+		 * @param array    $query_params    @see EEM_Base::get_all()
1712
+		 */
1713
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1714
+		/**
1715
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1716
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1717
+		 *
1718
+		 * @param array    $fields_n_values fields and their new values
1719
+		 * @param EEM_Base $model           the model being queried
1720
+		 * @param array    $query_params    see EEM_Base::get_all()
1721
+		 */
1722
+		$fields_n_values = (array) apply_filters(
1723
+			'FHEE__EEM_Base__update__fields_n_values',
1724
+			$fields_n_values,
1725
+			$this,
1726
+			$query_params
1727
+		);
1728
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1729
+		// to do that, for each table, verify that it's PK isn't null.
1730
+		$tables = $this->get_tables();
1731
+		// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1732
+		// NOTE: we should make this code more efficient by NOT querying twice
1733
+		// before the real update, but that needs to first go through ALPHA testing
1734
+		// as it's dangerous. says Mike August 8 2014
1735
+		// we want to make sure the default_where strategy is ignored
1736
+		$this->_ignore_where_strategy = true;
1737
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1738
+		foreach ($wpdb_select_results as $wpdb_result) {
1739
+			// type cast stdClass as array
1740
+			$wpdb_result = (array) $wpdb_result;
1741
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1742
+			if ($this->has_primary_key_field()) {
1743
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1744
+			} else {
1745
+				// if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1746
+				$main_table_pk_value = null;
1747
+			}
1748
+			// if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1749
+			// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1750
+			if (count($tables) > 1) {
1751
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1752
+				// in that table, and so we'll want to insert one
1753
+				foreach ($tables as $table_obj) {
1754
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1755
+					// if there is no private key for this table on the results, it means there's no entry
1756
+					// in this table, right? so insert a row in the current table, using any fields available
1757
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1758
+						   && $wpdb_result[ $this_table_pk_column ])
1759
+					) {
1760
+						$success = $this->_insert_into_specific_table(
1761
+							$table_obj,
1762
+							$fields_n_values,
1763
+							$main_table_pk_value
1764
+						);
1765
+						// if we died here, report the error
1766
+						if (! $success) {
1767
+							return false;
1768
+						}
1769
+					}
1770
+				}
1771
+			}
1772
+			//              //and now check that if we have cached any models by that ID on the model, that
1773
+			//              //they also get updated properly
1774
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1775
+			//              if( $model_object ){
1776
+			//                  foreach( $fields_n_values as $field => $value ){
1777
+			//                      $model_object->set($field, $value);
1778
+			// let's make sure default_where strategy is followed now
1779
+			$this->_ignore_where_strategy = false;
1780
+		}
1781
+		// if we want to keep model objects in sync, AND
1782
+		// if this wasn't called from a model object (to update itself)
1783
+		// then we want to make sure we keep all the existing
1784
+		// model objects in sync with the db
1785
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1786
+			if ($this->has_primary_key_field()) {
1787
+				$model_objs_affected_ids = $this->get_col($query_params);
1788
+			} else {
1789
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1790
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1791
+				$model_objs_affected_ids = array();
1792
+				foreach ($models_affected_key_columns as $row) {
1793
+					$combined_index_key = $this->get_index_primary_key_string($row);
1794
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1795
+				}
1796
+			}
1797
+			if (! $model_objs_affected_ids) {
1798
+				// wait wait wait- if nothing was affected let's stop here
1799
+				return 0;
1800
+			}
1801
+			foreach ($model_objs_affected_ids as $id) {
1802
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1803
+				if ($model_obj_in_entity_map) {
1804
+					foreach ($fields_n_values as $field => $new_value) {
1805
+						$model_obj_in_entity_map->set($field, $new_value);
1806
+					}
1807
+				}
1808
+			}
1809
+			// if there is a primary key on this model, we can now do a slight optimization
1810
+			if ($this->has_primary_key_field()) {
1811
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1812
+				$query_params = array(
1813
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1814
+					'limit'                    => count($model_objs_affected_ids),
1815
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1816
+				);
1817
+			}
1818
+		}
1819
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1820
+		$SQL = "UPDATE "
1821
+			   . $model_query_info->get_full_join_sql()
1822
+			   . " SET "
1823
+			   . $this->_construct_update_sql($fields_n_values)
1824
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1825
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1826
+		/**
1827
+		 * Action called after a model update call has been made.
1828
+		 *
1829
+		 * @param EEM_Base $model
1830
+		 * @param array    $fields_n_values the updated fields and their new values
1831
+		 * @param array    $query_params    @see EEM_Base::get_all()
1832
+		 * @param int      $rows_affected
1833
+		 */
1834
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1835
+		return $rows_affected;// how many supposedly got updated
1836
+	}
1837
+
1838
+
1839
+
1840
+	/**
1841
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1842
+	 * are teh values of the field specified (or by default the primary key field)
1843
+	 * that matched the query params. Note that you should pass the name of the
1844
+	 * model FIELD, not the database table's column name.
1845
+	 *
1846
+	 * @param array  $query_params @see EEM_Base::get_all()
1847
+	 * @param string $field_to_select
1848
+	 * @return array just like $wpdb->get_col()
1849
+	 * @throws EE_Error
1850
+	 */
1851
+	public function get_col($query_params = array(), $field_to_select = null)
1852
+	{
1853
+		if ($field_to_select) {
1854
+			$field = $this->field_settings_for($field_to_select);
1855
+		} elseif ($this->has_primary_key_field()) {
1856
+			$field = $this->get_primary_key_field();
1857
+		} else {
1858
+			// no primary key, just grab the first column
1859
+			$field = reset($this->field_settings());
1860
+		}
1861
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1862
+		$select_expressions = $field->get_qualified_column();
1863
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1864
+		return $this->_do_wpdb_query('get_col', array($SQL));
1865
+	}
1866
+
1867
+
1868
+
1869
+	/**
1870
+	 * Returns a single column value for a single row from the database
1871
+	 *
1872
+	 * @param array  $query_params    @see EEM_Base::get_all()
1873
+	 * @param string $field_to_select @see EEM_Base::get_col()
1874
+	 * @return string
1875
+	 * @throws EE_Error
1876
+	 */
1877
+	public function get_var($query_params = array(), $field_to_select = null)
1878
+	{
1879
+		$query_params['limit'] = 1;
1880
+		$col = $this->get_col($query_params, $field_to_select);
1881
+		if (! empty($col)) {
1882
+			return reset($col);
1883
+		}
1884
+		return null;
1885
+	}
1886
+
1887
+
1888
+
1889
+	/**
1890
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1891
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1892
+	 * injection, but currently no further filtering is done
1893
+	 *
1894
+	 * @global      $wpdb
1895
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1896
+	 *                               be updated to in the DB
1897
+	 * @return string of SQL
1898
+	 * @throws EE_Error
1899
+	 */
1900
+	public function _construct_update_sql($fields_n_values)
1901
+	{
1902
+		/** @type WPDB $wpdb */
1903
+		global $wpdb;
1904
+		$cols_n_values = array();
1905
+		foreach ($fields_n_values as $field_name => $value) {
1906
+			$field_obj = $this->field_settings_for($field_name);
1907
+			// if the value is NULL, we want to assign the value to that.
1908
+			// wpdb->prepare doesn't really handle that properly
1909
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1910
+			$value_sql = $prepared_value === null ? 'NULL'
1911
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1912
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1913
+		}
1914
+		return implode(",", $cols_n_values);
1915
+	}
1916
+
1917
+
1918
+
1919
+	/**
1920
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1921
+	 * Performs a HARD delete, meaning the database row should always be removed,
1922
+	 * not just have a flag field on it switched
1923
+	 * Wrapper for EEM_Base::delete_permanently()
1924
+	 *
1925
+	 * @param mixed $id
1926
+	 * @param boolean $allow_blocking
1927
+	 * @return int the number of rows deleted
1928
+	 * @throws EE_Error
1929
+	 */
1930
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1931
+	{
1932
+		return $this->delete_permanently(
1933
+			array(
1934
+				array($this->get_primary_key_field()->get_name() => $id),
1935
+				'limit' => 1,
1936
+			),
1937
+			$allow_blocking
1938
+		);
1939
+	}
1940
+
1941
+
1942
+
1943
+	/**
1944
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1945
+	 * Wrapper for EEM_Base::delete()
1946
+	 *
1947
+	 * @param mixed $id
1948
+	 * @param boolean $allow_blocking
1949
+	 * @return int the number of rows deleted
1950
+	 * @throws EE_Error
1951
+	 */
1952
+	public function delete_by_ID($id, $allow_blocking = true)
1953
+	{
1954
+		return $this->delete(
1955
+			array(
1956
+				array($this->get_primary_key_field()->get_name() => $id),
1957
+				'limit' => 1,
1958
+			),
1959
+			$allow_blocking
1960
+		);
1961
+	}
1962
+
1963
+
1964
+
1965
+	/**
1966
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1967
+	 * meaning if the model has a field that indicates its been "trashed" or
1968
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1969
+	 *
1970
+	 * @see EEM_Base::delete_permanently
1971
+	 * @param array   $query_params
1972
+	 * @param boolean $allow_blocking
1973
+	 * @return int how many rows got deleted
1974
+	 * @throws EE_Error
1975
+	 */
1976
+	public function delete($query_params, $allow_blocking = true)
1977
+	{
1978
+		return $this->delete_permanently($query_params, $allow_blocking);
1979
+	}
1980
+
1981
+
1982
+
1983
+	/**
1984
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1985
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1986
+	 * as archived, not actually deleted
1987
+	 *
1988
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1989
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1990
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1991
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1992
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1993
+	 *                                DB
1994
+	 * @return int how many rows got deleted
1995
+	 * @throws EE_Error
1996
+	 */
1997
+	public function delete_permanently($query_params, $allow_blocking = true)
1998
+	{
1999
+		/**
2000
+		 * Action called just before performing a real deletion query. You can use the
2001
+		 * model and its $query_params to find exactly which items will be deleted
2002
+		 *
2003
+		 * @param EEM_Base $model
2004
+		 * @param array    $query_params   @see EEM_Base::get_all()
2005
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
2006
+		 *                                 to block (prevent) this deletion
2007
+		 */
2008
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
2009
+		// some MySQL databases may be running safe mode, which may restrict
2010
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
2011
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
2012
+		// to delete them
2013
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
2014
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2015
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
2016
+			$columns_and_ids_for_deleting
2017
+		);
2018
+		/**
2019
+		 * Allows client code to act on the items being deleted before the query is actually executed.
2020
+		 *
2021
+		 * @param EEM_Base $this  The model instance being acted on.
2022
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2023
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
2024
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
2025
+		 *                                                  derived from the incoming query parameters.
2026
+		 *                                                  @see details on the structure of this array in the phpdocs
2027
+		 *                                                  for the `_get_ids_for_delete_method`
2028
+		 *
2029
+		 */
2030
+		do_action(
2031
+			'AHEE__EEM_Base__delete__before_query',
2032
+			$this,
2033
+			$query_params,
2034
+			$allow_blocking,
2035
+			$columns_and_ids_for_deleting
2036
+		);
2037
+		if ($deletion_where_query_part) {
2038
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2039
+			$table_aliases = array_keys($this->_tables);
2040
+			$SQL = "DELETE "
2041
+				   . implode(", ", $table_aliases)
2042
+				   . " FROM "
2043
+				   . $model_query_info->get_full_join_sql()
2044
+				   . " WHERE "
2045
+				   . $deletion_where_query_part;
2046
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2047
+		} else {
2048
+			$rows_deleted = 0;
2049
+		}
2050
+
2051
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2052
+		// there was no error with the delete query.
2053
+		if ($this->has_primary_key_field()
2054
+			&& $rows_deleted !== false
2055
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2056
+		) {
2057
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2058
+			foreach ($ids_for_removal as $id) {
2059
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2060
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2061
+				}
2062
+			}
2063
+
2064
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2065
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2066
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2067
+			// (although it is possible).
2068
+			// Note this can be skipped by using the provided filter and returning false.
2069
+			if (apply_filters(
2070
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2071
+				! $this instanceof EEM_Extra_Meta,
2072
+				$this
2073
+			)) {
2074
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2075
+					0 => array(
2076
+						'EXM_type' => $this->get_this_model_name(),
2077
+						'OBJ_ID'   => array(
2078
+							'IN',
2079
+							$ids_for_removal
2080
+						)
2081
+					)
2082
+				));
2083
+			}
2084
+		}
2085
+
2086
+		/**
2087
+		 * Action called just after performing a real deletion query. Although at this point the
2088
+		 * items should have been deleted
2089
+		 *
2090
+		 * @param EEM_Base $model
2091
+		 * @param array    $query_params @see EEM_Base::get_all()
2092
+		 * @param int      $rows_deleted
2093
+		 */
2094
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2095
+		return $rows_deleted;// how many supposedly got deleted
2096
+	}
2097
+
2098
+
2099
+
2100
+	/**
2101
+	 * Checks all the relations that throw error messages when there are blocking related objects
2102
+	 * for related model objects. If there are any related model objects on those relations,
2103
+	 * adds an EE_Error, and return true
2104
+	 *
2105
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2106
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2107
+	 *                                                 should be ignored when determining whether there are related
2108
+	 *                                                 model objects which block this model object's deletion. Useful
2109
+	 *                                                 if you know A is related to B and are considering deleting A,
2110
+	 *                                                 but want to see if A has any other objects blocking its deletion
2111
+	 *                                                 before removing the relation between A and B
2112
+	 * @return boolean
2113
+	 * @throws EE_Error
2114
+	 */
2115
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2116
+	{
2117
+		// first, if $ignore_this_model_obj was supplied, get its model
2118
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2119
+			$ignored_model = $ignore_this_model_obj->get_model();
2120
+		} else {
2121
+			$ignored_model = null;
2122
+		}
2123
+		// now check all the relations of $this_model_obj_or_id and see if there
2124
+		// are any related model objects blocking it?
2125
+		$is_blocked = false;
2126
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2127
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2128
+				// if $ignore_this_model_obj was supplied, then for the query
2129
+				// on that model needs to be told to ignore $ignore_this_model_obj
2130
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2131
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2132
+						array(
2133
+							$ignored_model->get_primary_key_field()->get_name() => array(
2134
+								'!=',
2135
+								$ignore_this_model_obj->ID(),
2136
+							),
2137
+						),
2138
+					));
2139
+				} else {
2140
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2141
+				}
2142
+				if ($related_model_objects) {
2143
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2144
+					$is_blocked = true;
2145
+				}
2146
+			}
2147
+		}
2148
+		return $is_blocked;
2149
+	}
2150
+
2151
+
2152
+	/**
2153
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2154
+	 * @param array $row_results_for_deleting
2155
+	 * @param bool  $allow_blocking
2156
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2157
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2158
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2159
+	 *                 deleted. Example:
2160
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2161
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2162
+	 *                 where each element is a group of columns and values that get deleted. Example:
2163
+	 *                      array(
2164
+	 *                          0 => array(
2165
+	 *                              'Term_Relationship.object_id' => 1
2166
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2167
+	 *                          ),
2168
+	 *                          1 => array(
2169
+	 *                              'Term_Relationship.object_id' => 1
2170
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2171
+	 *                          )
2172
+	 *                      )
2173
+	 * @throws EE_Error
2174
+	 */
2175
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2176
+	{
2177
+		$ids_to_delete_indexed_by_column = array();
2178
+		if ($this->has_primary_key_field()) {
2179
+			$primary_table = $this->_get_main_table();
2180
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2181
+			$other_tables = $this->_get_other_tables();
2182
+			$ids_to_delete_indexed_by_column = $query = array();
2183
+			foreach ($row_results_for_deleting as $item_to_delete) {
2184
+				// before we mark this item for deletion,
2185
+				// make sure there's no related entities blocking its deletion (if we're checking)
2186
+				if ($allow_blocking
2187
+					&& $this->delete_is_blocked_by_related_models(
2188
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2189
+					)
2190
+				) {
2191
+					continue;
2192
+				}
2193
+				// primary table deletes
2194
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2195
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2196
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2197
+				}
2198
+			}
2199
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2200
+			$fields = $this->get_combined_primary_key_fields();
2201
+			foreach ($row_results_for_deleting as $item_to_delete) {
2202
+				$ids_to_delete_indexed_by_column_for_row = array();
2203
+				foreach ($fields as $cpk_field) {
2204
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2205
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2206
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2207
+					}
2208
+				}
2209
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2210
+			}
2211
+		} else {
2212
+			// so there's no primary key and no combined key...
2213
+			// sorry, can't help you
2214
+			throw new EE_Error(
2215
+				sprintf(
2216
+					__(
2217
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2218
+						"event_espresso"
2219
+					),
2220
+					get_class($this)
2221
+				)
2222
+			);
2223
+		}
2224
+		return $ids_to_delete_indexed_by_column;
2225
+	}
2226
+
2227
+
2228
+	/**
2229
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2230
+	 * the corresponding query_part for the query performing the delete.
2231
+	 *
2232
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2233
+	 * @return string
2234
+	 * @throws EE_Error
2235
+	 */
2236
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2237
+	{
2238
+		$query_part = '';
2239
+		if (empty($ids_to_delete_indexed_by_column)) {
2240
+			return $query_part;
2241
+		} elseif ($this->has_primary_key_field()) {
2242
+			$query = array();
2243
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2244
+				// make sure we have unique $ids
2245
+				$ids = array_unique($ids);
2246
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2247
+			}
2248
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2249
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2250
+			$ways_to_identify_a_row = array();
2251
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2252
+				$values_for_each_combined_primary_key_for_a_row = array();
2253
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2254
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2255
+				}
2256
+				$ways_to_identify_a_row[] = '('
2257
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2258
+											. ')';
2259
+			}
2260
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2261
+		}
2262
+		return $query_part;
2263
+	}
2264
+
2265
+
2266
+
2267
+	/**
2268
+	 * Gets the model field by the fully qualified name
2269
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2270
+	 * @return EE_Model_Field_Base
2271
+	 */
2272
+	public function get_field_by_column($qualified_column_name)
2273
+	{
2274
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2275
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2276
+				return $field_obj;
2277
+			}
2278
+		}
2279
+		throw new EE_Error(
2280
+			sprintf(
2281
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2282
+				$this->get_this_model_name(),
2283
+				$qualified_column_name
2284
+			)
2285
+		);
2286
+	}
2287
+
2288
+
2289
+
2290
+	/**
2291
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2292
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2293
+	 * column
2294
+	 *
2295
+	 * @param array  $query_params   like EEM_Base::get_all's
2296
+	 * @param string $field_to_count field on model to count by (not column name)
2297
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2298
+	 *                               that by the setting $distinct to TRUE;
2299
+	 * @return int
2300
+	 * @throws EE_Error
2301
+	 */
2302
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2303
+	{
2304
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2305
+		if ($field_to_count) {
2306
+			$field_obj = $this->field_settings_for($field_to_count);
2307
+			$column_to_count = $field_obj->get_qualified_column();
2308
+		} elseif ($this->has_primary_key_field()) {
2309
+			$pk_field_obj = $this->get_primary_key_field();
2310
+			$column_to_count = $pk_field_obj->get_qualified_column();
2311
+		} else {
2312
+			// there's no primary key
2313
+			// if we're counting distinct items, and there's no primary key,
2314
+			// we need to list out the columns for distinction;
2315
+			// otherwise we can just use star
2316
+			if ($distinct) {
2317
+				$columns_to_use = array();
2318
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2319
+					$columns_to_use[] = $field_obj->get_qualified_column();
2320
+				}
2321
+				$column_to_count = implode(',', $columns_to_use);
2322
+			} else {
2323
+				$column_to_count = '*';
2324
+			}
2325
+		}
2326
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2327
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2328
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2329
+	}
2330
+
2331
+
2332
+
2333
+	/**
2334
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2335
+	 *
2336
+	 * @param array  $query_params like EEM_Base::get_all
2337
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2338
+	 * @return float
2339
+	 * @throws EE_Error
2340
+	 */
2341
+	public function sum($query_params, $field_to_sum = null)
2342
+	{
2343
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2344
+		if ($field_to_sum) {
2345
+			$field_obj = $this->field_settings_for($field_to_sum);
2346
+		} else {
2347
+			$field_obj = $this->get_primary_key_field();
2348
+		}
2349
+		$column_to_count = $field_obj->get_qualified_column();
2350
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2351
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2352
+		$data_type = $field_obj->get_wpdb_data_type();
2353
+		if ($data_type === '%d' || $data_type === '%s') {
2354
+			return (float) $return_value;
2355
+		}
2356
+		// must be %f
2357
+		return (float) $return_value;
2358
+	}
2359
+
2360
+
2361
+
2362
+	/**
2363
+	 * Just calls the specified method on $wpdb with the given arguments
2364
+	 * Consolidates a little extra error handling code
2365
+	 *
2366
+	 * @param string $wpdb_method
2367
+	 * @param array  $arguments_to_provide
2368
+	 * @throws EE_Error
2369
+	 * @global wpdb  $wpdb
2370
+	 * @return mixed
2371
+	 */
2372
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2373
+	{
2374
+		// if we're in maintenance mode level 2, DON'T run any queries
2375
+		// because level 2 indicates the database needs updating and
2376
+		// is probably out of sync with the code
2377
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2378
+			throw new EE_Error(sprintf(__(
2379
+				"Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2380
+				"event_espresso"
2381
+			)));
2382
+		}
2383
+		/** @type WPDB $wpdb */
2384
+		global $wpdb;
2385
+		if (! method_exists($wpdb, $wpdb_method)) {
2386
+			throw new EE_Error(sprintf(__(
2387
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2388
+				'event_espresso'
2389
+			), $wpdb_method));
2390
+		}
2391
+		if (WP_DEBUG) {
2392
+			$old_show_errors_value = $wpdb->show_errors;
2393
+			$wpdb->show_errors(false);
2394
+		}
2395
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2396
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2397
+		if (WP_DEBUG) {
2398
+			$wpdb->show_errors($old_show_errors_value);
2399
+			if (! empty($wpdb->last_error)) {
2400
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2401
+			}
2402
+			if ($result === false) {
2403
+				throw new EE_Error(sprintf(__(
2404
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2405
+					'event_espresso'
2406
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2407
+			}
2408
+		} elseif ($result === false) {
2409
+			EE_Error::add_error(
2410
+				sprintf(
2411
+					__(
2412
+						'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2413
+						'event_espresso'
2414
+					),
2415
+					$wpdb_method,
2416
+					var_export($arguments_to_provide, true),
2417
+					$wpdb->last_error
2418
+				),
2419
+				__FILE__,
2420
+				__FUNCTION__,
2421
+				__LINE__
2422
+			);
2423
+		}
2424
+		return $result;
2425
+	}
2426
+
2427
+
2428
+
2429
+	/**
2430
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2431
+	 * and if there's an error tries to verify the DB is correct. Uses
2432
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2433
+	 * we should try to fix the EE core db, the addons, or just give up
2434
+	 *
2435
+	 * @param string $wpdb_method
2436
+	 * @param array  $arguments_to_provide
2437
+	 * @return mixed
2438
+	 */
2439
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2440
+	{
2441
+		/** @type WPDB $wpdb */
2442
+		global $wpdb;
2443
+		$wpdb->last_error = null;
2444
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2445
+		// was there an error running the query? but we don't care on new activations
2446
+		// (we're going to setup the DB anyway on new activations)
2447
+		if (($result === false || ! empty($wpdb->last_error))
2448
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2449
+		) {
2450
+			switch (EEM_Base::$_db_verification_level) {
2451
+				case EEM_Base::db_verified_none:
2452
+					// let's double-check core's DB
2453
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2454
+					break;
2455
+				case EEM_Base::db_verified_core:
2456
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2457
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2458
+					break;
2459
+				case EEM_Base::db_verified_addons:
2460
+					// ummmm... you in trouble
2461
+					return $result;
2462
+					break;
2463
+			}
2464
+			if (! empty($error_message)) {
2465
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2466
+				trigger_error($error_message);
2467
+			}
2468
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2469
+		}
2470
+		return $result;
2471
+	}
2472
+
2473
+
2474
+
2475
+	/**
2476
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2477
+	 * EEM_Base::$_db_verification_level
2478
+	 *
2479
+	 * @param string $wpdb_method
2480
+	 * @param array  $arguments_to_provide
2481
+	 * @return string
2482
+	 */
2483
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2484
+	{
2485
+		/** @type WPDB $wpdb */
2486
+		global $wpdb;
2487
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2488
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2489
+		$error_message = sprintf(
2490
+			__(
2491
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2492
+				'event_espresso'
2493
+			),
2494
+			$wpdb->last_error,
2495
+			$wpdb_method,
2496
+			wp_json_encode($arguments_to_provide)
2497
+		);
2498
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2499
+		return $error_message;
2500
+	}
2501
+
2502
+
2503
+
2504
+	/**
2505
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2506
+	 * EEM_Base::$_db_verification_level
2507
+	 *
2508
+	 * @param $wpdb_method
2509
+	 * @param $arguments_to_provide
2510
+	 * @return string
2511
+	 */
2512
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2513
+	{
2514
+		/** @type WPDB $wpdb */
2515
+		global $wpdb;
2516
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2517
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2518
+		$error_message = sprintf(
2519
+			__(
2520
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2521
+				'event_espresso'
2522
+			),
2523
+			$wpdb->last_error,
2524
+			$wpdb_method,
2525
+			wp_json_encode($arguments_to_provide)
2526
+		);
2527
+		EE_System::instance()->initialize_addons();
2528
+		return $error_message;
2529
+	}
2530
+
2531
+
2532
+
2533
+	/**
2534
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2535
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2536
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2537
+	 * ..."
2538
+	 *
2539
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2540
+	 * @return string
2541
+	 */
2542
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2543
+	{
2544
+		return " FROM " . $model_query_info->get_full_join_sql() .
2545
+			   $model_query_info->get_where_sql() .
2546
+			   $model_query_info->get_group_by_sql() .
2547
+			   $model_query_info->get_having_sql() .
2548
+			   $model_query_info->get_order_by_sql() .
2549
+			   $model_query_info->get_limit_sql();
2550
+	}
2551
+
2552
+
2553
+
2554
+	/**
2555
+	 * Set to easily debug the next X queries ran from this model.
2556
+	 *
2557
+	 * @param int $count
2558
+	 */
2559
+	public function show_next_x_db_queries($count = 1)
2560
+	{
2561
+		$this->_show_next_x_db_queries = $count;
2562
+	}
2563
+
2564
+
2565
+
2566
+	/**
2567
+	 * @param $sql_query
2568
+	 */
2569
+	public function show_db_query_if_previously_requested($sql_query)
2570
+	{
2571
+		if ($this->_show_next_x_db_queries > 0) {
2572
+			echo $sql_query;
2573
+			$this->_show_next_x_db_queries--;
2574
+		}
2575
+	}
2576
+
2577
+
2578
+
2579
+	/**
2580
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2581
+	 * There are the 3 cases:
2582
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2583
+	 * $otherModelObject has no ID, it is first saved.
2584
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2585
+	 * has no ID, it is first saved.
2586
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2587
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2588
+	 * join table
2589
+	 *
2590
+	 * @param        EE_Base_Class                     /int $thisModelObject
2591
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2592
+	 * @param string $relationName                     , key in EEM_Base::_relations
2593
+	 *                                                 an attendee to a group, you also want to specify which role they
2594
+	 *                                                 will have in that group. So you would use this parameter to
2595
+	 *                                                 specify array('role-column-name'=>'role-id')
2596
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2597
+	 *                                                 to for relation to methods that allow you to further specify
2598
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2599
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2600
+	 *                                                 because these will be inserted in any new rows created as well.
2601
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2602
+	 * @throws EE_Error
2603
+	 */
2604
+	public function add_relationship_to(
2605
+		$id_or_obj,
2606
+		$other_model_id_or_obj,
2607
+		$relationName,
2608
+		$extra_join_model_fields_n_values = array()
2609
+	) {
2610
+		$relation_obj = $this->related_settings_for($relationName);
2611
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2612
+	}
2613
+
2614
+
2615
+
2616
+	/**
2617
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2618
+	 * There are the 3 cases:
2619
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2620
+	 * error
2621
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2622
+	 * an error
2623
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2624
+	 *
2625
+	 * @param        EE_Base_Class /int $id_or_obj
2626
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2627
+	 * @param string $relationName key in EEM_Base::_relations
2628
+	 * @return boolean of success
2629
+	 * @throws EE_Error
2630
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2631
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2632
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2633
+	 *                             because these will be inserted in any new rows created as well.
2634
+	 */
2635
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2636
+	{
2637
+		$relation_obj = $this->related_settings_for($relationName);
2638
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2639
+	}
2640
+
2641
+
2642
+
2643
+	/**
2644
+	 * @param mixed           $id_or_obj
2645
+	 * @param string          $relationName
2646
+	 * @param array           $where_query_params
2647
+	 * @param EE_Base_Class[] objects to which relations were removed
2648
+	 * @return \EE_Base_Class[]
2649
+	 * @throws EE_Error
2650
+	 */
2651
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2652
+	{
2653
+		$relation_obj = $this->related_settings_for($relationName);
2654
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2655
+	}
2656
+
2657
+
2658
+
2659
+	/**
2660
+	 * Gets all the related items of the specified $model_name, using $query_params.
2661
+	 * Note: by default, we remove the "default query params"
2662
+	 * because we want to get even deleted items etc.
2663
+	 *
2664
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2665
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2666
+	 * @param array  $query_params like EEM_Base::get_all
2667
+	 * @return EE_Base_Class[]
2668
+	 * @throws EE_Error
2669
+	 */
2670
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2671
+	{
2672
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2673
+		$relation_settings = $this->related_settings_for($model_name);
2674
+		return $relation_settings->get_all_related($model_obj, $query_params);
2675
+	}
2676
+
2677
+
2678
+
2679
+	/**
2680
+	 * Deletes all the model objects across the relation indicated by $model_name
2681
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2682
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2683
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2684
+	 *
2685
+	 * @param EE_Base_Class|int|string $id_or_obj
2686
+	 * @param string                   $model_name
2687
+	 * @param array                    $query_params
2688
+	 * @return int how many deleted
2689
+	 * @throws EE_Error
2690
+	 */
2691
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2692
+	{
2693
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2694
+		$relation_settings = $this->related_settings_for($model_name);
2695
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2696
+	}
2697
+
2698
+
2699
+
2700
+	/**
2701
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2702
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2703
+	 * the model objects can't be hard deleted because of blocking related model objects,
2704
+	 * just does a soft-delete on them instead.
2705
+	 *
2706
+	 * @param EE_Base_Class|int|string $id_or_obj
2707
+	 * @param string                   $model_name
2708
+	 * @param array                    $query_params
2709
+	 * @return int how many deleted
2710
+	 * @throws EE_Error
2711
+	 */
2712
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2713
+	{
2714
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2715
+		$relation_settings = $this->related_settings_for($model_name);
2716
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2717
+	}
2718
+
2719
+
2720
+
2721
+	/**
2722
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2723
+	 * unless otherwise specified in the $query_params
2724
+	 *
2725
+	 * @param        int             /EE_Base_Class $id_or_obj
2726
+	 * @param string $model_name     like 'Event', or 'Registration'
2727
+	 * @param array  $query_params   like EEM_Base::get_all's
2728
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2729
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2730
+	 *                               that by the setting $distinct to TRUE;
2731
+	 * @return int
2732
+	 * @throws EE_Error
2733
+	 */
2734
+	public function count_related(
2735
+		$id_or_obj,
2736
+		$model_name,
2737
+		$query_params = array(),
2738
+		$field_to_count = null,
2739
+		$distinct = false
2740
+	) {
2741
+		$related_model = $this->get_related_model_obj($model_name);
2742
+		// we're just going to use the query params on the related model's normal get_all query,
2743
+		// except add a condition to say to match the current mod
2744
+		if (! isset($query_params['default_where_conditions'])) {
2745
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2746
+		}
2747
+		$this_model_name = $this->get_this_model_name();
2748
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2749
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2750
+		return $related_model->count($query_params, $field_to_count, $distinct);
2751
+	}
2752
+
2753
+
2754
+
2755
+	/**
2756
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2757
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2758
+	 *
2759
+	 * @param        int           /EE_Base_Class $id_or_obj
2760
+	 * @param string $model_name   like 'Event', or 'Registration'
2761
+	 * @param array  $query_params like EEM_Base::get_all's
2762
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2763
+	 * @return float
2764
+	 * @throws EE_Error
2765
+	 */
2766
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2767
+	{
2768
+		$related_model = $this->get_related_model_obj($model_name);
2769
+		if (! is_array($query_params)) {
2770
+			EE_Error::doing_it_wrong(
2771
+				'EEM_Base::sum_related',
2772
+				sprintf(
2773
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2774
+					gettype($query_params)
2775
+				),
2776
+				'4.6.0'
2777
+			);
2778
+			$query_params = array();
2779
+		}
2780
+		// we're just going to use the query params on the related model's normal get_all query,
2781
+		// except add a condition to say to match the current mod
2782
+		if (! isset($query_params['default_where_conditions'])) {
2783
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2784
+		}
2785
+		$this_model_name = $this->get_this_model_name();
2786
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2787
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2788
+		return $related_model->sum($query_params, $field_to_sum);
2789
+	}
2790
+
2791
+
2792
+
2793
+	/**
2794
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2795
+	 * $modelObject
2796
+	 *
2797
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2798
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2799
+	 * @param array               $query_params     like EEM_Base::get_all's
2800
+	 * @return EE_Base_Class
2801
+	 * @throws EE_Error
2802
+	 */
2803
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2804
+	{
2805
+		$query_params['limit'] = 1;
2806
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2807
+		if ($results) {
2808
+			return array_shift($results);
2809
+		}
2810
+		return null;
2811
+	}
2812
+
2813
+
2814
+
2815
+	/**
2816
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2817
+	 *
2818
+	 * @return string
2819
+	 */
2820
+	public function get_this_model_name()
2821
+	{
2822
+		return str_replace("EEM_", "", get_class($this));
2823
+	}
2824
+
2825
+
2826
+
2827
+	/**
2828
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2829
+	 *
2830
+	 * @return EE_Any_Foreign_Model_Name_Field
2831
+	 * @throws EE_Error
2832
+	 */
2833
+	public function get_field_containing_related_model_name()
2834
+	{
2835
+		foreach ($this->field_settings(true) as $field) {
2836
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2837
+				$field_with_model_name = $field;
2838
+			}
2839
+		}
2840
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2841
+			throw new EE_Error(sprintf(
2842
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2843
+				$this->get_this_model_name()
2844
+			));
2845
+		}
2846
+		return $field_with_model_name;
2847
+	}
2848
+
2849
+
2850
+
2851
+	/**
2852
+	 * Inserts a new entry into the database, for each table.
2853
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2854
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2855
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2856
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2857
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2858
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2859
+	 *
2860
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2861
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2862
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2863
+	 *                              of EEM_Base)
2864
+	 * @return int new primary key on main table that got inserted
2865
+	 * @throws EE_Error
2866
+	 */
2867
+	public function insert($field_n_values)
2868
+	{
2869
+		/**
2870
+		 * Filters the fields and their values before inserting an item using the models
2871
+		 *
2872
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2873
+		 * @param EEM_Base $model           the model used
2874
+		 */
2875
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2876
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2877
+			$main_table = $this->_get_main_table();
2878
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2879
+			if ($new_id !== false) {
2880
+				foreach ($this->_get_other_tables() as $other_table) {
2881
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2882
+				}
2883
+			}
2884
+			/**
2885
+			 * Done just after attempting to insert a new model object
2886
+			 *
2887
+			 * @param EEM_Base   $model           used
2888
+			 * @param array      $fields_n_values fields and their values
2889
+			 * @param int|string the              ID of the newly-inserted model object
2890
+			 */
2891
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2892
+			return $new_id;
2893
+		}
2894
+		return false;
2895
+	}
2896
+
2897
+
2898
+
2899
+	/**
2900
+	 * Checks that the result would satisfy the unique indexes on this model
2901
+	 *
2902
+	 * @param array  $field_n_values
2903
+	 * @param string $action
2904
+	 * @return boolean
2905
+	 * @throws EE_Error
2906
+	 */
2907
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2908
+	{
2909
+		foreach ($this->unique_indexes() as $index_name => $index) {
2910
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2911
+			if ($this->exists(array($uniqueness_where_params))) {
2912
+				EE_Error::add_error(
2913
+					sprintf(
2914
+						__(
2915
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2916
+							"event_espresso"
2917
+						),
2918
+						$action,
2919
+						$this->_get_class_name(),
2920
+						$index_name,
2921
+						implode(",", $index->field_names()),
2922
+						http_build_query($uniqueness_where_params)
2923
+					),
2924
+					__FILE__,
2925
+					__FUNCTION__,
2926
+					__LINE__
2927
+				);
2928
+				return false;
2929
+			}
2930
+		}
2931
+		return true;
2932
+	}
2933
+
2934
+
2935
+
2936
+	/**
2937
+	 * Checks the database for an item that conflicts (ie, if this item were
2938
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2939
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2940
+	 * can be either an EE_Base_Class or an array of fields n values
2941
+	 *
2942
+	 * @param EE_Base_Class|array $obj_or_fields_array
2943
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2944
+	 *                                                 when looking for conflicts
2945
+	 *                                                 (ie, if false, we ignore the model object's primary key
2946
+	 *                                                 when finding "conflicts". If true, it's also considered).
2947
+	 *                                                 Only works for INT primary key,
2948
+	 *                                                 STRING primary keys cannot be ignored
2949
+	 * @throws EE_Error
2950
+	 * @return EE_Base_Class|array
2951
+	 */
2952
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2953
+	{
2954
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2955
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2956
+		} elseif (is_array($obj_or_fields_array)) {
2957
+			$fields_n_values = $obj_or_fields_array;
2958
+		} else {
2959
+			throw new EE_Error(
2960
+				sprintf(
2961
+					__(
2962
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2963
+						"event_espresso"
2964
+					),
2965
+					get_class($this),
2966
+					$obj_or_fields_array
2967
+				)
2968
+			);
2969
+		}
2970
+		$query_params = array();
2971
+		if ($this->has_primary_key_field()
2972
+			&& ($include_primary_key
2973
+				|| $this->get_primary_key_field()
2974
+				   instanceof
2975
+				   EE_Primary_Key_String_Field)
2976
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2977
+		) {
2978
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2979
+		}
2980
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2981
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2982
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2983
+		}
2984
+		// if there is nothing to base this search on, then we shouldn't find anything
2985
+		if (empty($query_params)) {
2986
+			return array();
2987
+		}
2988
+		return $this->get_one($query_params);
2989
+	}
2990
+
2991
+
2992
+
2993
+	/**
2994
+	 * Like count, but is optimized and returns a boolean instead of an int
2995
+	 *
2996
+	 * @param array $query_params
2997
+	 * @return boolean
2998
+	 * @throws EE_Error
2999
+	 */
3000
+	public function exists($query_params)
3001
+	{
3002
+		$query_params['limit'] = 1;
3003
+		return $this->count($query_params) > 0;
3004
+	}
3005
+
3006
+
3007
+
3008
+	/**
3009
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
3010
+	 *
3011
+	 * @param int|string $id
3012
+	 * @return boolean
3013
+	 * @throws EE_Error
3014
+	 */
3015
+	public function exists_by_ID($id)
3016
+	{
3017
+		return $this->exists(
3018
+			array(
3019
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3020
+				array(
3021
+					$this->primary_key_name() => $id,
3022
+				),
3023
+			)
3024
+		);
3025
+	}
3026
+
3027
+
3028
+
3029
+	/**
3030
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3031
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3032
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3033
+	 * on the main table)
3034
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3035
+	 * cases where we want to call it directly rather than via insert().
3036
+	 *
3037
+	 * @access   protected
3038
+	 * @param EE_Table_Base $table
3039
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3040
+	 *                                       float
3041
+	 * @param int           $new_id          for now we assume only int keys
3042
+	 * @throws EE_Error
3043
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3044
+	 * @return int ID of new row inserted, or FALSE on failure
3045
+	 */
3046
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3047
+	{
3048
+		global $wpdb;
3049
+		$insertion_col_n_values = array();
3050
+		$format_for_insertion = array();
3051
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
3052
+		foreach ($fields_on_table as $field_name => $field_obj) {
3053
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3054
+			if ($field_obj->is_auto_increment()) {
3055
+				continue;
3056
+			}
3057
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3058
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3059
+			if ($prepared_value !== null) {
3060
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3061
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
3062
+			}
3063
+		}
3064
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3065
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3066
+			// so add the fk to the main table as a column
3067
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3068
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3069
+		}
3070
+		// insert the new entry
3071
+		$result = $this->_do_wpdb_query(
3072
+			'insert',
3073
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3074
+		);
3075
+		if ($result === false) {
3076
+			return false;
3077
+		}
3078
+		// ok, now what do we return for the ID of the newly-inserted thing?
3079
+		if ($this->has_primary_key_field()) {
3080
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3081
+				return $wpdb->insert_id;
3082
+			}
3083
+			// it's not an auto-increment primary key, so
3084
+			// it must have been supplied
3085
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3086
+		}
3087
+		// we can't return a  primary key because there is none. instead return
3088
+		// a unique string indicating this model
3089
+		return $this->get_index_primary_key_string($fields_n_values);
3090
+	}
3091
+
3092
+
3093
+
3094
+	/**
3095
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3096
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3097
+	 * and there is no default, we pass it along. WPDB will take care of it)
3098
+	 *
3099
+	 * @param EE_Model_Field_Base $field_obj
3100
+	 * @param array               $fields_n_values
3101
+	 * @return mixed string|int|float depending on what the table column will be expecting
3102
+	 * @throws EE_Error
3103
+	 */
3104
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3105
+	{
3106
+		// if this field doesn't allow nullable, don't allow it
3107
+		if (! $field_obj->is_nullable()
3108
+			&& (
3109
+				! isset($fields_n_values[ $field_obj->get_name() ])
3110
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3111
+			)
3112
+		) {
3113
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3114
+		}
3115
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3116
+			? $fields_n_values[ $field_obj->get_name() ]
3117
+			: null;
3118
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3119
+	}
3120
+
3121
+
3122
+
3123
+	/**
3124
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3125
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3126
+	 * the field's prepare_for_set() method.
3127
+	 *
3128
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3129
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3130
+	 *                                   top of file)
3131
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3132
+	 *                                   $value is a custom selection
3133
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3134
+	 */
3135
+	private function _prepare_value_for_use_in_db($value, $field)
3136
+	{
3137
+		if ($field && $field instanceof EE_Model_Field_Base) {
3138
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3139
+			switch ($this->_values_already_prepared_by_model_object) {
3140
+				/** @noinspection PhpMissingBreakStatementInspection */
3141
+				case self::not_prepared_by_model_object:
3142
+					$value = $field->prepare_for_set($value);
3143
+				// purposefully left out "return"
3144
+				case self::prepared_by_model_object:
3145
+					/** @noinspection SuspiciousAssignmentsInspection */
3146
+					$value = $field->prepare_for_use_in_db($value);
3147
+				case self::prepared_for_use_in_db:
3148
+					// leave the value alone
3149
+			}
3150
+			return $value;
3151
+			// phpcs:enable
3152
+		}
3153
+		return $value;
3154
+	}
3155
+
3156
+
3157
+
3158
+	/**
3159
+	 * Returns the main table on this model
3160
+	 *
3161
+	 * @return EE_Primary_Table
3162
+	 * @throws EE_Error
3163
+	 */
3164
+	protected function _get_main_table()
3165
+	{
3166
+		foreach ($this->_tables as $table) {
3167
+			if ($table instanceof EE_Primary_Table) {
3168
+				return $table;
3169
+			}
3170
+		}
3171
+		throw new EE_Error(sprintf(__(
3172
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3173
+			'event_espresso'
3174
+		), get_class($this)));
3175
+	}
3176
+
3177
+
3178
+
3179
+	/**
3180
+	 * table
3181
+	 * returns EE_Primary_Table table name
3182
+	 *
3183
+	 * @return string
3184
+	 * @throws EE_Error
3185
+	 */
3186
+	public function table()
3187
+	{
3188
+		return $this->_get_main_table()->get_table_name();
3189
+	}
3190
+
3191
+
3192
+
3193
+	/**
3194
+	 * table
3195
+	 * returns first EE_Secondary_Table table name
3196
+	 *
3197
+	 * @return string
3198
+	 */
3199
+	public function second_table()
3200
+	{
3201
+		// grab second table from tables array
3202
+		$second_table = end($this->_tables);
3203
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3204
+	}
3205
+
3206
+
3207
+
3208
+	/**
3209
+	 * get_table_obj_by_alias
3210
+	 * returns table name given it's alias
3211
+	 *
3212
+	 * @param string $table_alias
3213
+	 * @return EE_Primary_Table | EE_Secondary_Table
3214
+	 */
3215
+	public function get_table_obj_by_alias($table_alias = '')
3216
+	{
3217
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3218
+	}
3219
+
3220
+
3221
+
3222
+	/**
3223
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3224
+	 *
3225
+	 * @return EE_Secondary_Table[]
3226
+	 */
3227
+	protected function _get_other_tables()
3228
+	{
3229
+		$other_tables = array();
3230
+		foreach ($this->_tables as $table_alias => $table) {
3231
+			if ($table instanceof EE_Secondary_Table) {
3232
+				$other_tables[ $table_alias ] = $table;
3233
+			}
3234
+		}
3235
+		return $other_tables;
3236
+	}
3237
+
3238
+
3239
+
3240
+	/**
3241
+	 * Finds all the fields that correspond to the given table
3242
+	 *
3243
+	 * @param string $table_alias , array key in EEM_Base::_tables
3244
+	 * @return EE_Model_Field_Base[]
3245
+	 */
3246
+	public function _get_fields_for_table($table_alias)
3247
+	{
3248
+		return $this->_fields[ $table_alias ];
3249
+	}
3250
+
3251
+
3252
+
3253
+	/**
3254
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3255
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3256
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3257
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3258
+	 * related Registration, Transaction, and Payment models.
3259
+	 *
3260
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3261
+	 * @return EE_Model_Query_Info_Carrier
3262
+	 * @throws EE_Error
3263
+	 */
3264
+	public function _extract_related_models_from_query($query_params)
3265
+	{
3266
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3267
+		if (array_key_exists(0, $query_params)) {
3268
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3269
+		}
3270
+		if (array_key_exists('group_by', $query_params)) {
3271
+			if (is_array($query_params['group_by'])) {
3272
+				$this->_extract_related_models_from_sub_params_array_values(
3273
+					$query_params['group_by'],
3274
+					$query_info_carrier,
3275
+					'group_by'
3276
+				);
3277
+			} elseif (! empty($query_params['group_by'])) {
3278
+				$this->_extract_related_model_info_from_query_param(
3279
+					$query_params['group_by'],
3280
+					$query_info_carrier,
3281
+					'group_by'
3282
+				);
3283
+			}
3284
+		}
3285
+		if (array_key_exists('having', $query_params)) {
3286
+			$this->_extract_related_models_from_sub_params_array_keys(
3287
+				$query_params[0],
3288
+				$query_info_carrier,
3289
+				'having'
3290
+			);
3291
+		}
3292
+		if (array_key_exists('order_by', $query_params)) {
3293
+			if (is_array($query_params['order_by'])) {
3294
+				$this->_extract_related_models_from_sub_params_array_keys(
3295
+					$query_params['order_by'],
3296
+					$query_info_carrier,
3297
+					'order_by'
3298
+				);
3299
+			} elseif (! empty($query_params['order_by'])) {
3300
+				$this->_extract_related_model_info_from_query_param(
3301
+					$query_params['order_by'],
3302
+					$query_info_carrier,
3303
+					'order_by'
3304
+				);
3305
+			}
3306
+		}
3307
+		if (array_key_exists('force_join', $query_params)) {
3308
+			$this->_extract_related_models_from_sub_params_array_values(
3309
+				$query_params['force_join'],
3310
+				$query_info_carrier,
3311
+				'force_join'
3312
+			);
3313
+		}
3314
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3315
+		return $query_info_carrier;
3316
+	}
3317
+
3318
+
3319
+
3320
+	/**
3321
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3322
+	 *
3323
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3324
+	 *                                                      $query_params['having']
3325
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3326
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3327
+	 * @throws EE_Error
3328
+	 * @return \EE_Model_Query_Info_Carrier
3329
+	 */
3330
+	private function _extract_related_models_from_sub_params_array_keys(
3331
+		$sub_query_params,
3332
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3333
+		$query_param_type
3334
+	) {
3335
+		if (! empty($sub_query_params)) {
3336
+			$sub_query_params = (array) $sub_query_params;
3337
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3338
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3339
+				$this->_extract_related_model_info_from_query_param(
3340
+					$param,
3341
+					$model_query_info_carrier,
3342
+					$query_param_type
3343
+				);
3344
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3345
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3346
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3347
+				// of array('Registration.TXN_ID'=>23)
3348
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3349
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3350
+					if (! is_array($possibly_array_of_params)) {
3351
+						throw new EE_Error(sprintf(
3352
+							__(
3353
+								"You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3354
+								"event_espresso"
3355
+							),
3356
+							$param,
3357
+							$possibly_array_of_params
3358
+						));
3359
+					}
3360
+					$this->_extract_related_models_from_sub_params_array_keys(
3361
+						$possibly_array_of_params,
3362
+						$model_query_info_carrier,
3363
+						$query_param_type
3364
+					);
3365
+				} elseif ($query_param_type === 0 // ie WHERE
3366
+						  && is_array($possibly_array_of_params)
3367
+						  && isset($possibly_array_of_params[2])
3368
+						  && $possibly_array_of_params[2] == true
3369
+				) {
3370
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3371
+					// indicating that $possible_array_of_params[1] is actually a field name,
3372
+					// from which we should extract query parameters!
3373
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3374
+						throw new EE_Error(sprintf(__(
3375
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3376
+							"event_espresso"
3377
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3378
+					}
3379
+					$this->_extract_related_model_info_from_query_param(
3380
+						$possibly_array_of_params[1],
3381
+						$model_query_info_carrier,
3382
+						$query_param_type
3383
+					);
3384
+				}
3385
+			}
3386
+		}
3387
+		return $model_query_info_carrier;
3388
+	}
3389
+
3390
+
3391
+
3392
+	/**
3393
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3394
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3395
+	 *
3396
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3397
+	 *                                                      $query_params['having']
3398
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3399
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3400
+	 * @throws EE_Error
3401
+	 * @return \EE_Model_Query_Info_Carrier
3402
+	 */
3403
+	private function _extract_related_models_from_sub_params_array_values(
3404
+		$sub_query_params,
3405
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3406
+		$query_param_type
3407
+	) {
3408
+		if (! empty($sub_query_params)) {
3409
+			if (! is_array($sub_query_params)) {
3410
+				throw new EE_Error(sprintf(
3411
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3412
+					$sub_query_params
3413
+				));
3414
+			}
3415
+			foreach ($sub_query_params as $param) {
3416
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3417
+				$this->_extract_related_model_info_from_query_param(
3418
+					$param,
3419
+					$model_query_info_carrier,
3420
+					$query_param_type
3421
+				);
3422
+			}
3423
+		}
3424
+		return $model_query_info_carrier;
3425
+	}
3426
+
3427
+
3428
+
3429
+	/**
3430
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3431
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3432
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3433
+	 * but use them in a different order. Eg, we need to know what models we are querying
3434
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3435
+	 * other models before we can finalize the where clause SQL.
3436
+	 *
3437
+	 * @param array $query_params
3438
+	 * @throws EE_Error
3439
+	 * @return EE_Model_Query_Info_Carrier
3440
+	 */
3441
+	public function _create_model_query_info_carrier($query_params)
3442
+	{
3443
+		if (! is_array($query_params)) {
3444
+			EE_Error::doing_it_wrong(
3445
+				'EEM_Base::_create_model_query_info_carrier',
3446
+				sprintf(
3447
+					__(
3448
+						'$query_params should be an array, you passed a variable of type %s',
3449
+						'event_espresso'
3450
+					),
3451
+					gettype($query_params)
3452
+				),
3453
+				'4.6.0'
3454
+			);
3455
+			$query_params = array();
3456
+		}
3457
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3458
+		// first check if we should alter the query to account for caps or not
3459
+		// because the caps might require us to do extra joins
3460
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3461
+			$query_params[0] = $where_query_params = array_replace_recursive(
3462
+				$where_query_params,
3463
+				$this->caps_where_conditions(
3464
+					$query_params['caps']
3465
+				)
3466
+			);
3467
+		}
3468
+		$query_object = $this->_extract_related_models_from_query($query_params);
3469
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3470
+		foreach ($where_query_params as $key => $value) {
3471
+			if (is_int($key)) {
3472
+				throw new EE_Error(
3473
+					sprintf(
3474
+						__(
3475
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3476
+							"event_espresso"
3477
+						),
3478
+						$key,
3479
+						var_export($value, true),
3480
+						var_export($query_params, true),
3481
+						get_class($this)
3482
+					)
3483
+				);
3484
+			}
3485
+		}
3486
+		if (array_key_exists('default_where_conditions', $query_params)
3487
+			&& ! empty($query_params['default_where_conditions'])
3488
+		) {
3489
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3490
+		} else {
3491
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3492
+		}
3493
+		$where_query_params = array_merge(
3494
+			$this->_get_default_where_conditions_for_models_in_query(
3495
+				$query_object,
3496
+				$use_default_where_conditions,
3497
+				$where_query_params
3498
+			),
3499
+			$where_query_params
3500
+		);
3501
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3502
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3503
+		// So we need to setup a subquery and use that for the main join.
3504
+		// Note for now this only works on the primary table for the model.
3505
+		// So for instance, you could set the limit array like this:
3506
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3507
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3508
+			$query_object->set_main_model_join_sql(
3509
+				$this->_construct_limit_join_select(
3510
+					$query_params['on_join_limit'][0],
3511
+					$query_params['on_join_limit'][1]
3512
+				)
3513
+			);
3514
+		}
3515
+		// set limit
3516
+		if (array_key_exists('limit', $query_params)) {
3517
+			if (is_array($query_params['limit'])) {
3518
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3519
+					$e = sprintf(
3520
+						__(
3521
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3522
+							"event_espresso"
3523
+						),
3524
+						http_build_query($query_params['limit'])
3525
+					);
3526
+					throw new EE_Error($e . "|" . $e);
3527
+				}
3528
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3529
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3530
+			} elseif (! empty($query_params['limit'])) {
3531
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3532
+			}
3533
+		}
3534
+		// set order by
3535
+		if (array_key_exists('order_by', $query_params)) {
3536
+			if (is_array($query_params['order_by'])) {
3537
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3538
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3539
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3540
+				if (array_key_exists('order', $query_params)) {
3541
+					throw new EE_Error(
3542
+						sprintf(
3543
+							__(
3544
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3545
+								"event_espresso"
3546
+							),
3547
+							get_class($this),
3548
+							implode(", ", array_keys($query_params['order_by'])),
3549
+							implode(", ", $query_params['order_by']),
3550
+							$query_params['order']
3551
+						)
3552
+					);
3553
+				}
3554
+				$this->_extract_related_models_from_sub_params_array_keys(
3555
+					$query_params['order_by'],
3556
+					$query_object,
3557
+					'order_by'
3558
+				);
3559
+				// assume it's an array of fields to order by
3560
+				$order_array = array();
3561
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3562
+					$order = $this->_extract_order($order);
3563
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3564
+				}
3565
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3566
+			} elseif (! empty($query_params['order_by'])) {
3567
+				$this->_extract_related_model_info_from_query_param(
3568
+					$query_params['order_by'],
3569
+					$query_object,
3570
+					'order',
3571
+					$query_params['order_by']
3572
+				);
3573
+				$order = isset($query_params['order'])
3574
+					? $this->_extract_order($query_params['order'])
3575
+					: 'DESC';
3576
+				$query_object->set_order_by_sql(
3577
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3578
+				);
3579
+			}
3580
+		}
3581
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3582
+		if (! array_key_exists('order_by', $query_params)
3583
+			&& array_key_exists('order', $query_params)
3584
+			&& ! empty($query_params['order'])
3585
+		) {
3586
+			$pk_field = $this->get_primary_key_field();
3587
+			$order = $this->_extract_order($query_params['order']);
3588
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3589
+		}
3590
+		// set group by
3591
+		if (array_key_exists('group_by', $query_params)) {
3592
+			if (is_array($query_params['group_by'])) {
3593
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3594
+				$group_by_array = array();
3595
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3596
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3597
+				}
3598
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3599
+			} elseif (! empty($query_params['group_by'])) {
3600
+				$query_object->set_group_by_sql(
3601
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3602
+				);
3603
+			}
3604
+		}
3605
+		// set having
3606
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3607
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3608
+		}
3609
+		// now, just verify they didn't pass anything wack
3610
+		foreach ($query_params as $query_key => $query_value) {
3611
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3612
+				throw new EE_Error(
3613
+					sprintf(
3614
+						__(
3615
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3616
+							'event_espresso'
3617
+						),
3618
+						$query_key,
3619
+						get_class($this),
3620
+						//                      print_r( $this->_allowed_query_params, TRUE )
3621
+						implode(',', $this->_allowed_query_params)
3622
+					)
3623
+				);
3624
+			}
3625
+		}
3626
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3627
+		if (empty($main_model_join_sql)) {
3628
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3629
+		}
3630
+		return $query_object;
3631
+	}
3632
+
3633
+
3634
+
3635
+	/**
3636
+	 * Gets the where conditions that should be imposed on the query based on the
3637
+	 * context (eg reading frontend, backend, edit or delete).
3638
+	 *
3639
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3640
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3641
+	 * @throws EE_Error
3642
+	 */
3643
+	public function caps_where_conditions($context = self::caps_read)
3644
+	{
3645
+		EEM_Base::verify_is_valid_cap_context($context);
3646
+		$cap_where_conditions = array();
3647
+		$cap_restrictions = $this->caps_missing($context);
3648
+		/**
3649
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3650
+		 */
3651
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3652
+			$cap_where_conditions = array_replace_recursive(
3653
+				$cap_where_conditions,
3654
+				$restriction_if_no_cap->get_default_where_conditions()
3655
+			);
3656
+		}
3657
+		return apply_filters(
3658
+			'FHEE__EEM_Base__caps_where_conditions__return',
3659
+			$cap_where_conditions,
3660
+			$this,
3661
+			$context,
3662
+			$cap_restrictions
3663
+		);
3664
+	}
3665
+
3666
+
3667
+
3668
+	/**
3669
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3670
+	 * otherwise throws an exception
3671
+	 *
3672
+	 * @param string $should_be_order_string
3673
+	 * @return string either ASC, asc, DESC or desc
3674
+	 * @throws EE_Error
3675
+	 */
3676
+	private function _extract_order($should_be_order_string)
3677
+	{
3678
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3679
+			return $should_be_order_string;
3680
+		}
3681
+		throw new EE_Error(
3682
+			sprintf(
3683
+				__(
3684
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3685
+					"event_espresso"
3686
+				),
3687
+				get_class($this),
3688
+				$should_be_order_string
3689
+			)
3690
+		);
3691
+	}
3692
+
3693
+
3694
+
3695
+	/**
3696
+	 * Looks at all the models which are included in this query, and asks each
3697
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3698
+	 * so they can be merged
3699
+	 *
3700
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3701
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3702
+	 *                                                                  'none' means NO default where conditions will
3703
+	 *                                                                  be used AT ALL during this query.
3704
+	 *                                                                  'other_models_only' means default where
3705
+	 *                                                                  conditions from other models will be used, but
3706
+	 *                                                                  not for this primary model. 'all', the default,
3707
+	 *                                                                  means default where conditions will apply as
3708
+	 *                                                                  normal
3709
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3710
+	 * @throws EE_Error
3711
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3712
+	 */
3713
+	private function _get_default_where_conditions_for_models_in_query(
3714
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3715
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3716
+		$where_query_params = array()
3717
+	) {
3718
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3719
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3720
+			throw new EE_Error(sprintf(
3721
+				__(
3722
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3723
+					"event_espresso"
3724
+				),
3725
+				$use_default_where_conditions,
3726
+				implode(", ", $allowed_used_default_where_conditions_values)
3727
+			));
3728
+		}
3729
+		$universal_query_params = array();
3730
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3731
+			$universal_query_params = $this->_get_default_where_conditions();
3732
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3733
+			$universal_query_params = $this->_get_minimum_where_conditions();
3734
+		}
3735
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3736
+			$related_model = $this->get_related_model_obj($model_name);
3737
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3738
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3739
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3740
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3741
+			} else {
3742
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3743
+				continue;
3744
+			}
3745
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3746
+				$related_model_universal_where_params,
3747
+				$where_query_params,
3748
+				$related_model,
3749
+				$model_relation_path
3750
+			);
3751
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3752
+				$universal_query_params,
3753
+				$overrides
3754
+			);
3755
+		}
3756
+		return $universal_query_params;
3757
+	}
3758
+
3759
+
3760
+
3761
+	/**
3762
+	 * Determines whether or not we should use default where conditions for the model in question
3763
+	 * (this model, or other related models).
3764
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3765
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3766
+	 * We should use default where conditions on related models when they requested to use default where conditions
3767
+	 * on all models, or specifically just on other related models
3768
+	 * @param      $default_where_conditions_value
3769
+	 * @param bool $for_this_model false means this is for OTHER related models
3770
+	 * @return bool
3771
+	 */
3772
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3773
+	{
3774
+		return (
3775
+				   $for_this_model
3776
+				   && in_array(
3777
+					   $default_where_conditions_value,
3778
+					   array(
3779
+						   EEM_Base::default_where_conditions_all,
3780
+						   EEM_Base::default_where_conditions_this_only,
3781
+						   EEM_Base::default_where_conditions_minimum_others,
3782
+					   ),
3783
+					   true
3784
+				   )
3785
+			   )
3786
+			   || (
3787
+				   ! $for_this_model
3788
+				   && in_array(
3789
+					   $default_where_conditions_value,
3790
+					   array(
3791
+						   EEM_Base::default_where_conditions_all,
3792
+						   EEM_Base::default_where_conditions_others_only,
3793
+					   ),
3794
+					   true
3795
+				   )
3796
+			   );
3797
+	}
3798
+
3799
+	/**
3800
+	 * Determines whether or not we should use default minimum conditions for the model in question
3801
+	 * (this model, or other related models).
3802
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3803
+	 * where conditions.
3804
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3805
+	 * on this model or others
3806
+	 * @param      $default_where_conditions_value
3807
+	 * @param bool $for_this_model false means this is for OTHER related models
3808
+	 * @return bool
3809
+	 */
3810
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3811
+	{
3812
+		return (
3813
+				   $for_this_model
3814
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3815
+			   )
3816
+			   || (
3817
+				   ! $for_this_model
3818
+				   && in_array(
3819
+					   $default_where_conditions_value,
3820
+					   array(
3821
+						   EEM_Base::default_where_conditions_minimum_others,
3822
+						   EEM_Base::default_where_conditions_minimum_all,
3823
+					   ),
3824
+					   true
3825
+				   )
3826
+			   );
3827
+	}
3828
+
3829
+
3830
+	/**
3831
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3832
+	 * then we also add a special where condition which allows for that model's primary key
3833
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3834
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3835
+	 *
3836
+	 * @param array    $default_where_conditions
3837
+	 * @param array    $provided_where_conditions
3838
+	 * @param EEM_Base $model
3839
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3840
+	 * @return array like EEM_Base::get_all's $query_params[0]
3841
+	 * @throws EE_Error
3842
+	 */
3843
+	private function _override_defaults_or_make_null_friendly(
3844
+		$default_where_conditions,
3845
+		$provided_where_conditions,
3846
+		$model,
3847
+		$model_relation_path
3848
+	) {
3849
+		$null_friendly_where_conditions = array();
3850
+		$none_overridden = true;
3851
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3852
+		foreach ($default_where_conditions as $key => $val) {
3853
+			if (isset($provided_where_conditions[ $key ])) {
3854
+				$none_overridden = false;
3855
+			} else {
3856
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3857
+			}
3858
+		}
3859
+		if ($none_overridden && $default_where_conditions) {
3860
+			if ($model->has_primary_key_field()) {
3861
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3862
+																				. "."
3863
+																				. $model->primary_key_name() ] = array('IS NULL');
3864
+			}/*else{
3865 3865
                 //@todo NO PK, use other defaults
3866 3866
             }*/
3867
-        }
3868
-        return $null_friendly_where_conditions;
3869
-    }
3870
-
3871
-
3872
-
3873
-    /**
3874
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3875
-     * default where conditions on all get_all, update, and delete queries done by this model.
3876
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3877
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3878
-     *
3879
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3880
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3881
-     */
3882
-    private function _get_default_where_conditions($model_relation_path = null)
3883
-    {
3884
-        if ($this->_ignore_where_strategy) {
3885
-            return array();
3886
-        }
3887
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3888
-    }
3889
-
3890
-
3891
-
3892
-    /**
3893
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3894
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3895
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3896
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3897
-     * Similar to _get_default_where_conditions
3898
-     *
3899
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3900
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3901
-     */
3902
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3903
-    {
3904
-        if ($this->_ignore_where_strategy) {
3905
-            return array();
3906
-        }
3907
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3908
-    }
3909
-
3910
-
3911
-
3912
-    /**
3913
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3914
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3915
-     *
3916
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3917
-     * @return string
3918
-     * @throws EE_Error
3919
-     */
3920
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3921
-    {
3922
-        $selects = $this->_get_columns_to_select_for_this_model();
3923
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3924
-            $name_of_other_model_included) {
3925
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3926
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3927
-            foreach ($other_model_selects as $key => $value) {
3928
-                $selects[] = $value;
3929
-            }
3930
-        }
3931
-        return implode(", ", $selects);
3932
-    }
3933
-
3934
-
3935
-
3936
-    /**
3937
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3938
-     * So that's going to be the columns for all the fields on the model
3939
-     *
3940
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3941
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3942
-     */
3943
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3944
-    {
3945
-        $fields = $this->field_settings();
3946
-        $selects = array();
3947
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3948
-            $model_relation_chain,
3949
-            $this->get_this_model_name()
3950
-        );
3951
-        foreach ($fields as $field_obj) {
3952
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3953
-                         . $field_obj->get_table_alias()
3954
-                         . "."
3955
-                         . $field_obj->get_table_column()
3956
-                         . " AS '"
3957
-                         . $table_alias_with_model_relation_chain_prefix
3958
-                         . $field_obj->get_table_alias()
3959
-                         . "."
3960
-                         . $field_obj->get_table_column()
3961
-                         . "'";
3962
-        }
3963
-        // make sure we are also getting the PKs of each table
3964
-        $tables = $this->get_tables();
3965
-        if (count($tables) > 1) {
3966
-            foreach ($tables as $table_obj) {
3967
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3968
-                                       . $table_obj->get_fully_qualified_pk_column();
3969
-                if (! in_array($qualified_pk_column, $selects)) {
3970
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3971
-                }
3972
-            }
3973
-        }
3974
-        return $selects;
3975
-    }
3976
-
3977
-
3978
-
3979
-    /**
3980
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3981
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3982
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3983
-     * SQL for joining, and the data types
3984
-     *
3985
-     * @param null|string                 $original_query_param
3986
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3987
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3988
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3989
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3990
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3991
-     *                                                          or 'Registration's
3992
-     * @param string                      $original_query_param what it originally was (eg
3993
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3994
-     *                                                          matches $query_param
3995
-     * @throws EE_Error
3996
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3997
-     */
3998
-    private function _extract_related_model_info_from_query_param(
3999
-        $query_param,
4000
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4001
-        $query_param_type,
4002
-        $original_query_param = null
4003
-    ) {
4004
-        if ($original_query_param === null) {
4005
-            $original_query_param = $query_param;
4006
-        }
4007
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4008
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
4009
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
4010
-        $allow_fields = in_array(
4011
-            $query_param_type,
4012
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
4013
-            true
4014
-        );
4015
-        // check to see if we have a field on this model
4016
-        $this_model_fields = $this->field_settings(true);
4017
-        if (array_key_exists($query_param, $this_model_fields)) {
4018
-            if ($allow_fields) {
4019
-                return;
4020
-            }
4021
-            throw new EE_Error(
4022
-                sprintf(
4023
-                    __(
4024
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4025
-                        "event_espresso"
4026
-                    ),
4027
-                    $query_param,
4028
-                    get_class($this),
4029
-                    $query_param_type,
4030
-                    $original_query_param
4031
-                )
4032
-            );
4033
-        }
4034
-        // check if this is a special logic query param
4035
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4036
-            if ($allow_logic_query_params) {
4037
-                return;
4038
-            }
4039
-            throw new EE_Error(
4040
-                sprintf(
4041
-                    __(
4042
-                        'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4043
-                        'event_espresso'
4044
-                    ),
4045
-                    implode('", "', $this->_logic_query_param_keys),
4046
-                    $query_param,
4047
-                    get_class($this),
4048
-                    '<br />',
4049
-                    "\t"
4050
-                    . ' $passed_in_query_info = <pre>'
4051
-                    . print_r($passed_in_query_info, true)
4052
-                    . '</pre>'
4053
-                    . "\n\t"
4054
-                    . ' $query_param_type = '
4055
-                    . $query_param_type
4056
-                    . "\n\t"
4057
-                    . ' $original_query_param = '
4058
-                    . $original_query_param
4059
-                )
4060
-            );
4061
-        }
4062
-        // check if it's a custom selection
4063
-        if ($this->_custom_selections instanceof CustomSelects
4064
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4065
-        ) {
4066
-            return;
4067
-        }
4068
-        // check if has a model name at the beginning
4069
-        // and
4070
-        // check if it's a field on a related model
4071
-        if ($this->extractJoinModelFromQueryParams(
4072
-            $passed_in_query_info,
4073
-            $query_param,
4074
-            $original_query_param,
4075
-            $query_param_type
4076
-        )) {
4077
-            return;
4078
-        }
4079
-
4080
-        // ok so $query_param didn't start with a model name
4081
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4082
-        // it's wack, that's what it is
4083
-        throw new EE_Error(
4084
-            sprintf(
4085
-                esc_html__(
4086
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4087
-                    "event_espresso"
4088
-                ),
4089
-                $query_param,
4090
-                get_class($this),
4091
-                $query_param_type,
4092
-                $original_query_param
4093
-            )
4094
-        );
4095
-    }
4096
-
4097
-
4098
-    /**
4099
-     * Extracts any possible join model information from the provided possible_join_string.
4100
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4101
-     * parts that should be added to the query.
4102
-     *
4103
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4104
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4105
-     * @param null|string                 $original_query_param
4106
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4107
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4108
-     * @return bool  returns true if a join was added and false if not.
4109
-     * @throws EE_Error
4110
-     */
4111
-    private function extractJoinModelFromQueryParams(
4112
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4113
-        $possible_join_string,
4114
-        $original_query_param,
4115
-        $query_parameter_type
4116
-    ) {
4117
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4118
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4119
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4120
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4121
-                if ($possible_join_string === '') {
4122
-                    // nothing left to $query_param
4123
-                    // we should actually end in a field name, not a model like this!
4124
-                    throw new EE_Error(
4125
-                        sprintf(
4126
-                            esc_html__(
4127
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4128
-                                "event_espresso"
4129
-                            ),
4130
-                            $possible_join_string,
4131
-                            $query_parameter_type,
4132
-                            get_class($this),
4133
-                            $valid_related_model_name
4134
-                        )
4135
-                    );
4136
-                }
4137
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4138
-                $related_model_obj->_extract_related_model_info_from_query_param(
4139
-                    $possible_join_string,
4140
-                    $query_info_carrier,
4141
-                    $query_parameter_type,
4142
-                    $original_query_param
4143
-                );
4144
-                return true;
4145
-            }
4146
-            if ($possible_join_string === $valid_related_model_name) {
4147
-                $this->_add_join_to_model(
4148
-                    $valid_related_model_name,
4149
-                    $query_info_carrier,
4150
-                    $original_query_param
4151
-                );
4152
-                return true;
4153
-            }
4154
-        }
4155
-        return false;
4156
-    }
4157
-
4158
-
4159
-    /**
4160
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4161
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4162
-     * @throws EE_Error
4163
-     */
4164
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4165
-    {
4166
-        if ($this->_custom_selections instanceof CustomSelects
4167
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4168
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4169
-            )
4170
-        ) {
4171
-            $original_selects = $this->_custom_selections->originalSelects();
4172
-            foreach ($original_selects as $alias => $select_configuration) {
4173
-                $this->extractJoinModelFromQueryParams(
4174
-                    $query_info_carrier,
4175
-                    $select_configuration[0],
4176
-                    $select_configuration[0],
4177
-                    'custom_selects'
4178
-                );
4179
-            }
4180
-        }
4181
-    }
4182
-
4183
-
4184
-
4185
-    /**
4186
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4187
-     * and store it on $passed_in_query_info
4188
-     *
4189
-     * @param string                      $model_name
4190
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4191
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4192
-     *                                                          model and $model_name. Eg, if we are querying Event,
4193
-     *                                                          and are adding a join to 'Payment' with the original
4194
-     *                                                          query param key
4195
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4196
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4197
-     *                                                          Payment wants to add default query params so that it
4198
-     *                                                          will know what models to prepend onto its default query
4199
-     *                                                          params or in case it wants to rename tables (in case
4200
-     *                                                          there are multiple joins to the same table)
4201
-     * @return void
4202
-     * @throws EE_Error
4203
-     */
4204
-    private function _add_join_to_model(
4205
-        $model_name,
4206
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4207
-        $original_query_param
4208
-    ) {
4209
-        $relation_obj = $this->related_settings_for($model_name);
4210
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4211
-        // check if the relation is HABTM, because then we're essentially doing two joins
4212
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4213
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4214
-            $join_model_obj = $relation_obj->get_join_model();
4215
-            // replace the model specified with the join model for this relation chain, whi
4216
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4217
-                $model_name,
4218
-                $join_model_obj->get_this_model_name(),
4219
-                $model_relation_chain
4220
-            );
4221
-            $passed_in_query_info->merge(
4222
-                new EE_Model_Query_Info_Carrier(
4223
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4224
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4225
-                )
4226
-            );
4227
-        }
4228
-        // now just join to the other table pointed to by the relation object, and add its data types
4229
-        $passed_in_query_info->merge(
4230
-            new EE_Model_Query_Info_Carrier(
4231
-                array($model_relation_chain => $model_name),
4232
-                $relation_obj->get_join_statement($model_relation_chain)
4233
-            )
4234
-        );
4235
-    }
4236
-
4237
-
4238
-
4239
-    /**
4240
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4241
-     *
4242
-     * @param array $where_params like EEM_Base::get_all
4243
-     * @return string of SQL
4244
-     * @throws EE_Error
4245
-     */
4246
-    private function _construct_where_clause($where_params)
4247
-    {
4248
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4249
-        if ($SQL) {
4250
-            return " WHERE " . $SQL;
4251
-        }
4252
-        return '';
4253
-    }
4254
-
4255
-
4256
-
4257
-    /**
4258
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4259
-     * and should be passed HAVING parameters, not WHERE parameters
4260
-     *
4261
-     * @param array $having_params
4262
-     * @return string
4263
-     * @throws EE_Error
4264
-     */
4265
-    private function _construct_having_clause($having_params)
4266
-    {
4267
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4268
-        if ($SQL) {
4269
-            return " HAVING " . $SQL;
4270
-        }
4271
-        return '';
4272
-    }
4273
-
4274
-
4275
-    /**
4276
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4277
-     * Event_Meta.meta_value = 'foo'))"
4278
-     *
4279
-     * @param array  $where_params see EEM_Base::get_all for documentation
4280
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4281
-     * @throws EE_Error
4282
-     * @return string of SQL
4283
-     */
4284
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4285
-    {
4286
-        $where_clauses = array();
4287
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4288
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4289
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4290
-                switch ($query_param) {
4291
-                    case 'not':
4292
-                    case 'NOT':
4293
-                        $where_clauses[] = "! ("
4294
-                                           . $this->_construct_condition_clause_recursive(
4295
-                                               $op_and_value_or_sub_condition,
4296
-                                               $glue
4297
-                                           )
4298
-                                           . ")";
4299
-                        break;
4300
-                    case 'and':
4301
-                    case 'AND':
4302
-                        $where_clauses[] = " ("
4303
-                                           . $this->_construct_condition_clause_recursive(
4304
-                                               $op_and_value_or_sub_condition,
4305
-                                               ' AND '
4306
-                                           )
4307
-                                           . ")";
4308
-                        break;
4309
-                    case 'or':
4310
-                    case 'OR':
4311
-                        $where_clauses[] = " ("
4312
-                                           . $this->_construct_condition_clause_recursive(
4313
-                                               $op_and_value_or_sub_condition,
4314
-                                               ' OR '
4315
-                                           )
4316
-                                           . ")";
4317
-                        break;
4318
-                }
4319
-            } else {
4320
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4321
-                // if it's not a normal field, maybe it's a custom selection?
4322
-                if (! $field_obj) {
4323
-                    if ($this->_custom_selections instanceof CustomSelects) {
4324
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4325
-                    } else {
4326
-                        throw new EE_Error(sprintf(__(
4327
-                            "%s is neither a valid model field name, nor a custom selection",
4328
-                            "event_espresso"
4329
-                        ), $query_param));
4330
-                    }
4331
-                }
4332
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4333
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4334
-            }
4335
-        }
4336
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4337
-    }
4338
-
4339
-
4340
-
4341
-    /**
4342
-     * Takes the input parameter and extract the table name (alias) and column name
4343
-     *
4344
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4345
-     * @throws EE_Error
4346
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4347
-     */
4348
-    private function _deduce_column_name_from_query_param($query_param)
4349
-    {
4350
-        $field = $this->_deduce_field_from_query_param($query_param);
4351
-        if ($field) {
4352
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4353
-                $field->get_model_name(),
4354
-                $query_param
4355
-            );
4356
-            return $table_alias_prefix . $field->get_qualified_column();
4357
-        }
4358
-        if ($this->_custom_selections instanceof CustomSelects
4359
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4360
-        ) {
4361
-            // maybe it's custom selection item?
4362
-            // if so, just use it as the "column name"
4363
-            return $query_param;
4364
-        }
4365
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4366
-            ? implode(',', $this->_custom_selections->columnAliases())
4367
-            : '';
4368
-        throw new EE_Error(
4369
-            sprintf(
4370
-                __(
4371
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4372
-                    "event_espresso"
4373
-                ),
4374
-                $query_param,
4375
-                $custom_select_aliases
4376
-            )
4377
-        );
4378
-    }
4379
-
4380
-
4381
-
4382
-    /**
4383
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4384
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4385
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4386
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4387
-     *
4388
-     * @param string $condition_query_param_key
4389
-     * @return string
4390
-     */
4391
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4392
-    {
4393
-        $pos_of_star = strpos($condition_query_param_key, '*');
4394
-        if ($pos_of_star === false) {
4395
-            return $condition_query_param_key;
4396
-        }
4397
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4398
-        return $condition_query_param_sans_star;
4399
-    }
4400
-
4401
-
4402
-
4403
-    /**
4404
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4405
-     *
4406
-     * @param                            mixed      array | string    $op_and_value
4407
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4408
-     * @throws EE_Error
4409
-     * @return string
4410
-     */
4411
-    private function _construct_op_and_value($op_and_value, $field_obj)
4412
-    {
4413
-        if (is_array($op_and_value)) {
4414
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4415
-            if (! $operator) {
4416
-                $php_array_like_string = array();
4417
-                foreach ($op_and_value as $key => $value) {
4418
-                    $php_array_like_string[] = "$key=>$value";
4419
-                }
4420
-                throw new EE_Error(
4421
-                    sprintf(
4422
-                        __(
4423
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4424
-                            "event_espresso"
4425
-                        ),
4426
-                        implode(",", $php_array_like_string)
4427
-                    )
4428
-                );
4429
-            }
4430
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4431
-        } else {
4432
-            $operator = '=';
4433
-            $value = $op_and_value;
4434
-        }
4435
-        // check to see if the value is actually another field
4436
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4437
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4438
-        }
4439
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4440
-            // in this case, the value should be an array, or at least a comma-separated list
4441
-            // it will need to handle a little differently
4442
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4443
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4444
-            return $operator . SP . $cleaned_value;
4445
-        }
4446
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4447
-            // the value should be an array with count of two.
4448
-            if (count($value) !== 2) {
4449
-                throw new EE_Error(
4450
-                    sprintf(
4451
-                        __(
4452
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4453
-                            'event_espresso'
4454
-                        ),
4455
-                        "BETWEEN"
4456
-                    )
4457
-                );
4458
-            }
4459
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4460
-            return $operator . SP . $cleaned_value;
4461
-        }
4462
-        if (in_array($operator, $this->valid_null_style_operators())) {
4463
-            if ($value !== null) {
4464
-                throw new EE_Error(
4465
-                    sprintf(
4466
-                        __(
4467
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4468
-                            "event_espresso"
4469
-                        ),
4470
-                        $value,
4471
-                        $operator
4472
-                    )
4473
-                );
4474
-            }
4475
-            return $operator;
4476
-        }
4477
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4478
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4479
-            // remove other junk. So just treat it as a string.
4480
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4481
-        }
4482
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4483
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4484
-        }
4485
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4486
-            throw new EE_Error(
4487
-                sprintf(
4488
-                    __(
4489
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4490
-                        'event_espresso'
4491
-                    ),
4492
-                    $operator,
4493
-                    $operator
4494
-                )
4495
-            );
4496
-        }
4497
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4498
-            throw new EE_Error(
4499
-                sprintf(
4500
-                    __(
4501
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4502
-                        'event_espresso'
4503
-                    ),
4504
-                    $operator,
4505
-                    $operator
4506
-                )
4507
-            );
4508
-        }
4509
-        throw new EE_Error(
4510
-            sprintf(
4511
-                __(
4512
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4513
-                    "event_espresso"
4514
-                ),
4515
-                http_build_query($op_and_value)
4516
-            )
4517
-        );
4518
-    }
4519
-
4520
-
4521
-
4522
-    /**
4523
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4524
-     *
4525
-     * @param array                      $values
4526
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4527
-     *                                              '%s'
4528
-     * @return string
4529
-     * @throws EE_Error
4530
-     */
4531
-    public function _construct_between_value($values, $field_obj)
4532
-    {
4533
-        $cleaned_values = array();
4534
-        foreach ($values as $value) {
4535
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4536
-        }
4537
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4538
-    }
4539
-
4540
-
4541
-
4542
-    /**
4543
-     * Takes an array or a comma-separated list of $values and cleans them
4544
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4545
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4546
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4547
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4548
-     *
4549
-     * @param mixed                      $values    array or comma-separated string
4550
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4551
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4552
-     * @throws EE_Error
4553
-     */
4554
-    public function _construct_in_value($values, $field_obj)
4555
-    {
4556
-        // check if the value is a CSV list
4557
-        if (is_string($values)) {
4558
-            // in which case, turn it into an array
4559
-            $values = explode(",", $values);
4560
-        }
4561
-        $cleaned_values = array();
4562
-        foreach ($values as $value) {
4563
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4564
-        }
4565
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4566
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4567
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4568
-        if (empty($cleaned_values)) {
4569
-            $all_fields = $this->field_settings();
4570
-            $a_field = array_shift($all_fields);
4571
-            $main_table = $this->_get_main_table();
4572
-            $cleaned_values[] = "SELECT "
4573
-                                . $a_field->get_table_column()
4574
-                                . " FROM "
4575
-                                . $main_table->get_table_name()
4576
-                                . " WHERE FALSE";
4577
-        }
4578
-        return "(" . implode(",", $cleaned_values) . ")";
4579
-    }
4580
-
4581
-
4582
-
4583
-    /**
4584
-     * @param mixed                      $value
4585
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4586
-     * @throws EE_Error
4587
-     * @return false|null|string
4588
-     */
4589
-    private function _wpdb_prepare_using_field($value, $field_obj)
4590
-    {
4591
-        /** @type WPDB $wpdb */
4592
-        global $wpdb;
4593
-        if ($field_obj instanceof EE_Model_Field_Base) {
4594
-            return $wpdb->prepare(
4595
-                $field_obj->get_wpdb_data_type(),
4596
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4597
-            );
4598
-        } //$field_obj should really just be a data type
4599
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4600
-            throw new EE_Error(
4601
-                sprintf(
4602
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4603
-                    $field_obj,
4604
-                    implode(",", $this->_valid_wpdb_data_types)
4605
-                )
4606
-            );
4607
-        }
4608
-        return $wpdb->prepare($field_obj, $value);
4609
-    }
4610
-
4611
-
4612
-
4613
-    /**
4614
-     * Takes the input parameter and finds the model field that it indicates.
4615
-     *
4616
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4617
-     * @throws EE_Error
4618
-     * @return EE_Model_Field_Base
4619
-     */
4620
-    protected function _deduce_field_from_query_param($query_param_name)
4621
-    {
4622
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4623
-        // which will help us find the database table and column
4624
-        $query_param_parts = explode(".", $query_param_name);
4625
-        if (empty($query_param_parts)) {
4626
-            throw new EE_Error(sprintf(__(
4627
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4628
-                'event_espresso'
4629
-            ), $query_param_name));
4630
-        }
4631
-        $number_of_parts = count($query_param_parts);
4632
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4633
-        if ($number_of_parts === 1) {
4634
-            $field_name = $last_query_param_part;
4635
-            $model_obj = $this;
4636
-        } else {// $number_of_parts >= 2
4637
-            // the last part is the column name, and there are only 2parts. therefore...
4638
-            $field_name = $last_query_param_part;
4639
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4640
-        }
4641
-        try {
4642
-            return $model_obj->field_settings_for($field_name);
4643
-        } catch (EE_Error $e) {
4644
-            return null;
4645
-        }
4646
-    }
4647
-
4648
-
4649
-
4650
-    /**
4651
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4652
-     * alias and column which corresponds to it
4653
-     *
4654
-     * @param string $field_name
4655
-     * @throws EE_Error
4656
-     * @return string
4657
-     */
4658
-    public function _get_qualified_column_for_field($field_name)
4659
-    {
4660
-        $all_fields = $this->field_settings();
4661
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4662
-        if ($field) {
4663
-            return $field->get_qualified_column();
4664
-        }
4665
-        throw new EE_Error(
4666
-            sprintf(
4667
-                __(
4668
-                    "There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4669
-                    'event_espresso'
4670
-                ),
4671
-                $field_name,
4672
-                get_class($this)
4673
-            )
4674
-        );
4675
-    }
4676
-
4677
-
4678
-
4679
-    /**
4680
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4681
-     * Example usage:
4682
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4683
-     *      array(),
4684
-     *      ARRAY_A,
4685
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4686
-     *  );
4687
-     * is equivalent to
4688
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4689
-     * and
4690
-     *  EEM_Event::instance()->get_all_wpdb_results(
4691
-     *      array(
4692
-     *          array(
4693
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4694
-     *          ),
4695
-     *          ARRAY_A,
4696
-     *          implode(
4697
-     *              ', ',
4698
-     *              array_merge(
4699
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4700
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4701
-     *              )
4702
-     *          )
4703
-     *      )
4704
-     *  );
4705
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4706
-     *
4707
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4708
-     *                                            and the one whose fields you are selecting for example: when querying
4709
-     *                                            tickets model and selecting fields from the tickets model you would
4710
-     *                                            leave this parameter empty, because no models are needed to join
4711
-     *                                            between the queried model and the selected one. Likewise when
4712
-     *                                            querying the datetime model and selecting fields from the tickets
4713
-     *                                            model, it would also be left empty, because there is a direct
4714
-     *                                            relation from datetimes to tickets, so no model is needed to join
4715
-     *                                            them together. However, when querying from the event model and
4716
-     *                                            selecting fields from the ticket model, you should provide the string
4717
-     *                                            'Datetime', indicating that the event model must first join to the
4718
-     *                                            datetime model in order to find its relation to ticket model.
4719
-     *                                            Also, when querying from the venue model and selecting fields from
4720
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4721
-     *                                            indicating you need to join the venue model to the event model,
4722
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4723
-     *                                            This string is used to deduce the prefix that gets added onto the
4724
-     *                                            models' tables qualified columns
4725
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4726
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4727
-     *                                            qualified column names
4728
-     * @return array|string
4729
-     */
4730
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4731
-    {
4732
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4733
-        $qualified_columns = array();
4734
-        foreach ($this->field_settings() as $field_name => $field) {
4735
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4736
-        }
4737
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4738
-    }
4739
-
4740
-
4741
-
4742
-    /**
4743
-     * constructs the select use on special limit joins
4744
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4745
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4746
-     * (as that is typically where the limits would be set).
4747
-     *
4748
-     * @param  string       $table_alias The table the select is being built for
4749
-     * @param  mixed|string $limit       The limit for this select
4750
-     * @return string                The final select join element for the query.
4751
-     */
4752
-    public function _construct_limit_join_select($table_alias, $limit)
4753
-    {
4754
-        $SQL = '';
4755
-        foreach ($this->_tables as $table_obj) {
4756
-            if ($table_obj instanceof EE_Primary_Table) {
4757
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4758
-                    ? $table_obj->get_select_join_limit($limit)
4759
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4760
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4761
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4762
-                    ? $table_obj->get_select_join_limit_join($limit)
4763
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4764
-            }
4765
-        }
4766
-        return $SQL;
4767
-    }
4768
-
4769
-
4770
-
4771
-    /**
4772
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4773
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4774
-     *
4775
-     * @return string SQL
4776
-     * @throws EE_Error
4777
-     */
4778
-    public function _construct_internal_join()
4779
-    {
4780
-        $SQL = $this->_get_main_table()->get_table_sql();
4781
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4782
-        return $SQL;
4783
-    }
4784
-
4785
-
4786
-
4787
-    /**
4788
-     * Constructs the SQL for joining all the tables on this model.
4789
-     * Normally $alias should be the primary table's alias, but in cases where
4790
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4791
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4792
-     * alias, this will construct SQL like:
4793
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4794
-     * With $alias being a secondary table's alias, this will construct SQL like:
4795
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4796
-     *
4797
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4798
-     * @return string
4799
-     */
4800
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4801
-    {
4802
-        $SQL = '';
4803
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4804
-        foreach ($this->_tables as $table_obj) {
4805
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4806
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4807
-                    // so we're joining to this table, meaning the table is already in
4808
-                    // the FROM statement, BUT the primary table isn't. So we want
4809
-                    // to add the inverse join sql
4810
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4811
-                } else {
4812
-                    // just add a regular JOIN to this table from the primary table
4813
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4814
-                }
4815
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4816
-        }
4817
-        return $SQL;
4818
-    }
4819
-
4820
-
4821
-
4822
-    /**
4823
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4824
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4825
-     * their data type (eg, '%s', '%d', etc)
4826
-     *
4827
-     * @return array
4828
-     */
4829
-    public function _get_data_types()
4830
-    {
4831
-        $data_types = array();
4832
-        foreach ($this->field_settings() as $field_obj) {
4833
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4834
-            /** @var $field_obj EE_Model_Field_Base */
4835
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4836
-        }
4837
-        return $data_types;
4838
-    }
4839
-
4840
-
4841
-
4842
-    /**
4843
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4844
-     *
4845
-     * @param string $model_name
4846
-     * @throws EE_Error
4847
-     * @return EEM_Base
4848
-     */
4849
-    public function get_related_model_obj($model_name)
4850
-    {
4851
-        $model_classname = "EEM_" . $model_name;
4852
-        if (! class_exists($model_classname)) {
4853
-            throw new EE_Error(sprintf(__(
4854
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4855
-                'event_espresso'
4856
-            ), $model_name, $model_classname));
4857
-        }
4858
-        return call_user_func($model_classname . "::instance");
4859
-    }
4860
-
4861
-
4862
-
4863
-    /**
4864
-     * Returns the array of EE_ModelRelations for this model.
4865
-     *
4866
-     * @return EE_Model_Relation_Base[]
4867
-     */
4868
-    public function relation_settings()
4869
-    {
4870
-        return $this->_model_relations;
4871
-    }
4872
-
4873
-
4874
-
4875
-    /**
4876
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4877
-     * because without THOSE models, this model probably doesn't have much purpose.
4878
-     * (Eg, without an event, datetimes have little purpose.)
4879
-     *
4880
-     * @return EE_Belongs_To_Relation[]
4881
-     */
4882
-    public function belongs_to_relations()
4883
-    {
4884
-        $belongs_to_relations = array();
4885
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4886
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4887
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4888
-            }
4889
-        }
4890
-        return $belongs_to_relations;
4891
-    }
4892
-
4893
-
4894
-
4895
-    /**
4896
-     * Returns the specified EE_Model_Relation, or throws an exception
4897
-     *
4898
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4899
-     * @throws EE_Error
4900
-     * @return EE_Model_Relation_Base
4901
-     */
4902
-    public function related_settings_for($relation_name)
4903
-    {
4904
-        $relatedModels = $this->relation_settings();
4905
-        if (! array_key_exists($relation_name, $relatedModels)) {
4906
-            throw new EE_Error(
4907
-                sprintf(
4908
-                    __(
4909
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4910
-                        'event_espresso'
4911
-                    ),
4912
-                    $relation_name,
4913
-                    $this->_get_class_name(),
4914
-                    implode(', ', array_keys($relatedModels))
4915
-                )
4916
-            );
4917
-        }
4918
-        return $relatedModels[ $relation_name ];
4919
-    }
4920
-
4921
-
4922
-
4923
-    /**
4924
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4925
-     * fields
4926
-     *
4927
-     * @param string $fieldName
4928
-     * @param boolean $include_db_only_fields
4929
-     * @throws EE_Error
4930
-     * @return EE_Model_Field_Base
4931
-     */
4932
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4933
-    {
4934
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4935
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4936
-            throw new EE_Error(sprintf(
4937
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4938
-                $fieldName,
4939
-                get_class($this)
4940
-            ));
4941
-        }
4942
-        return $fieldSettings[ $fieldName ];
4943
-    }
4944
-
4945
-
4946
-
4947
-    /**
4948
-     * Checks if this field exists on this model
4949
-     *
4950
-     * @param string $fieldName a key in the model's _field_settings array
4951
-     * @return boolean
4952
-     */
4953
-    public function has_field($fieldName)
4954
-    {
4955
-        $fieldSettings = $this->field_settings(true);
4956
-        if (isset($fieldSettings[ $fieldName ])) {
4957
-            return true;
4958
-        }
4959
-        return false;
4960
-    }
4961
-
4962
-
4963
-
4964
-    /**
4965
-     * Returns whether or not this model has a relation to the specified model
4966
-     *
4967
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4968
-     * @return boolean
4969
-     */
4970
-    public function has_relation($relation_name)
4971
-    {
4972
-        $relations = $this->relation_settings();
4973
-        if (isset($relations[ $relation_name ])) {
4974
-            return true;
4975
-        }
4976
-        return false;
4977
-    }
4978
-
4979
-
4980
-
4981
-    /**
4982
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4983
-     * Eg, on EE_Answer that would be ANS_ID field object
4984
-     *
4985
-     * @param $field_obj
4986
-     * @return boolean
4987
-     */
4988
-    public function is_primary_key_field($field_obj)
4989
-    {
4990
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4991
-    }
4992
-
4993
-
4994
-
4995
-    /**
4996
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4997
-     * Eg, on EE_Answer that would be ANS_ID field object
4998
-     *
4999
-     * @return EE_Model_Field_Base
5000
-     * @throws EE_Error
5001
-     */
5002
-    public function get_primary_key_field()
5003
-    {
5004
-        if ($this->_primary_key_field === null) {
5005
-            foreach ($this->field_settings(true) as $field_obj) {
5006
-                if ($this->is_primary_key_field($field_obj)) {
5007
-                    $this->_primary_key_field = $field_obj;
5008
-                    break;
5009
-                }
5010
-            }
5011
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5012
-                throw new EE_Error(sprintf(
5013
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
5014
-                    get_class($this)
5015
-                ));
5016
-            }
5017
-        }
5018
-        return $this->_primary_key_field;
5019
-    }
5020
-
5021
-
5022
-
5023
-    /**
5024
-     * Returns whether or not not there is a primary key on this model.
5025
-     * Internally does some caching.
5026
-     *
5027
-     * @return boolean
5028
-     */
5029
-    public function has_primary_key_field()
5030
-    {
5031
-        if ($this->_has_primary_key_field === null) {
5032
-            try {
5033
-                $this->get_primary_key_field();
5034
-                $this->_has_primary_key_field = true;
5035
-            } catch (EE_Error $e) {
5036
-                $this->_has_primary_key_field = false;
5037
-            }
5038
-        }
5039
-        return $this->_has_primary_key_field;
5040
-    }
5041
-
5042
-
5043
-
5044
-    /**
5045
-     * Finds the first field of type $field_class_name.
5046
-     *
5047
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5048
-     *                                 EE_Foreign_Key_Field, etc
5049
-     * @return EE_Model_Field_Base or null if none is found
5050
-     */
5051
-    public function get_a_field_of_type($field_class_name)
5052
-    {
5053
-        foreach ($this->field_settings() as $field) {
5054
-            if ($field instanceof $field_class_name) {
5055
-                return $field;
5056
-            }
5057
-        }
5058
-        return null;
5059
-    }
5060
-
5061
-
5062
-
5063
-    /**
5064
-     * Gets a foreign key field pointing to model.
5065
-     *
5066
-     * @param string $model_name eg Event, Registration, not EEM_Event
5067
-     * @return EE_Foreign_Key_Field_Base
5068
-     * @throws EE_Error
5069
-     */
5070
-    public function get_foreign_key_to($model_name)
5071
-    {
5072
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5073
-            foreach ($this->field_settings() as $field) {
5074
-                if ($field instanceof EE_Foreign_Key_Field_Base
5075
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5076
-                ) {
5077
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5078
-                    break;
5079
-                }
5080
-            }
5081
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5082
-                throw new EE_Error(sprintf(__(
5083
-                    "There is no foreign key field pointing to model %s on model %s",
5084
-                    'event_espresso'
5085
-                ), $model_name, get_class($this)));
5086
-            }
5087
-        }
5088
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5089
-    }
5090
-
5091
-
5092
-
5093
-    /**
5094
-     * Gets the table name (including $wpdb->prefix) for the table alias
5095
-     *
5096
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5097
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5098
-     *                            Either one works
5099
-     * @return string
5100
-     */
5101
-    public function get_table_for_alias($table_alias)
5102
-    {
5103
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5104
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5105
-    }
5106
-
5107
-
5108
-
5109
-    /**
5110
-     * Returns a flat array of all field son this model, instead of organizing them
5111
-     * by table_alias as they are in the constructor.
5112
-     *
5113
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5114
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5115
-     */
5116
-    public function field_settings($include_db_only_fields = false)
5117
-    {
5118
-        if ($include_db_only_fields) {
5119
-            if ($this->_cached_fields === null) {
5120
-                $this->_cached_fields = array();
5121
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5122
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5123
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5124
-                    }
5125
-                }
5126
-            }
5127
-            return $this->_cached_fields;
5128
-        }
5129
-        if ($this->_cached_fields_non_db_only === null) {
5130
-            $this->_cached_fields_non_db_only = array();
5131
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5132
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5133
-                    /** @var $field_obj EE_Model_Field_Base */
5134
-                    if (! $field_obj->is_db_only_field()) {
5135
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5136
-                    }
5137
-                }
5138
-            }
5139
-        }
5140
-        return $this->_cached_fields_non_db_only;
5141
-    }
5142
-
5143
-
5144
-
5145
-    /**
5146
-     *        cycle though array of attendees and create objects out of each item
5147
-     *
5148
-     * @access        private
5149
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5150
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5151
-     *                           numerically indexed)
5152
-     * @throws EE_Error
5153
-     */
5154
-    protected function _create_objects($rows = array())
5155
-    {
5156
-        $array_of_objects = array();
5157
-        if (empty($rows)) {
5158
-            return array();
5159
-        }
5160
-        $count_if_model_has_no_primary_key = 0;
5161
-        $has_primary_key = $this->has_primary_key_field();
5162
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5163
-        foreach ((array) $rows as $row) {
5164
-            if (empty($row)) {
5165
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5166
-                return array();
5167
-            }
5168
-            // check if we've already set this object in the results array,
5169
-            // in which case there's no need to process it further (again)
5170
-            if ($has_primary_key) {
5171
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5172
-                    $row,
5173
-                    $primary_key_field->get_qualified_column(),
5174
-                    $primary_key_field->get_table_column()
5175
-                );
5176
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5177
-                    continue;
5178
-                }
5179
-            }
5180
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5181
-            if (! $classInstance) {
5182
-                throw new EE_Error(
5183
-                    sprintf(
5184
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5185
-                        $this->get_this_model_name(),
5186
-                        http_build_query($row)
5187
-                    )
5188
-                );
5189
-            }
5190
-            // set the timezone on the instantiated objects
5191
-            $classInstance->set_timezone($this->_timezone);
5192
-            // make sure if there is any timezone setting present that we set the timezone for the object
5193
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5194
-            $array_of_objects[ $key ] = $classInstance;
5195
-            // also, for all the relations of type BelongsTo, see if we can cache
5196
-            // those related models
5197
-            // (we could do this for other relations too, but if there are conditions
5198
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5199
-            // so it requires a little more thought than just caching them immediately...)
5200
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5201
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5202
-                    // check if this model's INFO is present. If so, cache it on the model
5203
-                    $other_model = $relation_obj->get_other_model();
5204
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5205
-                    // if we managed to make a model object from the results, cache it on the main model object
5206
-                    if ($other_model_obj_maybe) {
5207
-                        // set timezone on these other model objects if they are present
5208
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5209
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5210
-                    }
5211
-                }
5212
-            }
5213
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5214
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5215
-            // the field in the CustomSelects object
5216
-            if ($this->_custom_selections instanceof CustomSelects) {
5217
-                $classInstance->setCustomSelectsValues(
5218
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5219
-                );
5220
-            }
5221
-        }
5222
-        return $array_of_objects;
5223
-    }
5224
-
5225
-
5226
-    /**
5227
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5228
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5229
-     *
5230
-     * @param array $db_results_row
5231
-     * @return array
5232
-     */
5233
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5234
-    {
5235
-        $results = array();
5236
-        if ($this->_custom_selections instanceof CustomSelects) {
5237
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5238
-                if (isset($db_results_row[ $alias ])) {
5239
-                    $results[ $alias ] = $this->convertValueToDataType(
5240
-                        $db_results_row[ $alias ],
5241
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5242
-                    );
5243
-                }
5244
-            }
5245
-        }
5246
-        return $results;
5247
-    }
5248
-
5249
-
5250
-    /**
5251
-     * This will set the value for the given alias
5252
-     * @param string $value
5253
-     * @param string $datatype (one of %d, %s, %f)
5254
-     * @return int|string|float (int for %d, string for %s, float for %f)
5255
-     */
5256
-    protected function convertValueToDataType($value, $datatype)
5257
-    {
5258
-        switch ($datatype) {
5259
-            case '%f':
5260
-                return (float) $value;
5261
-            case '%d':
5262
-                return (int) $value;
5263
-            default:
5264
-                return (string) $value;
5265
-        }
5266
-    }
5267
-
5268
-
5269
-    /**
5270
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5271
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5272
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5273
-     * object (as set in the model_field!).
5274
-     *
5275
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5276
-     */
5277
-    public function create_default_object()
5278
-    {
5279
-        $this_model_fields_and_values = array();
5280
-        // setup the row using default values;
5281
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5282
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5283
-        }
5284
-        $className = $this->_get_class_name();
5285
-        $classInstance = EE_Registry::instance()
5286
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5287
-        return $classInstance;
5288
-    }
5289
-
5290
-
5291
-
5292
-    /**
5293
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5294
-     *                             or an stdClass where each property is the name of a column,
5295
-     * @return EE_Base_Class
5296
-     * @throws EE_Error
5297
-     */
5298
-    public function instantiate_class_from_array_or_object($cols_n_values)
5299
-    {
5300
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5301
-            $cols_n_values = get_object_vars($cols_n_values);
5302
-        }
5303
-        $primary_key = null;
5304
-        // make sure the array only has keys that are fields/columns on this model
5305
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5306
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5307
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5308
-        }
5309
-        $className = $this->_get_class_name();
5310
-        // check we actually found results that we can use to build our model object
5311
-        // if not, return null
5312
-        if ($this->has_primary_key_field()) {
5313
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5314
-                return null;
5315
-            }
5316
-        } elseif ($this->unique_indexes()) {
5317
-            $first_column = reset($this_model_fields_n_values);
5318
-            if (empty($first_column)) {
5319
-                return null;
5320
-            }
5321
-        }
5322
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5323
-        if ($primary_key) {
5324
-            $classInstance = $this->get_from_entity_map($primary_key);
5325
-            if (! $classInstance) {
5326
-                $classInstance = EE_Registry::instance()
5327
-                                            ->load_class(
5328
-                                                $className,
5329
-                                                array($this_model_fields_n_values, $this->_timezone),
5330
-                                                true,
5331
-                                                false
5332
-                                            );
5333
-                // add this new object to the entity map
5334
-                $classInstance = $this->add_to_entity_map($classInstance);
5335
-            }
5336
-        } else {
5337
-            $classInstance = EE_Registry::instance()
5338
-                                        ->load_class(
5339
-                                            $className,
5340
-                                            array($this_model_fields_n_values, $this->_timezone),
5341
-                                            true,
5342
-                                            false
5343
-                                        );
5344
-        }
5345
-        return $classInstance;
5346
-    }
5347
-
5348
-
5349
-
5350
-    /**
5351
-     * Gets the model object from the  entity map if it exists
5352
-     *
5353
-     * @param int|string $id the ID of the model object
5354
-     * @return EE_Base_Class
5355
-     */
5356
-    public function get_from_entity_map($id)
5357
-    {
5358
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5359
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5360
-    }
5361
-
5362
-
5363
-
5364
-    /**
5365
-     * add_to_entity_map
5366
-     * Adds the object to the model's entity mappings
5367
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5368
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5369
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5370
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5371
-     *        then this method should be called immediately after the update query
5372
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5373
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5374
-     *
5375
-     * @param    EE_Base_Class $object
5376
-     * @throws EE_Error
5377
-     * @return \EE_Base_Class
5378
-     */
5379
-    public function add_to_entity_map(EE_Base_Class $object)
5380
-    {
5381
-        $className = $this->_get_class_name();
5382
-        if (! $object instanceof $className) {
5383
-            throw new EE_Error(sprintf(
5384
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5385
-                is_object($object) ? get_class($object) : $object,
5386
-                $className
5387
-            ));
5388
-        }
5389
-        /** @var $object EE_Base_Class */
5390
-        if (! $object->ID()) {
5391
-            throw new EE_Error(sprintf(__(
5392
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5393
-                "event_espresso"
5394
-            ), get_class($this)));
5395
-        }
5396
-        // double check it's not already there
5397
-        $classInstance = $this->get_from_entity_map($object->ID());
5398
-        if ($classInstance) {
5399
-            return $classInstance;
5400
-        }
5401
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5402
-        return $object;
5403
-    }
5404
-
5405
-
5406
-
5407
-    /**
5408
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5409
-     * if no identifier is provided, then the entire entity map is emptied
5410
-     *
5411
-     * @param int|string $id the ID of the model object
5412
-     * @return boolean
5413
-     */
5414
-    public function clear_entity_map($id = null)
5415
-    {
5416
-        if (empty($id)) {
5417
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5418
-            return true;
5419
-        }
5420
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5421
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5422
-            return true;
5423
-        }
5424
-        return false;
5425
-    }
5426
-
5427
-
5428
-
5429
-    /**
5430
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5431
-     * Given an array where keys are column (or column alias) names and values,
5432
-     * returns an array of their corresponding field names and database values
5433
-     *
5434
-     * @param array $cols_n_values
5435
-     * @return array
5436
-     */
5437
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5438
-    {
5439
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5440
-    }
5441
-
5442
-
5443
-
5444
-    /**
5445
-     * _deduce_fields_n_values_from_cols_n_values
5446
-     * Given an array where keys are column (or column alias) names and values,
5447
-     * returns an array of their corresponding field names and database values
5448
-     *
5449
-     * @param string $cols_n_values
5450
-     * @return array
5451
-     */
5452
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5453
-    {
5454
-        $this_model_fields_n_values = array();
5455
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5456
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5457
-                $cols_n_values,
5458
-                $table_obj->get_fully_qualified_pk_column(),
5459
-                $table_obj->get_pk_column()
5460
-            );
5461
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5462
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5463
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5464
-                    if (! $field_obj->is_db_only_field()) {
5465
-                        // prepare field as if its coming from db
5466
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5467
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5468
-                    }
5469
-                }
5470
-            } else {
5471
-                // the table's rows existed. Use their values
5472
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5473
-                    if (! $field_obj->is_db_only_field()) {
5474
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5475
-                            $cols_n_values,
5476
-                            $field_obj->get_qualified_column(),
5477
-                            $field_obj->get_table_column()
5478
-                        );
5479
-                    }
5480
-                }
5481
-            }
5482
-        }
5483
-        return $this_model_fields_n_values;
5484
-    }
5485
-
5486
-
5487
-
5488
-    /**
5489
-     * @param $cols_n_values
5490
-     * @param $qualified_column
5491
-     * @param $regular_column
5492
-     * @return null
5493
-     */
5494
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5495
-    {
5496
-        $value = null;
5497
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5498
-        // does the field on the model relate to this column retrieved from the db?
5499
-        // or is it a db-only field? (not relating to the model)
5500
-        if (isset($cols_n_values[ $qualified_column ])) {
5501
-            $value = $cols_n_values[ $qualified_column ];
5502
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5503
-            $value = $cols_n_values[ $regular_column ];
5504
-        }
5505
-        return $value;
5506
-    }
5507
-
5508
-
5509
-
5510
-    /**
5511
-     * refresh_entity_map_from_db
5512
-     * Makes sure the model object in the entity map at $id assumes the values
5513
-     * of the database (opposite of EE_base_Class::save())
5514
-     *
5515
-     * @param int|string $id
5516
-     * @return EE_Base_Class
5517
-     * @throws EE_Error
5518
-     */
5519
-    public function refresh_entity_map_from_db($id)
5520
-    {
5521
-        $obj_in_map = $this->get_from_entity_map($id);
5522
-        if ($obj_in_map) {
5523
-            $wpdb_results = $this->_get_all_wpdb_results(
5524
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5525
-            );
5526
-            if ($wpdb_results && is_array($wpdb_results)) {
5527
-                $one_row = reset($wpdb_results);
5528
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5529
-                    $obj_in_map->set_from_db($field_name, $db_value);
5530
-                }
5531
-                // clear the cache of related model objects
5532
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5533
-                    $obj_in_map->clear_cache($relation_name, null, true);
5534
-                }
5535
-            }
5536
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5537
-            return $obj_in_map;
5538
-        }
5539
-        return $this->get_one_by_ID($id);
5540
-    }
5541
-
5542
-
5543
-
5544
-    /**
5545
-     * refresh_entity_map_with
5546
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5547
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5548
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5549
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5550
-     *
5551
-     * @param int|string    $id
5552
-     * @param EE_Base_Class $replacing_model_obj
5553
-     * @return \EE_Base_Class
5554
-     * @throws EE_Error
5555
-     */
5556
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5557
-    {
5558
-        $obj_in_map = $this->get_from_entity_map($id);
5559
-        if ($obj_in_map) {
5560
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5561
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5562
-                    $obj_in_map->set($field_name, $value);
5563
-                }
5564
-                // make the model object in the entity map's cache match the $replacing_model_obj
5565
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5566
-                    $obj_in_map->clear_cache($relation_name, null, true);
5567
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5568
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5569
-                    }
5570
-                }
5571
-            }
5572
-            return $obj_in_map;
5573
-        }
5574
-        $this->add_to_entity_map($replacing_model_obj);
5575
-        return $replacing_model_obj;
5576
-    }
5577
-
5578
-
5579
-
5580
-    /**
5581
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5582
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5583
-     * require_once($this->_getClassName().".class.php");
5584
-     *
5585
-     * @return string
5586
-     */
5587
-    private function _get_class_name()
5588
-    {
5589
-        return "EE_" . $this->get_this_model_name();
5590
-    }
5591
-
5592
-
5593
-
5594
-    /**
5595
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5596
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5597
-     * it would be 'Events'.
5598
-     *
5599
-     * @param int $quantity
5600
-     * @return string
5601
-     */
5602
-    public function item_name($quantity = 1)
5603
-    {
5604
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5605
-    }
5606
-
5607
-
5608
-
5609
-    /**
5610
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5611
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5612
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5613
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5614
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5615
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5616
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5617
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5618
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5619
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5620
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5621
-     *        return $previousReturnValue.$returnString;
5622
-     * }
5623
-     * require('EEM_Answer.model.php');
5624
-     * $answer=EEM_Answer::instance();
5625
-     * echo $answer->my_callback('monkeys',100);
5626
-     * //will output "you called my_callback! and passed args:monkeys,100"
5627
-     *
5628
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5629
-     * @param array  $args       array of original arguments passed to the function
5630
-     * @throws EE_Error
5631
-     * @return mixed whatever the plugin which calls add_filter decides
5632
-     */
5633
-    public function __call($methodName, $args)
5634
-    {
5635
-        $className = get_class($this);
5636
-        $tagName = "FHEE__{$className}__{$methodName}";
5637
-        if (! has_filter($tagName)) {
5638
-            throw new EE_Error(
5639
-                sprintf(
5640
-                    __(
5641
-                        'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5642
-                        'event_espresso'
5643
-                    ),
5644
-                    $methodName,
5645
-                    $className,
5646
-                    $tagName,
5647
-                    '<br />'
5648
-                )
5649
-            );
5650
-        }
5651
-        return apply_filters($tagName, null, $this, $args);
5652
-    }
5653
-
5654
-
5655
-
5656
-    /**
5657
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5658
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5659
-     *
5660
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5661
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5662
-     *                                                       the object's class name
5663
-     *                                                       or object's ID
5664
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5665
-     *                                                       exists in the database. If it does not, we add it
5666
-     * @throws EE_Error
5667
-     * @return EE_Base_Class
5668
-     */
5669
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5670
-    {
5671
-        $className = $this->_get_class_name();
5672
-        if ($base_class_obj_or_id instanceof $className) {
5673
-            $model_object = $base_class_obj_or_id;
5674
-        } else {
5675
-            $primary_key_field = $this->get_primary_key_field();
5676
-            if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5677
-                && (
5678
-                    is_int($base_class_obj_or_id)
5679
-                    || is_string($base_class_obj_or_id)
5680
-                )
5681
-            ) {
5682
-                // assume it's an ID.
5683
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5684
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5685
-            } elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5686
-                && is_string($base_class_obj_or_id)
5687
-            ) {
5688
-                // assume its a string representation of the object
5689
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5690
-            } else {
5691
-                throw new EE_Error(
5692
-                    sprintf(
5693
-                        __(
5694
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5695
-                            'event_espresso'
5696
-                        ),
5697
-                        $base_class_obj_or_id,
5698
-                        $this->_get_class_name(),
5699
-                        print_r($base_class_obj_or_id, true)
5700
-                    )
5701
-                );
5702
-            }
5703
-        }
5704
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5705
-            $model_object->save();
5706
-        }
5707
-        return $model_object;
5708
-    }
5709
-
5710
-
5711
-
5712
-    /**
5713
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5714
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5715
-     * returns it ID.
5716
-     *
5717
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5718
-     * @return int|string depending on the type of this model object's ID
5719
-     * @throws EE_Error
5720
-     */
5721
-    public function ensure_is_ID($base_class_obj_or_id)
5722
-    {
5723
-        $className = $this->_get_class_name();
5724
-        if ($base_class_obj_or_id instanceof $className) {
5725
-            /** @var $base_class_obj_or_id EE_Base_Class */
5726
-            $id = $base_class_obj_or_id->ID();
5727
-        } elseif (is_int($base_class_obj_or_id)) {
5728
-            // assume it's an ID
5729
-            $id = $base_class_obj_or_id;
5730
-        } elseif (is_string($base_class_obj_or_id)) {
5731
-            // assume its a string representation of the object
5732
-            $id = $base_class_obj_or_id;
5733
-        } else {
5734
-            throw new EE_Error(sprintf(
5735
-                __(
5736
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5737
-                    'event_espresso'
5738
-                ),
5739
-                $base_class_obj_or_id,
5740
-                $this->_get_class_name(),
5741
-                print_r($base_class_obj_or_id, true)
5742
-            ));
5743
-        }
5744
-        return $id;
5745
-    }
5746
-
5747
-
5748
-
5749
-    /**
5750
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5751
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5752
-     * been sanitized and converted into the appropriate domain.
5753
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5754
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5755
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5756
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5757
-     * $EVT = EEM_Event::instance(); $old_setting =
5758
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5759
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5760
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5761
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5762
-     *
5763
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5764
-     * @return void
5765
-     */
5766
-    public function assume_values_already_prepared_by_model_object(
5767
-        $values_already_prepared = self::not_prepared_by_model_object
5768
-    ) {
5769
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5770
-    }
5771
-
5772
-
5773
-
5774
-    /**
5775
-     * Read comments for assume_values_already_prepared_by_model_object()
5776
-     *
5777
-     * @return int
5778
-     */
5779
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5780
-    {
5781
-        return $this->_values_already_prepared_by_model_object;
5782
-    }
5783
-
5784
-
5785
-
5786
-    /**
5787
-     * Gets all the indexes on this model
5788
-     *
5789
-     * @return EE_Index[]
5790
-     */
5791
-    public function indexes()
5792
-    {
5793
-        return $this->_indexes;
5794
-    }
5795
-
5796
-
5797
-
5798
-    /**
5799
-     * Gets all the Unique Indexes on this model
5800
-     *
5801
-     * @return EE_Unique_Index[]
5802
-     */
5803
-    public function unique_indexes()
5804
-    {
5805
-        $unique_indexes = array();
5806
-        foreach ($this->_indexes as $name => $index) {
5807
-            if ($index instanceof EE_Unique_Index) {
5808
-                $unique_indexes [ $name ] = $index;
5809
-            }
5810
-        }
5811
-        return $unique_indexes;
5812
-    }
5813
-
5814
-
5815
-
5816
-    /**
5817
-     * Gets all the fields which, when combined, make the primary key.
5818
-     * This is usually just an array with 1 element (the primary key), but in cases
5819
-     * where there is no primary key, it's a combination of fields as defined
5820
-     * on a primary index
5821
-     *
5822
-     * @return EE_Model_Field_Base[] indexed by the field's name
5823
-     * @throws EE_Error
5824
-     */
5825
-    public function get_combined_primary_key_fields()
5826
-    {
5827
-        foreach ($this->indexes() as $index) {
5828
-            if ($index instanceof EE_Primary_Key_Index) {
5829
-                return $index->fields();
5830
-            }
5831
-        }
5832
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5833
-    }
5834
-
5835
-
5836
-
5837
-    /**
5838
-     * Used to build a primary key string (when the model has no primary key),
5839
-     * which can be used a unique string to identify this model object.
5840
-     *
5841
-     * @param array $cols_n_values keys are field names, values are their values
5842
-     * @return string
5843
-     * @throws EE_Error
5844
-     */
5845
-    public function get_index_primary_key_string($cols_n_values)
5846
-    {
5847
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5848
-            $cols_n_values,
5849
-            $this->get_combined_primary_key_fields()
5850
-        );
5851
-        return http_build_query($cols_n_values_for_primary_key_index);
5852
-    }
5853
-
5854
-
5855
-
5856
-    /**
5857
-     * Gets the field values from the primary key string
5858
-     *
5859
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5860
-     * @param string $index_primary_key_string
5861
-     * @return null|array
5862
-     * @throws EE_Error
5863
-     */
5864
-    public function parse_index_primary_key_string($index_primary_key_string)
5865
-    {
5866
-        $key_fields = $this->get_combined_primary_key_fields();
5867
-        // check all of them are in the $id
5868
-        $key_vals_in_combined_pk = array();
5869
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5870
-        foreach ($key_fields as $key_field_name => $field_obj) {
5871
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5872
-                return null;
5873
-            }
5874
-        }
5875
-        return $key_vals_in_combined_pk;
5876
-    }
5877
-
5878
-
5879
-
5880
-    /**
5881
-     * verifies that an array of key-value pairs for model fields has a key
5882
-     * for each field comprising the primary key index
5883
-     *
5884
-     * @param array $key_vals
5885
-     * @return boolean
5886
-     * @throws EE_Error
5887
-     */
5888
-    public function has_all_combined_primary_key_fields($key_vals)
5889
-    {
5890
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5891
-        foreach ($keys_it_should_have as $key) {
5892
-            if (! isset($key_vals[ $key ])) {
5893
-                return false;
5894
-            }
5895
-        }
5896
-        return true;
5897
-    }
5898
-
5899
-
5900
-
5901
-    /**
5902
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5903
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5904
-     *
5905
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5906
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5907
-     * @throws EE_Error
5908
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5909
-     *                                                              indexed)
5910
-     */
5911
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5912
-    {
5913
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5914
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5915
-        } elseif (is_array($model_object_or_attributes_array)) {
5916
-            $attributes_array = $model_object_or_attributes_array;
5917
-        } else {
5918
-            throw new EE_Error(sprintf(__(
5919
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5920
-                "event_espresso"
5921
-            ), $model_object_or_attributes_array));
5922
-        }
5923
-        // even copies obviously won't have the same ID, so remove the primary key
5924
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5925
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5926
-            unset($attributes_array[ $this->primary_key_name() ]);
5927
-        }
5928
-        if (isset($query_params[0])) {
5929
-            $query_params[0] = array_merge($attributes_array, $query_params);
5930
-        } else {
5931
-            $query_params[0] = $attributes_array;
5932
-        }
5933
-        return $this->get_all($query_params);
5934
-    }
5935
-
5936
-
5937
-
5938
-    /**
5939
-     * Gets the first copy we find. See get_all_copies for more details
5940
-     *
5941
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5942
-     * @param array $query_params
5943
-     * @return EE_Base_Class
5944
-     * @throws EE_Error
5945
-     */
5946
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5947
-    {
5948
-        if (! is_array($query_params)) {
5949
-            EE_Error::doing_it_wrong(
5950
-                'EEM_Base::get_one_copy',
5951
-                sprintf(
5952
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5953
-                    gettype($query_params)
5954
-                ),
5955
-                '4.6.0'
5956
-            );
5957
-            $query_params = array();
5958
-        }
5959
-        $query_params['limit'] = 1;
5960
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5961
-        if (is_array($copies)) {
5962
-            return array_shift($copies);
5963
-        }
5964
-        return null;
5965
-    }
5966
-
5967
-
5968
-
5969
-    /**
5970
-     * Updates the item with the specified id. Ignores default query parameters because
5971
-     * we have specified the ID, and its assumed we KNOW what we're doing
5972
-     *
5973
-     * @param array      $fields_n_values keys are field names, values are their new values
5974
-     * @param int|string $id              the value of the primary key to update
5975
-     * @return int number of rows updated
5976
-     * @throws EE_Error
5977
-     */
5978
-    public function update_by_ID($fields_n_values, $id)
5979
-    {
5980
-        $query_params = array(
5981
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5982
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5983
-        );
5984
-        return $this->update($fields_n_values, $query_params);
5985
-    }
5986
-
5987
-
5988
-
5989
-    /**
5990
-     * Changes an operator which was supplied to the models into one usable in SQL
5991
-     *
5992
-     * @param string $operator_supplied
5993
-     * @return string an operator which can be used in SQL
5994
-     * @throws EE_Error
5995
-     */
5996
-    private function _prepare_operator_for_sql($operator_supplied)
5997
-    {
5998
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5999
-            : null;
6000
-        if ($sql_operator) {
6001
-            return $sql_operator;
6002
-        }
6003
-        throw new EE_Error(
6004
-            sprintf(
6005
-                __(
6006
-                    "The operator '%s' is not in the list of valid operators: %s",
6007
-                    "event_espresso"
6008
-                ),
6009
-                $operator_supplied,
6010
-                implode(",", array_keys($this->_valid_operators))
6011
-            )
6012
-        );
6013
-    }
6014
-
6015
-
6016
-
6017
-    /**
6018
-     * Gets the valid operators
6019
-     * @return array keys are accepted strings, values are the SQL they are converted to
6020
-     */
6021
-    public function valid_operators()
6022
-    {
6023
-        return $this->_valid_operators;
6024
-    }
6025
-
6026
-
6027
-
6028
-    /**
6029
-     * Gets the between-style operators (take 2 arguments).
6030
-     * @return array keys are accepted strings, values are the SQL they are converted to
6031
-     */
6032
-    public function valid_between_style_operators()
6033
-    {
6034
-        return array_intersect(
6035
-            $this->valid_operators(),
6036
-            $this->_between_style_operators
6037
-        );
6038
-    }
6039
-
6040
-    /**
6041
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6042
-     * @return array keys are accepted strings, values are the SQL they are converted to
6043
-     */
6044
-    public function valid_like_style_operators()
6045
-    {
6046
-        return array_intersect(
6047
-            $this->valid_operators(),
6048
-            $this->_like_style_operators
6049
-        );
6050
-    }
6051
-
6052
-    /**
6053
-     * Gets the "in"-style operators
6054
-     * @return array keys are accepted strings, values are the SQL they are converted to
6055
-     */
6056
-    public function valid_in_style_operators()
6057
-    {
6058
-        return array_intersect(
6059
-            $this->valid_operators(),
6060
-            $this->_in_style_operators
6061
-        );
6062
-    }
6063
-
6064
-    /**
6065
-     * Gets the "null"-style operators (accept no arguments)
6066
-     * @return array keys are accepted strings, values are the SQL they are converted to
6067
-     */
6068
-    public function valid_null_style_operators()
6069
-    {
6070
-        return array_intersect(
6071
-            $this->valid_operators(),
6072
-            $this->_null_style_operators
6073
-        );
6074
-    }
6075
-
6076
-    /**
6077
-     * Gets an array where keys are the primary keys and values are their 'names'
6078
-     * (as determined by the model object's name() function, which is often overridden)
6079
-     *
6080
-     * @param array $query_params like get_all's
6081
-     * @return string[]
6082
-     * @throws EE_Error
6083
-     */
6084
-    public function get_all_names($query_params = array())
6085
-    {
6086
-        $objs = $this->get_all($query_params);
6087
-        $names = array();
6088
-        foreach ($objs as $obj) {
6089
-            $names[ $obj->ID() ] = $obj->name();
6090
-        }
6091
-        return $names;
6092
-    }
6093
-
6094
-
6095
-
6096
-    /**
6097
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6098
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6099
-     * this is duplicated effort and reduces efficiency) you would be better to use
6100
-     * array_keys() on $model_objects.
6101
-     *
6102
-     * @param \EE_Base_Class[] $model_objects
6103
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6104
-     *                                               in the returned array
6105
-     * @return array
6106
-     * @throws EE_Error
6107
-     */
6108
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6109
-    {
6110
-        if (! $this->has_primary_key_field()) {
6111
-            if (WP_DEBUG) {
6112
-                EE_Error::add_error(
6113
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6114
-                    __FILE__,
6115
-                    __FUNCTION__,
6116
-                    __LINE__
6117
-                );
6118
-            }
6119
-        }
6120
-        $IDs = array();
6121
-        foreach ($model_objects as $model_object) {
6122
-            $id = $model_object->ID();
6123
-            if (! $id) {
6124
-                if ($filter_out_empty_ids) {
6125
-                    continue;
6126
-                }
6127
-                if (WP_DEBUG) {
6128
-                    EE_Error::add_error(
6129
-                        __(
6130
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6131
-                            'event_espresso'
6132
-                        ),
6133
-                        __FILE__,
6134
-                        __FUNCTION__,
6135
-                        __LINE__
6136
-                    );
6137
-                }
6138
-            }
6139
-            $IDs[] = $id;
6140
-        }
6141
-        return $IDs;
6142
-    }
6143
-
6144
-
6145
-
6146
-    /**
6147
-     * Returns the string used in capabilities relating to this model. If there
6148
-     * are no capabilities that relate to this model returns false
6149
-     *
6150
-     * @return string|false
6151
-     */
6152
-    public function cap_slug()
6153
-    {
6154
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6155
-    }
6156
-
6157
-
6158
-
6159
-    /**
6160
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6161
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6162
-     * only returns the cap restrictions array in that context (ie, the array
6163
-     * at that key)
6164
-     *
6165
-     * @param string $context
6166
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6167
-     * @throws EE_Error
6168
-     */
6169
-    public function cap_restrictions($context = EEM_Base::caps_read)
6170
-    {
6171
-        EEM_Base::verify_is_valid_cap_context($context);
6172
-        // check if we ought to run the restriction generator first
6173
-        if (isset($this->_cap_restriction_generators[ $context ])
6174
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6175
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6176
-        ) {
6177
-            $this->_cap_restrictions[ $context ] = array_merge(
6178
-                $this->_cap_restrictions[ $context ],
6179
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6180
-            );
6181
-        }
6182
-        // and make sure we've finalized the construction of each restriction
6183
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6184
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6185
-                $where_conditions_obj->_finalize_construct($this);
6186
-            }
6187
-        }
6188
-        return $this->_cap_restrictions[ $context ];
6189
-    }
6190
-
6191
-
6192
-
6193
-    /**
6194
-     * Indicating whether or not this model thinks its a wp core model
6195
-     *
6196
-     * @return boolean
6197
-     */
6198
-    public function is_wp_core_model()
6199
-    {
6200
-        return $this->_wp_core_model;
6201
-    }
6202
-
6203
-
6204
-
6205
-    /**
6206
-     * Gets all the caps that are missing which impose a restriction on
6207
-     * queries made in this context
6208
-     *
6209
-     * @param string $context one of EEM_Base::caps_ constants
6210
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6211
-     * @throws EE_Error
6212
-     */
6213
-    public function caps_missing($context = EEM_Base::caps_read)
6214
-    {
6215
-        $missing_caps = array();
6216
-        $cap_restrictions = $this->cap_restrictions($context);
6217
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6218
-            if (! EE_Capabilities::instance()
6219
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6220
-            ) {
6221
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6222
-            }
6223
-        }
6224
-        return $missing_caps;
6225
-    }
6226
-
6227
-
6228
-
6229
-    /**
6230
-     * Gets the mapping from capability contexts to action strings used in capability names
6231
-     *
6232
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6233
-     * one of 'read', 'edit', or 'delete'
6234
-     */
6235
-    public function cap_contexts_to_cap_action_map()
6236
-    {
6237
-        return apply_filters(
6238
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6239
-            $this->_cap_contexts_to_cap_action_map,
6240
-            $this
6241
-        );
6242
-    }
6243
-
6244
-
6245
-
6246
-    /**
6247
-     * Gets the action string for the specified capability context
6248
-     *
6249
-     * @param string $context
6250
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6251
-     * @throws EE_Error
6252
-     */
6253
-    public function cap_action_for_context($context)
6254
-    {
6255
-        $mapping = $this->cap_contexts_to_cap_action_map();
6256
-        if (isset($mapping[ $context ])) {
6257
-            return $mapping[ $context ];
6258
-        }
6259
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6260
-            return $action;
6261
-        }
6262
-        throw new EE_Error(
6263
-            sprintf(
6264
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6265
-                $context,
6266
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6267
-            )
6268
-        );
6269
-    }
6270
-
6271
-
6272
-
6273
-    /**
6274
-     * Returns all the capability contexts which are valid when querying models
6275
-     *
6276
-     * @return array
6277
-     */
6278
-    public static function valid_cap_contexts()
6279
-    {
6280
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6281
-            self::caps_read,
6282
-            self::caps_read_admin,
6283
-            self::caps_edit,
6284
-            self::caps_delete,
6285
-        ));
6286
-    }
6287
-
6288
-
6289
-
6290
-    /**
6291
-     * Returns all valid options for 'default_where_conditions'
6292
-     *
6293
-     * @return array
6294
-     */
6295
-    public static function valid_default_where_conditions()
6296
-    {
6297
-        return array(
6298
-            EEM_Base::default_where_conditions_all,
6299
-            EEM_Base::default_where_conditions_this_only,
6300
-            EEM_Base::default_where_conditions_others_only,
6301
-            EEM_Base::default_where_conditions_minimum_all,
6302
-            EEM_Base::default_where_conditions_minimum_others,
6303
-            EEM_Base::default_where_conditions_none
6304
-        );
6305
-    }
6306
-
6307
-    // public static function default_where_conditions_full
6308
-    /**
6309
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6310
-     *
6311
-     * @param string $context
6312
-     * @return bool
6313
-     * @throws EE_Error
6314
-     */
6315
-    public static function verify_is_valid_cap_context($context)
6316
-    {
6317
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6318
-        if (in_array($context, $valid_cap_contexts)) {
6319
-            return true;
6320
-        }
6321
-        throw new EE_Error(
6322
-            sprintf(
6323
-                __(
6324
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6325
-                    'event_espresso'
6326
-                ),
6327
-                $context,
6328
-                'EEM_Base',
6329
-                implode(',', $valid_cap_contexts)
6330
-            )
6331
-        );
6332
-    }
6333
-
6334
-
6335
-
6336
-    /**
6337
-     * Clears all the models field caches. This is only useful when a sub-class
6338
-     * might have added a field or something and these caches might be invalidated
6339
-     */
6340
-    protected function _invalidate_field_caches()
6341
-    {
6342
-        $this->_cache_foreign_key_to_fields = array();
6343
-        $this->_cached_fields = null;
6344
-        $this->_cached_fields_non_db_only = null;
6345
-    }
6346
-
6347
-
6348
-
6349
-    /**
6350
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6351
-     * (eg "and", "or", "not").
6352
-     *
6353
-     * @return array
6354
-     */
6355
-    public function logic_query_param_keys()
6356
-    {
6357
-        return $this->_logic_query_param_keys;
6358
-    }
6359
-
6360
-
6361
-
6362
-    /**
6363
-     * Determines whether or not the where query param array key is for a logic query param.
6364
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6365
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6366
-     *
6367
-     * @param $query_param_key
6368
-     * @return bool
6369
-     */
6370
-    public function is_logic_query_param_key($query_param_key)
6371
-    {
6372
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6373
-            if ($query_param_key === $logic_query_param_key
6374
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6375
-            ) {
6376
-                return true;
6377
-            }
6378
-        }
6379
-        return false;
6380
-    }
3867
+		}
3868
+		return $null_friendly_where_conditions;
3869
+	}
3870
+
3871
+
3872
+
3873
+	/**
3874
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3875
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3876
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3877
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3878
+	 *
3879
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3880
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3881
+	 */
3882
+	private function _get_default_where_conditions($model_relation_path = null)
3883
+	{
3884
+		if ($this->_ignore_where_strategy) {
3885
+			return array();
3886
+		}
3887
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3888
+	}
3889
+
3890
+
3891
+
3892
+	/**
3893
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3894
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3895
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3896
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3897
+	 * Similar to _get_default_where_conditions
3898
+	 *
3899
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3900
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3901
+	 */
3902
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3903
+	{
3904
+		if ($this->_ignore_where_strategy) {
3905
+			return array();
3906
+		}
3907
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3908
+	}
3909
+
3910
+
3911
+
3912
+	/**
3913
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3914
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3915
+	 *
3916
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3917
+	 * @return string
3918
+	 * @throws EE_Error
3919
+	 */
3920
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3921
+	{
3922
+		$selects = $this->_get_columns_to_select_for_this_model();
3923
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3924
+			$name_of_other_model_included) {
3925
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3926
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3927
+			foreach ($other_model_selects as $key => $value) {
3928
+				$selects[] = $value;
3929
+			}
3930
+		}
3931
+		return implode(", ", $selects);
3932
+	}
3933
+
3934
+
3935
+
3936
+	/**
3937
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3938
+	 * So that's going to be the columns for all the fields on the model
3939
+	 *
3940
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3941
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3942
+	 */
3943
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3944
+	{
3945
+		$fields = $this->field_settings();
3946
+		$selects = array();
3947
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3948
+			$model_relation_chain,
3949
+			$this->get_this_model_name()
3950
+		);
3951
+		foreach ($fields as $field_obj) {
3952
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3953
+						 . $field_obj->get_table_alias()
3954
+						 . "."
3955
+						 . $field_obj->get_table_column()
3956
+						 . " AS '"
3957
+						 . $table_alias_with_model_relation_chain_prefix
3958
+						 . $field_obj->get_table_alias()
3959
+						 . "."
3960
+						 . $field_obj->get_table_column()
3961
+						 . "'";
3962
+		}
3963
+		// make sure we are also getting the PKs of each table
3964
+		$tables = $this->get_tables();
3965
+		if (count($tables) > 1) {
3966
+			foreach ($tables as $table_obj) {
3967
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3968
+									   . $table_obj->get_fully_qualified_pk_column();
3969
+				if (! in_array($qualified_pk_column, $selects)) {
3970
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3971
+				}
3972
+			}
3973
+		}
3974
+		return $selects;
3975
+	}
3976
+
3977
+
3978
+
3979
+	/**
3980
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3981
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3982
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3983
+	 * SQL for joining, and the data types
3984
+	 *
3985
+	 * @param null|string                 $original_query_param
3986
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3987
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3988
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3989
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3990
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3991
+	 *                                                          or 'Registration's
3992
+	 * @param string                      $original_query_param what it originally was (eg
3993
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3994
+	 *                                                          matches $query_param
3995
+	 * @throws EE_Error
3996
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3997
+	 */
3998
+	private function _extract_related_model_info_from_query_param(
3999
+		$query_param,
4000
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4001
+		$query_param_type,
4002
+		$original_query_param = null
4003
+	) {
4004
+		if ($original_query_param === null) {
4005
+			$original_query_param = $query_param;
4006
+		}
4007
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4008
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
4009
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
4010
+		$allow_fields = in_array(
4011
+			$query_param_type,
4012
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
4013
+			true
4014
+		);
4015
+		// check to see if we have a field on this model
4016
+		$this_model_fields = $this->field_settings(true);
4017
+		if (array_key_exists($query_param, $this_model_fields)) {
4018
+			if ($allow_fields) {
4019
+				return;
4020
+			}
4021
+			throw new EE_Error(
4022
+				sprintf(
4023
+					__(
4024
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4025
+						"event_espresso"
4026
+					),
4027
+					$query_param,
4028
+					get_class($this),
4029
+					$query_param_type,
4030
+					$original_query_param
4031
+				)
4032
+			);
4033
+		}
4034
+		// check if this is a special logic query param
4035
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4036
+			if ($allow_logic_query_params) {
4037
+				return;
4038
+			}
4039
+			throw new EE_Error(
4040
+				sprintf(
4041
+					__(
4042
+						'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4043
+						'event_espresso'
4044
+					),
4045
+					implode('", "', $this->_logic_query_param_keys),
4046
+					$query_param,
4047
+					get_class($this),
4048
+					'<br />',
4049
+					"\t"
4050
+					. ' $passed_in_query_info = <pre>'
4051
+					. print_r($passed_in_query_info, true)
4052
+					. '</pre>'
4053
+					. "\n\t"
4054
+					. ' $query_param_type = '
4055
+					. $query_param_type
4056
+					. "\n\t"
4057
+					. ' $original_query_param = '
4058
+					. $original_query_param
4059
+				)
4060
+			);
4061
+		}
4062
+		// check if it's a custom selection
4063
+		if ($this->_custom_selections instanceof CustomSelects
4064
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4065
+		) {
4066
+			return;
4067
+		}
4068
+		// check if has a model name at the beginning
4069
+		// and
4070
+		// check if it's a field on a related model
4071
+		if ($this->extractJoinModelFromQueryParams(
4072
+			$passed_in_query_info,
4073
+			$query_param,
4074
+			$original_query_param,
4075
+			$query_param_type
4076
+		)) {
4077
+			return;
4078
+		}
4079
+
4080
+		// ok so $query_param didn't start with a model name
4081
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4082
+		// it's wack, that's what it is
4083
+		throw new EE_Error(
4084
+			sprintf(
4085
+				esc_html__(
4086
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4087
+					"event_espresso"
4088
+				),
4089
+				$query_param,
4090
+				get_class($this),
4091
+				$query_param_type,
4092
+				$original_query_param
4093
+			)
4094
+		);
4095
+	}
4096
+
4097
+
4098
+	/**
4099
+	 * Extracts any possible join model information from the provided possible_join_string.
4100
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4101
+	 * parts that should be added to the query.
4102
+	 *
4103
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4104
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4105
+	 * @param null|string                 $original_query_param
4106
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4107
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4108
+	 * @return bool  returns true if a join was added and false if not.
4109
+	 * @throws EE_Error
4110
+	 */
4111
+	private function extractJoinModelFromQueryParams(
4112
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4113
+		$possible_join_string,
4114
+		$original_query_param,
4115
+		$query_parameter_type
4116
+	) {
4117
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4118
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4119
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4120
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4121
+				if ($possible_join_string === '') {
4122
+					// nothing left to $query_param
4123
+					// we should actually end in a field name, not a model like this!
4124
+					throw new EE_Error(
4125
+						sprintf(
4126
+							esc_html__(
4127
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4128
+								"event_espresso"
4129
+							),
4130
+							$possible_join_string,
4131
+							$query_parameter_type,
4132
+							get_class($this),
4133
+							$valid_related_model_name
4134
+						)
4135
+					);
4136
+				}
4137
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4138
+				$related_model_obj->_extract_related_model_info_from_query_param(
4139
+					$possible_join_string,
4140
+					$query_info_carrier,
4141
+					$query_parameter_type,
4142
+					$original_query_param
4143
+				);
4144
+				return true;
4145
+			}
4146
+			if ($possible_join_string === $valid_related_model_name) {
4147
+				$this->_add_join_to_model(
4148
+					$valid_related_model_name,
4149
+					$query_info_carrier,
4150
+					$original_query_param
4151
+				);
4152
+				return true;
4153
+			}
4154
+		}
4155
+		return false;
4156
+	}
4157
+
4158
+
4159
+	/**
4160
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4161
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4162
+	 * @throws EE_Error
4163
+	 */
4164
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4165
+	{
4166
+		if ($this->_custom_selections instanceof CustomSelects
4167
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4168
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4169
+			)
4170
+		) {
4171
+			$original_selects = $this->_custom_selections->originalSelects();
4172
+			foreach ($original_selects as $alias => $select_configuration) {
4173
+				$this->extractJoinModelFromQueryParams(
4174
+					$query_info_carrier,
4175
+					$select_configuration[0],
4176
+					$select_configuration[0],
4177
+					'custom_selects'
4178
+				);
4179
+			}
4180
+		}
4181
+	}
4182
+
4183
+
4184
+
4185
+	/**
4186
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4187
+	 * and store it on $passed_in_query_info
4188
+	 *
4189
+	 * @param string                      $model_name
4190
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4191
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4192
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4193
+	 *                                                          and are adding a join to 'Payment' with the original
4194
+	 *                                                          query param key
4195
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4196
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4197
+	 *                                                          Payment wants to add default query params so that it
4198
+	 *                                                          will know what models to prepend onto its default query
4199
+	 *                                                          params or in case it wants to rename tables (in case
4200
+	 *                                                          there are multiple joins to the same table)
4201
+	 * @return void
4202
+	 * @throws EE_Error
4203
+	 */
4204
+	private function _add_join_to_model(
4205
+		$model_name,
4206
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4207
+		$original_query_param
4208
+	) {
4209
+		$relation_obj = $this->related_settings_for($model_name);
4210
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4211
+		// check if the relation is HABTM, because then we're essentially doing two joins
4212
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4213
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4214
+			$join_model_obj = $relation_obj->get_join_model();
4215
+			// replace the model specified with the join model for this relation chain, whi
4216
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4217
+				$model_name,
4218
+				$join_model_obj->get_this_model_name(),
4219
+				$model_relation_chain
4220
+			);
4221
+			$passed_in_query_info->merge(
4222
+				new EE_Model_Query_Info_Carrier(
4223
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4224
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4225
+				)
4226
+			);
4227
+		}
4228
+		// now just join to the other table pointed to by the relation object, and add its data types
4229
+		$passed_in_query_info->merge(
4230
+			new EE_Model_Query_Info_Carrier(
4231
+				array($model_relation_chain => $model_name),
4232
+				$relation_obj->get_join_statement($model_relation_chain)
4233
+			)
4234
+		);
4235
+	}
4236
+
4237
+
4238
+
4239
+	/**
4240
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4241
+	 *
4242
+	 * @param array $where_params like EEM_Base::get_all
4243
+	 * @return string of SQL
4244
+	 * @throws EE_Error
4245
+	 */
4246
+	private function _construct_where_clause($where_params)
4247
+	{
4248
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4249
+		if ($SQL) {
4250
+			return " WHERE " . $SQL;
4251
+		}
4252
+		return '';
4253
+	}
4254
+
4255
+
4256
+
4257
+	/**
4258
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4259
+	 * and should be passed HAVING parameters, not WHERE parameters
4260
+	 *
4261
+	 * @param array $having_params
4262
+	 * @return string
4263
+	 * @throws EE_Error
4264
+	 */
4265
+	private function _construct_having_clause($having_params)
4266
+	{
4267
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4268
+		if ($SQL) {
4269
+			return " HAVING " . $SQL;
4270
+		}
4271
+		return '';
4272
+	}
4273
+
4274
+
4275
+	/**
4276
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4277
+	 * Event_Meta.meta_value = 'foo'))"
4278
+	 *
4279
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4280
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4281
+	 * @throws EE_Error
4282
+	 * @return string of SQL
4283
+	 */
4284
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4285
+	{
4286
+		$where_clauses = array();
4287
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4288
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4289
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4290
+				switch ($query_param) {
4291
+					case 'not':
4292
+					case 'NOT':
4293
+						$where_clauses[] = "! ("
4294
+										   . $this->_construct_condition_clause_recursive(
4295
+											   $op_and_value_or_sub_condition,
4296
+											   $glue
4297
+										   )
4298
+										   . ")";
4299
+						break;
4300
+					case 'and':
4301
+					case 'AND':
4302
+						$where_clauses[] = " ("
4303
+										   . $this->_construct_condition_clause_recursive(
4304
+											   $op_and_value_or_sub_condition,
4305
+											   ' AND '
4306
+										   )
4307
+										   . ")";
4308
+						break;
4309
+					case 'or':
4310
+					case 'OR':
4311
+						$where_clauses[] = " ("
4312
+										   . $this->_construct_condition_clause_recursive(
4313
+											   $op_and_value_or_sub_condition,
4314
+											   ' OR '
4315
+										   )
4316
+										   . ")";
4317
+						break;
4318
+				}
4319
+			} else {
4320
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4321
+				// if it's not a normal field, maybe it's a custom selection?
4322
+				if (! $field_obj) {
4323
+					if ($this->_custom_selections instanceof CustomSelects) {
4324
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4325
+					} else {
4326
+						throw new EE_Error(sprintf(__(
4327
+							"%s is neither a valid model field name, nor a custom selection",
4328
+							"event_espresso"
4329
+						), $query_param));
4330
+					}
4331
+				}
4332
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4333
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4334
+			}
4335
+		}
4336
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4337
+	}
4338
+
4339
+
4340
+
4341
+	/**
4342
+	 * Takes the input parameter and extract the table name (alias) and column name
4343
+	 *
4344
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4345
+	 * @throws EE_Error
4346
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4347
+	 */
4348
+	private function _deduce_column_name_from_query_param($query_param)
4349
+	{
4350
+		$field = $this->_deduce_field_from_query_param($query_param);
4351
+		if ($field) {
4352
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4353
+				$field->get_model_name(),
4354
+				$query_param
4355
+			);
4356
+			return $table_alias_prefix . $field->get_qualified_column();
4357
+		}
4358
+		if ($this->_custom_selections instanceof CustomSelects
4359
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4360
+		) {
4361
+			// maybe it's custom selection item?
4362
+			// if so, just use it as the "column name"
4363
+			return $query_param;
4364
+		}
4365
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4366
+			? implode(',', $this->_custom_selections->columnAliases())
4367
+			: '';
4368
+		throw new EE_Error(
4369
+			sprintf(
4370
+				__(
4371
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4372
+					"event_espresso"
4373
+				),
4374
+				$query_param,
4375
+				$custom_select_aliases
4376
+			)
4377
+		);
4378
+	}
4379
+
4380
+
4381
+
4382
+	/**
4383
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4384
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4385
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4386
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4387
+	 *
4388
+	 * @param string $condition_query_param_key
4389
+	 * @return string
4390
+	 */
4391
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4392
+	{
4393
+		$pos_of_star = strpos($condition_query_param_key, '*');
4394
+		if ($pos_of_star === false) {
4395
+			return $condition_query_param_key;
4396
+		}
4397
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4398
+		return $condition_query_param_sans_star;
4399
+	}
4400
+
4401
+
4402
+
4403
+	/**
4404
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4405
+	 *
4406
+	 * @param                            mixed      array | string    $op_and_value
4407
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4408
+	 * @throws EE_Error
4409
+	 * @return string
4410
+	 */
4411
+	private function _construct_op_and_value($op_and_value, $field_obj)
4412
+	{
4413
+		if (is_array($op_and_value)) {
4414
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4415
+			if (! $operator) {
4416
+				$php_array_like_string = array();
4417
+				foreach ($op_and_value as $key => $value) {
4418
+					$php_array_like_string[] = "$key=>$value";
4419
+				}
4420
+				throw new EE_Error(
4421
+					sprintf(
4422
+						__(
4423
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4424
+							"event_espresso"
4425
+						),
4426
+						implode(",", $php_array_like_string)
4427
+					)
4428
+				);
4429
+			}
4430
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4431
+		} else {
4432
+			$operator = '=';
4433
+			$value = $op_and_value;
4434
+		}
4435
+		// check to see if the value is actually another field
4436
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4437
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4438
+		}
4439
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4440
+			// in this case, the value should be an array, or at least a comma-separated list
4441
+			// it will need to handle a little differently
4442
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4443
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4444
+			return $operator . SP . $cleaned_value;
4445
+		}
4446
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4447
+			// the value should be an array with count of two.
4448
+			if (count($value) !== 2) {
4449
+				throw new EE_Error(
4450
+					sprintf(
4451
+						__(
4452
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4453
+							'event_espresso'
4454
+						),
4455
+						"BETWEEN"
4456
+					)
4457
+				);
4458
+			}
4459
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4460
+			return $operator . SP . $cleaned_value;
4461
+		}
4462
+		if (in_array($operator, $this->valid_null_style_operators())) {
4463
+			if ($value !== null) {
4464
+				throw new EE_Error(
4465
+					sprintf(
4466
+						__(
4467
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4468
+							"event_espresso"
4469
+						),
4470
+						$value,
4471
+						$operator
4472
+					)
4473
+				);
4474
+			}
4475
+			return $operator;
4476
+		}
4477
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4478
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4479
+			// remove other junk. So just treat it as a string.
4480
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4481
+		}
4482
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4483
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4484
+		}
4485
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4486
+			throw new EE_Error(
4487
+				sprintf(
4488
+					__(
4489
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4490
+						'event_espresso'
4491
+					),
4492
+					$operator,
4493
+					$operator
4494
+				)
4495
+			);
4496
+		}
4497
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4498
+			throw new EE_Error(
4499
+				sprintf(
4500
+					__(
4501
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4502
+						'event_espresso'
4503
+					),
4504
+					$operator,
4505
+					$operator
4506
+				)
4507
+			);
4508
+		}
4509
+		throw new EE_Error(
4510
+			sprintf(
4511
+				__(
4512
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4513
+					"event_espresso"
4514
+				),
4515
+				http_build_query($op_and_value)
4516
+			)
4517
+		);
4518
+	}
4519
+
4520
+
4521
+
4522
+	/**
4523
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4524
+	 *
4525
+	 * @param array                      $values
4526
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4527
+	 *                                              '%s'
4528
+	 * @return string
4529
+	 * @throws EE_Error
4530
+	 */
4531
+	public function _construct_between_value($values, $field_obj)
4532
+	{
4533
+		$cleaned_values = array();
4534
+		foreach ($values as $value) {
4535
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4536
+		}
4537
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4538
+	}
4539
+
4540
+
4541
+
4542
+	/**
4543
+	 * Takes an array or a comma-separated list of $values and cleans them
4544
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4545
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4546
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4547
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4548
+	 *
4549
+	 * @param mixed                      $values    array or comma-separated string
4550
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4551
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4552
+	 * @throws EE_Error
4553
+	 */
4554
+	public function _construct_in_value($values, $field_obj)
4555
+	{
4556
+		// check if the value is a CSV list
4557
+		if (is_string($values)) {
4558
+			// in which case, turn it into an array
4559
+			$values = explode(",", $values);
4560
+		}
4561
+		$cleaned_values = array();
4562
+		foreach ($values as $value) {
4563
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4564
+		}
4565
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4566
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4567
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4568
+		if (empty($cleaned_values)) {
4569
+			$all_fields = $this->field_settings();
4570
+			$a_field = array_shift($all_fields);
4571
+			$main_table = $this->_get_main_table();
4572
+			$cleaned_values[] = "SELECT "
4573
+								. $a_field->get_table_column()
4574
+								. " FROM "
4575
+								. $main_table->get_table_name()
4576
+								. " WHERE FALSE";
4577
+		}
4578
+		return "(" . implode(",", $cleaned_values) . ")";
4579
+	}
4580
+
4581
+
4582
+
4583
+	/**
4584
+	 * @param mixed                      $value
4585
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4586
+	 * @throws EE_Error
4587
+	 * @return false|null|string
4588
+	 */
4589
+	private function _wpdb_prepare_using_field($value, $field_obj)
4590
+	{
4591
+		/** @type WPDB $wpdb */
4592
+		global $wpdb;
4593
+		if ($field_obj instanceof EE_Model_Field_Base) {
4594
+			return $wpdb->prepare(
4595
+				$field_obj->get_wpdb_data_type(),
4596
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4597
+			);
4598
+		} //$field_obj should really just be a data type
4599
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4600
+			throw new EE_Error(
4601
+				sprintf(
4602
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4603
+					$field_obj,
4604
+					implode(",", $this->_valid_wpdb_data_types)
4605
+				)
4606
+			);
4607
+		}
4608
+		return $wpdb->prepare($field_obj, $value);
4609
+	}
4610
+
4611
+
4612
+
4613
+	/**
4614
+	 * Takes the input parameter and finds the model field that it indicates.
4615
+	 *
4616
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4617
+	 * @throws EE_Error
4618
+	 * @return EE_Model_Field_Base
4619
+	 */
4620
+	protected function _deduce_field_from_query_param($query_param_name)
4621
+	{
4622
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4623
+		// which will help us find the database table and column
4624
+		$query_param_parts = explode(".", $query_param_name);
4625
+		if (empty($query_param_parts)) {
4626
+			throw new EE_Error(sprintf(__(
4627
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4628
+				'event_espresso'
4629
+			), $query_param_name));
4630
+		}
4631
+		$number_of_parts = count($query_param_parts);
4632
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4633
+		if ($number_of_parts === 1) {
4634
+			$field_name = $last_query_param_part;
4635
+			$model_obj = $this;
4636
+		} else {// $number_of_parts >= 2
4637
+			// the last part is the column name, and there are only 2parts. therefore...
4638
+			$field_name = $last_query_param_part;
4639
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4640
+		}
4641
+		try {
4642
+			return $model_obj->field_settings_for($field_name);
4643
+		} catch (EE_Error $e) {
4644
+			return null;
4645
+		}
4646
+	}
4647
+
4648
+
4649
+
4650
+	/**
4651
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4652
+	 * alias and column which corresponds to it
4653
+	 *
4654
+	 * @param string $field_name
4655
+	 * @throws EE_Error
4656
+	 * @return string
4657
+	 */
4658
+	public function _get_qualified_column_for_field($field_name)
4659
+	{
4660
+		$all_fields = $this->field_settings();
4661
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4662
+		if ($field) {
4663
+			return $field->get_qualified_column();
4664
+		}
4665
+		throw new EE_Error(
4666
+			sprintf(
4667
+				__(
4668
+					"There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4669
+					'event_espresso'
4670
+				),
4671
+				$field_name,
4672
+				get_class($this)
4673
+			)
4674
+		);
4675
+	}
4676
+
4677
+
4678
+
4679
+	/**
4680
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4681
+	 * Example usage:
4682
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4683
+	 *      array(),
4684
+	 *      ARRAY_A,
4685
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4686
+	 *  );
4687
+	 * is equivalent to
4688
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4689
+	 * and
4690
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4691
+	 *      array(
4692
+	 *          array(
4693
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4694
+	 *          ),
4695
+	 *          ARRAY_A,
4696
+	 *          implode(
4697
+	 *              ', ',
4698
+	 *              array_merge(
4699
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4700
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4701
+	 *              )
4702
+	 *          )
4703
+	 *      )
4704
+	 *  );
4705
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4706
+	 *
4707
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4708
+	 *                                            and the one whose fields you are selecting for example: when querying
4709
+	 *                                            tickets model and selecting fields from the tickets model you would
4710
+	 *                                            leave this parameter empty, because no models are needed to join
4711
+	 *                                            between the queried model and the selected one. Likewise when
4712
+	 *                                            querying the datetime model and selecting fields from the tickets
4713
+	 *                                            model, it would also be left empty, because there is a direct
4714
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4715
+	 *                                            them together. However, when querying from the event model and
4716
+	 *                                            selecting fields from the ticket model, you should provide the string
4717
+	 *                                            'Datetime', indicating that the event model must first join to the
4718
+	 *                                            datetime model in order to find its relation to ticket model.
4719
+	 *                                            Also, when querying from the venue model and selecting fields from
4720
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4721
+	 *                                            indicating you need to join the venue model to the event model,
4722
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4723
+	 *                                            This string is used to deduce the prefix that gets added onto the
4724
+	 *                                            models' tables qualified columns
4725
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4726
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4727
+	 *                                            qualified column names
4728
+	 * @return array|string
4729
+	 */
4730
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4731
+	{
4732
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4733
+		$qualified_columns = array();
4734
+		foreach ($this->field_settings() as $field_name => $field) {
4735
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4736
+		}
4737
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4738
+	}
4739
+
4740
+
4741
+
4742
+	/**
4743
+	 * constructs the select use on special limit joins
4744
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4745
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4746
+	 * (as that is typically where the limits would be set).
4747
+	 *
4748
+	 * @param  string       $table_alias The table the select is being built for
4749
+	 * @param  mixed|string $limit       The limit for this select
4750
+	 * @return string                The final select join element for the query.
4751
+	 */
4752
+	public function _construct_limit_join_select($table_alias, $limit)
4753
+	{
4754
+		$SQL = '';
4755
+		foreach ($this->_tables as $table_obj) {
4756
+			if ($table_obj instanceof EE_Primary_Table) {
4757
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4758
+					? $table_obj->get_select_join_limit($limit)
4759
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4760
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4761
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4762
+					? $table_obj->get_select_join_limit_join($limit)
4763
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4764
+			}
4765
+		}
4766
+		return $SQL;
4767
+	}
4768
+
4769
+
4770
+
4771
+	/**
4772
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4773
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4774
+	 *
4775
+	 * @return string SQL
4776
+	 * @throws EE_Error
4777
+	 */
4778
+	public function _construct_internal_join()
4779
+	{
4780
+		$SQL = $this->_get_main_table()->get_table_sql();
4781
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4782
+		return $SQL;
4783
+	}
4784
+
4785
+
4786
+
4787
+	/**
4788
+	 * Constructs the SQL for joining all the tables on this model.
4789
+	 * Normally $alias should be the primary table's alias, but in cases where
4790
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4791
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4792
+	 * alias, this will construct SQL like:
4793
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4794
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4795
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4796
+	 *
4797
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4798
+	 * @return string
4799
+	 */
4800
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4801
+	{
4802
+		$SQL = '';
4803
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4804
+		foreach ($this->_tables as $table_obj) {
4805
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4806
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4807
+					// so we're joining to this table, meaning the table is already in
4808
+					// the FROM statement, BUT the primary table isn't. So we want
4809
+					// to add the inverse join sql
4810
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4811
+				} else {
4812
+					// just add a regular JOIN to this table from the primary table
4813
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4814
+				}
4815
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4816
+		}
4817
+		return $SQL;
4818
+	}
4819
+
4820
+
4821
+
4822
+	/**
4823
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4824
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4825
+	 * their data type (eg, '%s', '%d', etc)
4826
+	 *
4827
+	 * @return array
4828
+	 */
4829
+	public function _get_data_types()
4830
+	{
4831
+		$data_types = array();
4832
+		foreach ($this->field_settings() as $field_obj) {
4833
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4834
+			/** @var $field_obj EE_Model_Field_Base */
4835
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4836
+		}
4837
+		return $data_types;
4838
+	}
4839
+
4840
+
4841
+
4842
+	/**
4843
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4844
+	 *
4845
+	 * @param string $model_name
4846
+	 * @throws EE_Error
4847
+	 * @return EEM_Base
4848
+	 */
4849
+	public function get_related_model_obj($model_name)
4850
+	{
4851
+		$model_classname = "EEM_" . $model_name;
4852
+		if (! class_exists($model_classname)) {
4853
+			throw new EE_Error(sprintf(__(
4854
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4855
+				'event_espresso'
4856
+			), $model_name, $model_classname));
4857
+		}
4858
+		return call_user_func($model_classname . "::instance");
4859
+	}
4860
+
4861
+
4862
+
4863
+	/**
4864
+	 * Returns the array of EE_ModelRelations for this model.
4865
+	 *
4866
+	 * @return EE_Model_Relation_Base[]
4867
+	 */
4868
+	public function relation_settings()
4869
+	{
4870
+		return $this->_model_relations;
4871
+	}
4872
+
4873
+
4874
+
4875
+	/**
4876
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4877
+	 * because without THOSE models, this model probably doesn't have much purpose.
4878
+	 * (Eg, without an event, datetimes have little purpose.)
4879
+	 *
4880
+	 * @return EE_Belongs_To_Relation[]
4881
+	 */
4882
+	public function belongs_to_relations()
4883
+	{
4884
+		$belongs_to_relations = array();
4885
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4886
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4887
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4888
+			}
4889
+		}
4890
+		return $belongs_to_relations;
4891
+	}
4892
+
4893
+
4894
+
4895
+	/**
4896
+	 * Returns the specified EE_Model_Relation, or throws an exception
4897
+	 *
4898
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4899
+	 * @throws EE_Error
4900
+	 * @return EE_Model_Relation_Base
4901
+	 */
4902
+	public function related_settings_for($relation_name)
4903
+	{
4904
+		$relatedModels = $this->relation_settings();
4905
+		if (! array_key_exists($relation_name, $relatedModels)) {
4906
+			throw new EE_Error(
4907
+				sprintf(
4908
+					__(
4909
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4910
+						'event_espresso'
4911
+					),
4912
+					$relation_name,
4913
+					$this->_get_class_name(),
4914
+					implode(', ', array_keys($relatedModels))
4915
+				)
4916
+			);
4917
+		}
4918
+		return $relatedModels[ $relation_name ];
4919
+	}
4920
+
4921
+
4922
+
4923
+	/**
4924
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4925
+	 * fields
4926
+	 *
4927
+	 * @param string $fieldName
4928
+	 * @param boolean $include_db_only_fields
4929
+	 * @throws EE_Error
4930
+	 * @return EE_Model_Field_Base
4931
+	 */
4932
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4933
+	{
4934
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4935
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4936
+			throw new EE_Error(sprintf(
4937
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4938
+				$fieldName,
4939
+				get_class($this)
4940
+			));
4941
+		}
4942
+		return $fieldSettings[ $fieldName ];
4943
+	}
4944
+
4945
+
4946
+
4947
+	/**
4948
+	 * Checks if this field exists on this model
4949
+	 *
4950
+	 * @param string $fieldName a key in the model's _field_settings array
4951
+	 * @return boolean
4952
+	 */
4953
+	public function has_field($fieldName)
4954
+	{
4955
+		$fieldSettings = $this->field_settings(true);
4956
+		if (isset($fieldSettings[ $fieldName ])) {
4957
+			return true;
4958
+		}
4959
+		return false;
4960
+	}
4961
+
4962
+
4963
+
4964
+	/**
4965
+	 * Returns whether or not this model has a relation to the specified model
4966
+	 *
4967
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4968
+	 * @return boolean
4969
+	 */
4970
+	public function has_relation($relation_name)
4971
+	{
4972
+		$relations = $this->relation_settings();
4973
+		if (isset($relations[ $relation_name ])) {
4974
+			return true;
4975
+		}
4976
+		return false;
4977
+	}
4978
+
4979
+
4980
+
4981
+	/**
4982
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4983
+	 * Eg, on EE_Answer that would be ANS_ID field object
4984
+	 *
4985
+	 * @param $field_obj
4986
+	 * @return boolean
4987
+	 */
4988
+	public function is_primary_key_field($field_obj)
4989
+	{
4990
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4991
+	}
4992
+
4993
+
4994
+
4995
+	/**
4996
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4997
+	 * Eg, on EE_Answer that would be ANS_ID field object
4998
+	 *
4999
+	 * @return EE_Model_Field_Base
5000
+	 * @throws EE_Error
5001
+	 */
5002
+	public function get_primary_key_field()
5003
+	{
5004
+		if ($this->_primary_key_field === null) {
5005
+			foreach ($this->field_settings(true) as $field_obj) {
5006
+				if ($this->is_primary_key_field($field_obj)) {
5007
+					$this->_primary_key_field = $field_obj;
5008
+					break;
5009
+				}
5010
+			}
5011
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5012
+				throw new EE_Error(sprintf(
5013
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
5014
+					get_class($this)
5015
+				));
5016
+			}
5017
+		}
5018
+		return $this->_primary_key_field;
5019
+	}
5020
+
5021
+
5022
+
5023
+	/**
5024
+	 * Returns whether or not not there is a primary key on this model.
5025
+	 * Internally does some caching.
5026
+	 *
5027
+	 * @return boolean
5028
+	 */
5029
+	public function has_primary_key_field()
5030
+	{
5031
+		if ($this->_has_primary_key_field === null) {
5032
+			try {
5033
+				$this->get_primary_key_field();
5034
+				$this->_has_primary_key_field = true;
5035
+			} catch (EE_Error $e) {
5036
+				$this->_has_primary_key_field = false;
5037
+			}
5038
+		}
5039
+		return $this->_has_primary_key_field;
5040
+	}
5041
+
5042
+
5043
+
5044
+	/**
5045
+	 * Finds the first field of type $field_class_name.
5046
+	 *
5047
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5048
+	 *                                 EE_Foreign_Key_Field, etc
5049
+	 * @return EE_Model_Field_Base or null if none is found
5050
+	 */
5051
+	public function get_a_field_of_type($field_class_name)
5052
+	{
5053
+		foreach ($this->field_settings() as $field) {
5054
+			if ($field instanceof $field_class_name) {
5055
+				return $field;
5056
+			}
5057
+		}
5058
+		return null;
5059
+	}
5060
+
5061
+
5062
+
5063
+	/**
5064
+	 * Gets a foreign key field pointing to model.
5065
+	 *
5066
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5067
+	 * @return EE_Foreign_Key_Field_Base
5068
+	 * @throws EE_Error
5069
+	 */
5070
+	public function get_foreign_key_to($model_name)
5071
+	{
5072
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5073
+			foreach ($this->field_settings() as $field) {
5074
+				if ($field instanceof EE_Foreign_Key_Field_Base
5075
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5076
+				) {
5077
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5078
+					break;
5079
+				}
5080
+			}
5081
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5082
+				throw new EE_Error(sprintf(__(
5083
+					"There is no foreign key field pointing to model %s on model %s",
5084
+					'event_espresso'
5085
+				), $model_name, get_class($this)));
5086
+			}
5087
+		}
5088
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5089
+	}
5090
+
5091
+
5092
+
5093
+	/**
5094
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5095
+	 *
5096
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5097
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5098
+	 *                            Either one works
5099
+	 * @return string
5100
+	 */
5101
+	public function get_table_for_alias($table_alias)
5102
+	{
5103
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5104
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5105
+	}
5106
+
5107
+
5108
+
5109
+	/**
5110
+	 * Returns a flat array of all field son this model, instead of organizing them
5111
+	 * by table_alias as they are in the constructor.
5112
+	 *
5113
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5114
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5115
+	 */
5116
+	public function field_settings($include_db_only_fields = false)
5117
+	{
5118
+		if ($include_db_only_fields) {
5119
+			if ($this->_cached_fields === null) {
5120
+				$this->_cached_fields = array();
5121
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5122
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5123
+						$this->_cached_fields[ $field_name ] = $field_obj;
5124
+					}
5125
+				}
5126
+			}
5127
+			return $this->_cached_fields;
5128
+		}
5129
+		if ($this->_cached_fields_non_db_only === null) {
5130
+			$this->_cached_fields_non_db_only = array();
5131
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5132
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5133
+					/** @var $field_obj EE_Model_Field_Base */
5134
+					if (! $field_obj->is_db_only_field()) {
5135
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5136
+					}
5137
+				}
5138
+			}
5139
+		}
5140
+		return $this->_cached_fields_non_db_only;
5141
+	}
5142
+
5143
+
5144
+
5145
+	/**
5146
+	 *        cycle though array of attendees and create objects out of each item
5147
+	 *
5148
+	 * @access        private
5149
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5150
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5151
+	 *                           numerically indexed)
5152
+	 * @throws EE_Error
5153
+	 */
5154
+	protected function _create_objects($rows = array())
5155
+	{
5156
+		$array_of_objects = array();
5157
+		if (empty($rows)) {
5158
+			return array();
5159
+		}
5160
+		$count_if_model_has_no_primary_key = 0;
5161
+		$has_primary_key = $this->has_primary_key_field();
5162
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5163
+		foreach ((array) $rows as $row) {
5164
+			if (empty($row)) {
5165
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5166
+				return array();
5167
+			}
5168
+			// check if we've already set this object in the results array,
5169
+			// in which case there's no need to process it further (again)
5170
+			if ($has_primary_key) {
5171
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5172
+					$row,
5173
+					$primary_key_field->get_qualified_column(),
5174
+					$primary_key_field->get_table_column()
5175
+				);
5176
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5177
+					continue;
5178
+				}
5179
+			}
5180
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5181
+			if (! $classInstance) {
5182
+				throw new EE_Error(
5183
+					sprintf(
5184
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5185
+						$this->get_this_model_name(),
5186
+						http_build_query($row)
5187
+					)
5188
+				);
5189
+			}
5190
+			// set the timezone on the instantiated objects
5191
+			$classInstance->set_timezone($this->_timezone);
5192
+			// make sure if there is any timezone setting present that we set the timezone for the object
5193
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5194
+			$array_of_objects[ $key ] = $classInstance;
5195
+			// also, for all the relations of type BelongsTo, see if we can cache
5196
+			// those related models
5197
+			// (we could do this for other relations too, but if there are conditions
5198
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5199
+			// so it requires a little more thought than just caching them immediately...)
5200
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5201
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5202
+					// check if this model's INFO is present. If so, cache it on the model
5203
+					$other_model = $relation_obj->get_other_model();
5204
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5205
+					// if we managed to make a model object from the results, cache it on the main model object
5206
+					if ($other_model_obj_maybe) {
5207
+						// set timezone on these other model objects if they are present
5208
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5209
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5210
+					}
5211
+				}
5212
+			}
5213
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5214
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5215
+			// the field in the CustomSelects object
5216
+			if ($this->_custom_selections instanceof CustomSelects) {
5217
+				$classInstance->setCustomSelectsValues(
5218
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5219
+				);
5220
+			}
5221
+		}
5222
+		return $array_of_objects;
5223
+	}
5224
+
5225
+
5226
+	/**
5227
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5228
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5229
+	 *
5230
+	 * @param array $db_results_row
5231
+	 * @return array
5232
+	 */
5233
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5234
+	{
5235
+		$results = array();
5236
+		if ($this->_custom_selections instanceof CustomSelects) {
5237
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5238
+				if (isset($db_results_row[ $alias ])) {
5239
+					$results[ $alias ] = $this->convertValueToDataType(
5240
+						$db_results_row[ $alias ],
5241
+						$this->_custom_selections->getDataTypeForAlias($alias)
5242
+					);
5243
+				}
5244
+			}
5245
+		}
5246
+		return $results;
5247
+	}
5248
+
5249
+
5250
+	/**
5251
+	 * This will set the value for the given alias
5252
+	 * @param string $value
5253
+	 * @param string $datatype (one of %d, %s, %f)
5254
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5255
+	 */
5256
+	protected function convertValueToDataType($value, $datatype)
5257
+	{
5258
+		switch ($datatype) {
5259
+			case '%f':
5260
+				return (float) $value;
5261
+			case '%d':
5262
+				return (int) $value;
5263
+			default:
5264
+				return (string) $value;
5265
+		}
5266
+	}
5267
+
5268
+
5269
+	/**
5270
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5271
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5272
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5273
+	 * object (as set in the model_field!).
5274
+	 *
5275
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5276
+	 */
5277
+	public function create_default_object()
5278
+	{
5279
+		$this_model_fields_and_values = array();
5280
+		// setup the row using default values;
5281
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5282
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5283
+		}
5284
+		$className = $this->_get_class_name();
5285
+		$classInstance = EE_Registry::instance()
5286
+									->load_class($className, array($this_model_fields_and_values), false, false);
5287
+		return $classInstance;
5288
+	}
5289
+
5290
+
5291
+
5292
+	/**
5293
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5294
+	 *                             or an stdClass where each property is the name of a column,
5295
+	 * @return EE_Base_Class
5296
+	 * @throws EE_Error
5297
+	 */
5298
+	public function instantiate_class_from_array_or_object($cols_n_values)
5299
+	{
5300
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5301
+			$cols_n_values = get_object_vars($cols_n_values);
5302
+		}
5303
+		$primary_key = null;
5304
+		// make sure the array only has keys that are fields/columns on this model
5305
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5306
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5307
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5308
+		}
5309
+		$className = $this->_get_class_name();
5310
+		// check we actually found results that we can use to build our model object
5311
+		// if not, return null
5312
+		if ($this->has_primary_key_field()) {
5313
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5314
+				return null;
5315
+			}
5316
+		} elseif ($this->unique_indexes()) {
5317
+			$first_column = reset($this_model_fields_n_values);
5318
+			if (empty($first_column)) {
5319
+				return null;
5320
+			}
5321
+		}
5322
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5323
+		if ($primary_key) {
5324
+			$classInstance = $this->get_from_entity_map($primary_key);
5325
+			if (! $classInstance) {
5326
+				$classInstance = EE_Registry::instance()
5327
+											->load_class(
5328
+												$className,
5329
+												array($this_model_fields_n_values, $this->_timezone),
5330
+												true,
5331
+												false
5332
+											);
5333
+				// add this new object to the entity map
5334
+				$classInstance = $this->add_to_entity_map($classInstance);
5335
+			}
5336
+		} else {
5337
+			$classInstance = EE_Registry::instance()
5338
+										->load_class(
5339
+											$className,
5340
+											array($this_model_fields_n_values, $this->_timezone),
5341
+											true,
5342
+											false
5343
+										);
5344
+		}
5345
+		return $classInstance;
5346
+	}
5347
+
5348
+
5349
+
5350
+	/**
5351
+	 * Gets the model object from the  entity map if it exists
5352
+	 *
5353
+	 * @param int|string $id the ID of the model object
5354
+	 * @return EE_Base_Class
5355
+	 */
5356
+	public function get_from_entity_map($id)
5357
+	{
5358
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5359
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5360
+	}
5361
+
5362
+
5363
+
5364
+	/**
5365
+	 * add_to_entity_map
5366
+	 * Adds the object to the model's entity mappings
5367
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5368
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5369
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5370
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5371
+	 *        then this method should be called immediately after the update query
5372
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5373
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5374
+	 *
5375
+	 * @param    EE_Base_Class $object
5376
+	 * @throws EE_Error
5377
+	 * @return \EE_Base_Class
5378
+	 */
5379
+	public function add_to_entity_map(EE_Base_Class $object)
5380
+	{
5381
+		$className = $this->_get_class_name();
5382
+		if (! $object instanceof $className) {
5383
+			throw new EE_Error(sprintf(
5384
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5385
+				is_object($object) ? get_class($object) : $object,
5386
+				$className
5387
+			));
5388
+		}
5389
+		/** @var $object EE_Base_Class */
5390
+		if (! $object->ID()) {
5391
+			throw new EE_Error(sprintf(__(
5392
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5393
+				"event_espresso"
5394
+			), get_class($this)));
5395
+		}
5396
+		// double check it's not already there
5397
+		$classInstance = $this->get_from_entity_map($object->ID());
5398
+		if ($classInstance) {
5399
+			return $classInstance;
5400
+		}
5401
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5402
+		return $object;
5403
+	}
5404
+
5405
+
5406
+
5407
+	/**
5408
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5409
+	 * if no identifier is provided, then the entire entity map is emptied
5410
+	 *
5411
+	 * @param int|string $id the ID of the model object
5412
+	 * @return boolean
5413
+	 */
5414
+	public function clear_entity_map($id = null)
5415
+	{
5416
+		if (empty($id)) {
5417
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5418
+			return true;
5419
+		}
5420
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5421
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5422
+			return true;
5423
+		}
5424
+		return false;
5425
+	}
5426
+
5427
+
5428
+
5429
+	/**
5430
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5431
+	 * Given an array where keys are column (or column alias) names and values,
5432
+	 * returns an array of their corresponding field names and database values
5433
+	 *
5434
+	 * @param array $cols_n_values
5435
+	 * @return array
5436
+	 */
5437
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5438
+	{
5439
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5440
+	}
5441
+
5442
+
5443
+
5444
+	/**
5445
+	 * _deduce_fields_n_values_from_cols_n_values
5446
+	 * Given an array where keys are column (or column alias) names and values,
5447
+	 * returns an array of their corresponding field names and database values
5448
+	 *
5449
+	 * @param string $cols_n_values
5450
+	 * @return array
5451
+	 */
5452
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5453
+	{
5454
+		$this_model_fields_n_values = array();
5455
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5456
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5457
+				$cols_n_values,
5458
+				$table_obj->get_fully_qualified_pk_column(),
5459
+				$table_obj->get_pk_column()
5460
+			);
5461
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5462
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5463
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5464
+					if (! $field_obj->is_db_only_field()) {
5465
+						// prepare field as if its coming from db
5466
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5467
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5468
+					}
5469
+				}
5470
+			} else {
5471
+				// the table's rows existed. Use their values
5472
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5473
+					if (! $field_obj->is_db_only_field()) {
5474
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5475
+							$cols_n_values,
5476
+							$field_obj->get_qualified_column(),
5477
+							$field_obj->get_table_column()
5478
+						);
5479
+					}
5480
+				}
5481
+			}
5482
+		}
5483
+		return $this_model_fields_n_values;
5484
+	}
5485
+
5486
+
5487
+
5488
+	/**
5489
+	 * @param $cols_n_values
5490
+	 * @param $qualified_column
5491
+	 * @param $regular_column
5492
+	 * @return null
5493
+	 */
5494
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5495
+	{
5496
+		$value = null;
5497
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5498
+		// does the field on the model relate to this column retrieved from the db?
5499
+		// or is it a db-only field? (not relating to the model)
5500
+		if (isset($cols_n_values[ $qualified_column ])) {
5501
+			$value = $cols_n_values[ $qualified_column ];
5502
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5503
+			$value = $cols_n_values[ $regular_column ];
5504
+		}
5505
+		return $value;
5506
+	}
5507
+
5508
+
5509
+
5510
+	/**
5511
+	 * refresh_entity_map_from_db
5512
+	 * Makes sure the model object in the entity map at $id assumes the values
5513
+	 * of the database (opposite of EE_base_Class::save())
5514
+	 *
5515
+	 * @param int|string $id
5516
+	 * @return EE_Base_Class
5517
+	 * @throws EE_Error
5518
+	 */
5519
+	public function refresh_entity_map_from_db($id)
5520
+	{
5521
+		$obj_in_map = $this->get_from_entity_map($id);
5522
+		if ($obj_in_map) {
5523
+			$wpdb_results = $this->_get_all_wpdb_results(
5524
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5525
+			);
5526
+			if ($wpdb_results && is_array($wpdb_results)) {
5527
+				$one_row = reset($wpdb_results);
5528
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5529
+					$obj_in_map->set_from_db($field_name, $db_value);
5530
+				}
5531
+				// clear the cache of related model objects
5532
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5533
+					$obj_in_map->clear_cache($relation_name, null, true);
5534
+				}
5535
+			}
5536
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5537
+			return $obj_in_map;
5538
+		}
5539
+		return $this->get_one_by_ID($id);
5540
+	}
5541
+
5542
+
5543
+
5544
+	/**
5545
+	 * refresh_entity_map_with
5546
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5547
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5548
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5549
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5550
+	 *
5551
+	 * @param int|string    $id
5552
+	 * @param EE_Base_Class $replacing_model_obj
5553
+	 * @return \EE_Base_Class
5554
+	 * @throws EE_Error
5555
+	 */
5556
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5557
+	{
5558
+		$obj_in_map = $this->get_from_entity_map($id);
5559
+		if ($obj_in_map) {
5560
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5561
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5562
+					$obj_in_map->set($field_name, $value);
5563
+				}
5564
+				// make the model object in the entity map's cache match the $replacing_model_obj
5565
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5566
+					$obj_in_map->clear_cache($relation_name, null, true);
5567
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5568
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5569
+					}
5570
+				}
5571
+			}
5572
+			return $obj_in_map;
5573
+		}
5574
+		$this->add_to_entity_map($replacing_model_obj);
5575
+		return $replacing_model_obj;
5576
+	}
5577
+
5578
+
5579
+
5580
+	/**
5581
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5582
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5583
+	 * require_once($this->_getClassName().".class.php");
5584
+	 *
5585
+	 * @return string
5586
+	 */
5587
+	private function _get_class_name()
5588
+	{
5589
+		return "EE_" . $this->get_this_model_name();
5590
+	}
5591
+
5592
+
5593
+
5594
+	/**
5595
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5596
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5597
+	 * it would be 'Events'.
5598
+	 *
5599
+	 * @param int $quantity
5600
+	 * @return string
5601
+	 */
5602
+	public function item_name($quantity = 1)
5603
+	{
5604
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5605
+	}
5606
+
5607
+
5608
+
5609
+	/**
5610
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5611
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5612
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5613
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5614
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5615
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5616
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5617
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5618
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5619
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5620
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5621
+	 *        return $previousReturnValue.$returnString;
5622
+	 * }
5623
+	 * require('EEM_Answer.model.php');
5624
+	 * $answer=EEM_Answer::instance();
5625
+	 * echo $answer->my_callback('monkeys',100);
5626
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5627
+	 *
5628
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5629
+	 * @param array  $args       array of original arguments passed to the function
5630
+	 * @throws EE_Error
5631
+	 * @return mixed whatever the plugin which calls add_filter decides
5632
+	 */
5633
+	public function __call($methodName, $args)
5634
+	{
5635
+		$className = get_class($this);
5636
+		$tagName = "FHEE__{$className}__{$methodName}";
5637
+		if (! has_filter($tagName)) {
5638
+			throw new EE_Error(
5639
+				sprintf(
5640
+					__(
5641
+						'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5642
+						'event_espresso'
5643
+					),
5644
+					$methodName,
5645
+					$className,
5646
+					$tagName,
5647
+					'<br />'
5648
+				)
5649
+			);
5650
+		}
5651
+		return apply_filters($tagName, null, $this, $args);
5652
+	}
5653
+
5654
+
5655
+
5656
+	/**
5657
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5658
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5659
+	 *
5660
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5661
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5662
+	 *                                                       the object's class name
5663
+	 *                                                       or object's ID
5664
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5665
+	 *                                                       exists in the database. If it does not, we add it
5666
+	 * @throws EE_Error
5667
+	 * @return EE_Base_Class
5668
+	 */
5669
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5670
+	{
5671
+		$className = $this->_get_class_name();
5672
+		if ($base_class_obj_or_id instanceof $className) {
5673
+			$model_object = $base_class_obj_or_id;
5674
+		} else {
5675
+			$primary_key_field = $this->get_primary_key_field();
5676
+			if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5677
+				&& (
5678
+					is_int($base_class_obj_or_id)
5679
+					|| is_string($base_class_obj_or_id)
5680
+				)
5681
+			) {
5682
+				// assume it's an ID.
5683
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5684
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5685
+			} elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5686
+				&& is_string($base_class_obj_or_id)
5687
+			) {
5688
+				// assume its a string representation of the object
5689
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5690
+			} else {
5691
+				throw new EE_Error(
5692
+					sprintf(
5693
+						__(
5694
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5695
+							'event_espresso'
5696
+						),
5697
+						$base_class_obj_or_id,
5698
+						$this->_get_class_name(),
5699
+						print_r($base_class_obj_or_id, true)
5700
+					)
5701
+				);
5702
+			}
5703
+		}
5704
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5705
+			$model_object->save();
5706
+		}
5707
+		return $model_object;
5708
+	}
5709
+
5710
+
5711
+
5712
+	/**
5713
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5714
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5715
+	 * returns it ID.
5716
+	 *
5717
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5718
+	 * @return int|string depending on the type of this model object's ID
5719
+	 * @throws EE_Error
5720
+	 */
5721
+	public function ensure_is_ID($base_class_obj_or_id)
5722
+	{
5723
+		$className = $this->_get_class_name();
5724
+		if ($base_class_obj_or_id instanceof $className) {
5725
+			/** @var $base_class_obj_or_id EE_Base_Class */
5726
+			$id = $base_class_obj_or_id->ID();
5727
+		} elseif (is_int($base_class_obj_or_id)) {
5728
+			// assume it's an ID
5729
+			$id = $base_class_obj_or_id;
5730
+		} elseif (is_string($base_class_obj_or_id)) {
5731
+			// assume its a string representation of the object
5732
+			$id = $base_class_obj_or_id;
5733
+		} else {
5734
+			throw new EE_Error(sprintf(
5735
+				__(
5736
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5737
+					'event_espresso'
5738
+				),
5739
+				$base_class_obj_or_id,
5740
+				$this->_get_class_name(),
5741
+				print_r($base_class_obj_or_id, true)
5742
+			));
5743
+		}
5744
+		return $id;
5745
+	}
5746
+
5747
+
5748
+
5749
+	/**
5750
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5751
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5752
+	 * been sanitized and converted into the appropriate domain.
5753
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5754
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5755
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5756
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5757
+	 * $EVT = EEM_Event::instance(); $old_setting =
5758
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5759
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5760
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5761
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5762
+	 *
5763
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5764
+	 * @return void
5765
+	 */
5766
+	public function assume_values_already_prepared_by_model_object(
5767
+		$values_already_prepared = self::not_prepared_by_model_object
5768
+	) {
5769
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5770
+	}
5771
+
5772
+
5773
+
5774
+	/**
5775
+	 * Read comments for assume_values_already_prepared_by_model_object()
5776
+	 *
5777
+	 * @return int
5778
+	 */
5779
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5780
+	{
5781
+		return $this->_values_already_prepared_by_model_object;
5782
+	}
5783
+
5784
+
5785
+
5786
+	/**
5787
+	 * Gets all the indexes on this model
5788
+	 *
5789
+	 * @return EE_Index[]
5790
+	 */
5791
+	public function indexes()
5792
+	{
5793
+		return $this->_indexes;
5794
+	}
5795
+
5796
+
5797
+
5798
+	/**
5799
+	 * Gets all the Unique Indexes on this model
5800
+	 *
5801
+	 * @return EE_Unique_Index[]
5802
+	 */
5803
+	public function unique_indexes()
5804
+	{
5805
+		$unique_indexes = array();
5806
+		foreach ($this->_indexes as $name => $index) {
5807
+			if ($index instanceof EE_Unique_Index) {
5808
+				$unique_indexes [ $name ] = $index;
5809
+			}
5810
+		}
5811
+		return $unique_indexes;
5812
+	}
5813
+
5814
+
5815
+
5816
+	/**
5817
+	 * Gets all the fields which, when combined, make the primary key.
5818
+	 * This is usually just an array with 1 element (the primary key), but in cases
5819
+	 * where there is no primary key, it's a combination of fields as defined
5820
+	 * on a primary index
5821
+	 *
5822
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5823
+	 * @throws EE_Error
5824
+	 */
5825
+	public function get_combined_primary_key_fields()
5826
+	{
5827
+		foreach ($this->indexes() as $index) {
5828
+			if ($index instanceof EE_Primary_Key_Index) {
5829
+				return $index->fields();
5830
+			}
5831
+		}
5832
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5833
+	}
5834
+
5835
+
5836
+
5837
+	/**
5838
+	 * Used to build a primary key string (when the model has no primary key),
5839
+	 * which can be used a unique string to identify this model object.
5840
+	 *
5841
+	 * @param array $cols_n_values keys are field names, values are their values
5842
+	 * @return string
5843
+	 * @throws EE_Error
5844
+	 */
5845
+	public function get_index_primary_key_string($cols_n_values)
5846
+	{
5847
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5848
+			$cols_n_values,
5849
+			$this->get_combined_primary_key_fields()
5850
+		);
5851
+		return http_build_query($cols_n_values_for_primary_key_index);
5852
+	}
5853
+
5854
+
5855
+
5856
+	/**
5857
+	 * Gets the field values from the primary key string
5858
+	 *
5859
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5860
+	 * @param string $index_primary_key_string
5861
+	 * @return null|array
5862
+	 * @throws EE_Error
5863
+	 */
5864
+	public function parse_index_primary_key_string($index_primary_key_string)
5865
+	{
5866
+		$key_fields = $this->get_combined_primary_key_fields();
5867
+		// check all of them are in the $id
5868
+		$key_vals_in_combined_pk = array();
5869
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5870
+		foreach ($key_fields as $key_field_name => $field_obj) {
5871
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5872
+				return null;
5873
+			}
5874
+		}
5875
+		return $key_vals_in_combined_pk;
5876
+	}
5877
+
5878
+
5879
+
5880
+	/**
5881
+	 * verifies that an array of key-value pairs for model fields has a key
5882
+	 * for each field comprising the primary key index
5883
+	 *
5884
+	 * @param array $key_vals
5885
+	 * @return boolean
5886
+	 * @throws EE_Error
5887
+	 */
5888
+	public function has_all_combined_primary_key_fields($key_vals)
5889
+	{
5890
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5891
+		foreach ($keys_it_should_have as $key) {
5892
+			if (! isset($key_vals[ $key ])) {
5893
+				return false;
5894
+			}
5895
+		}
5896
+		return true;
5897
+	}
5898
+
5899
+
5900
+
5901
+	/**
5902
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5903
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5904
+	 *
5905
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5906
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5907
+	 * @throws EE_Error
5908
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5909
+	 *                                                              indexed)
5910
+	 */
5911
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5912
+	{
5913
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5914
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5915
+		} elseif (is_array($model_object_or_attributes_array)) {
5916
+			$attributes_array = $model_object_or_attributes_array;
5917
+		} else {
5918
+			throw new EE_Error(sprintf(__(
5919
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5920
+				"event_espresso"
5921
+			), $model_object_or_attributes_array));
5922
+		}
5923
+		// even copies obviously won't have the same ID, so remove the primary key
5924
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5925
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5926
+			unset($attributes_array[ $this->primary_key_name() ]);
5927
+		}
5928
+		if (isset($query_params[0])) {
5929
+			$query_params[0] = array_merge($attributes_array, $query_params);
5930
+		} else {
5931
+			$query_params[0] = $attributes_array;
5932
+		}
5933
+		return $this->get_all($query_params);
5934
+	}
5935
+
5936
+
5937
+
5938
+	/**
5939
+	 * Gets the first copy we find. See get_all_copies for more details
5940
+	 *
5941
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5942
+	 * @param array $query_params
5943
+	 * @return EE_Base_Class
5944
+	 * @throws EE_Error
5945
+	 */
5946
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5947
+	{
5948
+		if (! is_array($query_params)) {
5949
+			EE_Error::doing_it_wrong(
5950
+				'EEM_Base::get_one_copy',
5951
+				sprintf(
5952
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5953
+					gettype($query_params)
5954
+				),
5955
+				'4.6.0'
5956
+			);
5957
+			$query_params = array();
5958
+		}
5959
+		$query_params['limit'] = 1;
5960
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5961
+		if (is_array($copies)) {
5962
+			return array_shift($copies);
5963
+		}
5964
+		return null;
5965
+	}
5966
+
5967
+
5968
+
5969
+	/**
5970
+	 * Updates the item with the specified id. Ignores default query parameters because
5971
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5972
+	 *
5973
+	 * @param array      $fields_n_values keys are field names, values are their new values
5974
+	 * @param int|string $id              the value of the primary key to update
5975
+	 * @return int number of rows updated
5976
+	 * @throws EE_Error
5977
+	 */
5978
+	public function update_by_ID($fields_n_values, $id)
5979
+	{
5980
+		$query_params = array(
5981
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5982
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5983
+		);
5984
+		return $this->update($fields_n_values, $query_params);
5985
+	}
5986
+
5987
+
5988
+
5989
+	/**
5990
+	 * Changes an operator which was supplied to the models into one usable in SQL
5991
+	 *
5992
+	 * @param string $operator_supplied
5993
+	 * @return string an operator which can be used in SQL
5994
+	 * @throws EE_Error
5995
+	 */
5996
+	private function _prepare_operator_for_sql($operator_supplied)
5997
+	{
5998
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5999
+			: null;
6000
+		if ($sql_operator) {
6001
+			return $sql_operator;
6002
+		}
6003
+		throw new EE_Error(
6004
+			sprintf(
6005
+				__(
6006
+					"The operator '%s' is not in the list of valid operators: %s",
6007
+					"event_espresso"
6008
+				),
6009
+				$operator_supplied,
6010
+				implode(",", array_keys($this->_valid_operators))
6011
+			)
6012
+		);
6013
+	}
6014
+
6015
+
6016
+
6017
+	/**
6018
+	 * Gets the valid operators
6019
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6020
+	 */
6021
+	public function valid_operators()
6022
+	{
6023
+		return $this->_valid_operators;
6024
+	}
6025
+
6026
+
6027
+
6028
+	/**
6029
+	 * Gets the between-style operators (take 2 arguments).
6030
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6031
+	 */
6032
+	public function valid_between_style_operators()
6033
+	{
6034
+		return array_intersect(
6035
+			$this->valid_operators(),
6036
+			$this->_between_style_operators
6037
+		);
6038
+	}
6039
+
6040
+	/**
6041
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6042
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6043
+	 */
6044
+	public function valid_like_style_operators()
6045
+	{
6046
+		return array_intersect(
6047
+			$this->valid_operators(),
6048
+			$this->_like_style_operators
6049
+		);
6050
+	}
6051
+
6052
+	/**
6053
+	 * Gets the "in"-style operators
6054
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6055
+	 */
6056
+	public function valid_in_style_operators()
6057
+	{
6058
+		return array_intersect(
6059
+			$this->valid_operators(),
6060
+			$this->_in_style_operators
6061
+		);
6062
+	}
6063
+
6064
+	/**
6065
+	 * Gets the "null"-style operators (accept no arguments)
6066
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6067
+	 */
6068
+	public function valid_null_style_operators()
6069
+	{
6070
+		return array_intersect(
6071
+			$this->valid_operators(),
6072
+			$this->_null_style_operators
6073
+		);
6074
+	}
6075
+
6076
+	/**
6077
+	 * Gets an array where keys are the primary keys and values are their 'names'
6078
+	 * (as determined by the model object's name() function, which is often overridden)
6079
+	 *
6080
+	 * @param array $query_params like get_all's
6081
+	 * @return string[]
6082
+	 * @throws EE_Error
6083
+	 */
6084
+	public function get_all_names($query_params = array())
6085
+	{
6086
+		$objs = $this->get_all($query_params);
6087
+		$names = array();
6088
+		foreach ($objs as $obj) {
6089
+			$names[ $obj->ID() ] = $obj->name();
6090
+		}
6091
+		return $names;
6092
+	}
6093
+
6094
+
6095
+
6096
+	/**
6097
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6098
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6099
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6100
+	 * array_keys() on $model_objects.
6101
+	 *
6102
+	 * @param \EE_Base_Class[] $model_objects
6103
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6104
+	 *                                               in the returned array
6105
+	 * @return array
6106
+	 * @throws EE_Error
6107
+	 */
6108
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6109
+	{
6110
+		if (! $this->has_primary_key_field()) {
6111
+			if (WP_DEBUG) {
6112
+				EE_Error::add_error(
6113
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6114
+					__FILE__,
6115
+					__FUNCTION__,
6116
+					__LINE__
6117
+				);
6118
+			}
6119
+		}
6120
+		$IDs = array();
6121
+		foreach ($model_objects as $model_object) {
6122
+			$id = $model_object->ID();
6123
+			if (! $id) {
6124
+				if ($filter_out_empty_ids) {
6125
+					continue;
6126
+				}
6127
+				if (WP_DEBUG) {
6128
+					EE_Error::add_error(
6129
+						__(
6130
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6131
+							'event_espresso'
6132
+						),
6133
+						__FILE__,
6134
+						__FUNCTION__,
6135
+						__LINE__
6136
+					);
6137
+				}
6138
+			}
6139
+			$IDs[] = $id;
6140
+		}
6141
+		return $IDs;
6142
+	}
6143
+
6144
+
6145
+
6146
+	/**
6147
+	 * Returns the string used in capabilities relating to this model. If there
6148
+	 * are no capabilities that relate to this model returns false
6149
+	 *
6150
+	 * @return string|false
6151
+	 */
6152
+	public function cap_slug()
6153
+	{
6154
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6155
+	}
6156
+
6157
+
6158
+
6159
+	/**
6160
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6161
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6162
+	 * only returns the cap restrictions array in that context (ie, the array
6163
+	 * at that key)
6164
+	 *
6165
+	 * @param string $context
6166
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6167
+	 * @throws EE_Error
6168
+	 */
6169
+	public function cap_restrictions($context = EEM_Base::caps_read)
6170
+	{
6171
+		EEM_Base::verify_is_valid_cap_context($context);
6172
+		// check if we ought to run the restriction generator first
6173
+		if (isset($this->_cap_restriction_generators[ $context ])
6174
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6175
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6176
+		) {
6177
+			$this->_cap_restrictions[ $context ] = array_merge(
6178
+				$this->_cap_restrictions[ $context ],
6179
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6180
+			);
6181
+		}
6182
+		// and make sure we've finalized the construction of each restriction
6183
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6184
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6185
+				$where_conditions_obj->_finalize_construct($this);
6186
+			}
6187
+		}
6188
+		return $this->_cap_restrictions[ $context ];
6189
+	}
6190
+
6191
+
6192
+
6193
+	/**
6194
+	 * Indicating whether or not this model thinks its a wp core model
6195
+	 *
6196
+	 * @return boolean
6197
+	 */
6198
+	public function is_wp_core_model()
6199
+	{
6200
+		return $this->_wp_core_model;
6201
+	}
6202
+
6203
+
6204
+
6205
+	/**
6206
+	 * Gets all the caps that are missing which impose a restriction on
6207
+	 * queries made in this context
6208
+	 *
6209
+	 * @param string $context one of EEM_Base::caps_ constants
6210
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6211
+	 * @throws EE_Error
6212
+	 */
6213
+	public function caps_missing($context = EEM_Base::caps_read)
6214
+	{
6215
+		$missing_caps = array();
6216
+		$cap_restrictions = $this->cap_restrictions($context);
6217
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6218
+			if (! EE_Capabilities::instance()
6219
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6220
+			) {
6221
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6222
+			}
6223
+		}
6224
+		return $missing_caps;
6225
+	}
6226
+
6227
+
6228
+
6229
+	/**
6230
+	 * Gets the mapping from capability contexts to action strings used in capability names
6231
+	 *
6232
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6233
+	 * one of 'read', 'edit', or 'delete'
6234
+	 */
6235
+	public function cap_contexts_to_cap_action_map()
6236
+	{
6237
+		return apply_filters(
6238
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6239
+			$this->_cap_contexts_to_cap_action_map,
6240
+			$this
6241
+		);
6242
+	}
6243
+
6244
+
6245
+
6246
+	/**
6247
+	 * Gets the action string for the specified capability context
6248
+	 *
6249
+	 * @param string $context
6250
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6251
+	 * @throws EE_Error
6252
+	 */
6253
+	public function cap_action_for_context($context)
6254
+	{
6255
+		$mapping = $this->cap_contexts_to_cap_action_map();
6256
+		if (isset($mapping[ $context ])) {
6257
+			return $mapping[ $context ];
6258
+		}
6259
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6260
+			return $action;
6261
+		}
6262
+		throw new EE_Error(
6263
+			sprintf(
6264
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6265
+				$context,
6266
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6267
+			)
6268
+		);
6269
+	}
6270
+
6271
+
6272
+
6273
+	/**
6274
+	 * Returns all the capability contexts which are valid when querying models
6275
+	 *
6276
+	 * @return array
6277
+	 */
6278
+	public static function valid_cap_contexts()
6279
+	{
6280
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6281
+			self::caps_read,
6282
+			self::caps_read_admin,
6283
+			self::caps_edit,
6284
+			self::caps_delete,
6285
+		));
6286
+	}
6287
+
6288
+
6289
+
6290
+	/**
6291
+	 * Returns all valid options for 'default_where_conditions'
6292
+	 *
6293
+	 * @return array
6294
+	 */
6295
+	public static function valid_default_where_conditions()
6296
+	{
6297
+		return array(
6298
+			EEM_Base::default_where_conditions_all,
6299
+			EEM_Base::default_where_conditions_this_only,
6300
+			EEM_Base::default_where_conditions_others_only,
6301
+			EEM_Base::default_where_conditions_minimum_all,
6302
+			EEM_Base::default_where_conditions_minimum_others,
6303
+			EEM_Base::default_where_conditions_none
6304
+		);
6305
+	}
6306
+
6307
+	// public static function default_where_conditions_full
6308
+	/**
6309
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6310
+	 *
6311
+	 * @param string $context
6312
+	 * @return bool
6313
+	 * @throws EE_Error
6314
+	 */
6315
+	public static function verify_is_valid_cap_context($context)
6316
+	{
6317
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6318
+		if (in_array($context, $valid_cap_contexts)) {
6319
+			return true;
6320
+		}
6321
+		throw new EE_Error(
6322
+			sprintf(
6323
+				__(
6324
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6325
+					'event_espresso'
6326
+				),
6327
+				$context,
6328
+				'EEM_Base',
6329
+				implode(',', $valid_cap_contexts)
6330
+			)
6331
+		);
6332
+	}
6333
+
6334
+
6335
+
6336
+	/**
6337
+	 * Clears all the models field caches. This is only useful when a sub-class
6338
+	 * might have added a field or something and these caches might be invalidated
6339
+	 */
6340
+	protected function _invalidate_field_caches()
6341
+	{
6342
+		$this->_cache_foreign_key_to_fields = array();
6343
+		$this->_cached_fields = null;
6344
+		$this->_cached_fields_non_db_only = null;
6345
+	}
6346
+
6347
+
6348
+
6349
+	/**
6350
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6351
+	 * (eg "and", "or", "not").
6352
+	 *
6353
+	 * @return array
6354
+	 */
6355
+	public function logic_query_param_keys()
6356
+	{
6357
+		return $this->_logic_query_param_keys;
6358
+	}
6359
+
6360
+
6361
+
6362
+	/**
6363
+	 * Determines whether or not the where query param array key is for a logic query param.
6364
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6365
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6366
+	 *
6367
+	 * @param $query_param_key
6368
+	 * @return bool
6369
+	 */
6370
+	public function is_logic_query_param_key($query_param_key)
6371
+	{
6372
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6373
+			if ($query_param_key === $logic_query_param_key
6374
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6375
+			) {
6376
+				return true;
6377
+			}
6378
+		}
6379
+		return false;
6380
+	}
6381 6381
 }
Please login to merge, or discard this patch.
Spacing   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
     protected function __construct($timezone = null)
516 516
     {
517 517
         // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
518
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
519 519
             throw new EE_Error(
520 520
                 sprintf(
521 521
                     __(
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
          *
539 539
          * @var EE_Table_Base[] $_tables
540 540
          */
541
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
541
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
542 542
         foreach ($this->_tables as $table_alias => $table_obj) {
543 543
             /** @var $table_obj EE_Table_Base */
544 544
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -553,10 +553,10 @@  discard block
 block discarded – undo
553 553
          *
554 554
          * @param EE_Model_Field_Base[] $_fields
555 555
          */
556
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
556
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
557 557
         $this->_invalidate_field_caches();
558 558
         foreach ($this->_fields as $table_alias => $fields_for_table) {
559
-            if (! array_key_exists($table_alias, $this->_tables)) {
559
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
560 560
                 throw new EE_Error(sprintf(__(
561 561
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
562 562
                     'event_espresso'
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
          * @param EE_Model_Relation_Base[] $_model_relations
588 588
          */
589 589
         $this->_model_relations = (array) apply_filters(
590
-            'FHEE__' . get_class($this) . '__construct__model_relations',
590
+            'FHEE__'.get_class($this).'__construct__model_relations',
591 591
             $this->_model_relations
592 592
         );
593 593
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -600,12 +600,12 @@  discard block
 block discarded – undo
600 600
         }
601 601
         $this->set_timezone($timezone);
602 602
         // finalize default where condition strategy, or set default
603
-        if (! $this->_default_where_conditions_strategy) {
603
+        if ( ! $this->_default_where_conditions_strategy) {
604 604
             // nothing was set during child constructor, so set default
605 605
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
606 606
         }
607 607
         $this->_default_where_conditions_strategy->_finalize_construct($this);
608
-        if (! $this->_minimum_where_conditions_strategy) {
608
+        if ( ! $this->_minimum_where_conditions_strategy) {
609 609
             // nothing was set during child constructor, so set default
610 610
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
611 611
         }
@@ -618,8 +618,8 @@  discard block
 block discarded – undo
618 618
         // initialize the standard cap restriction generators if none were specified by the child constructor
619 619
         if ($this->_cap_restriction_generators !== false) {
620 620
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
621
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
622
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
621
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
622
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
623 623
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
624 624
                         new EE_Restriction_Generator_Protected(),
625 625
                         $cap_context,
@@ -631,10 +631,10 @@  discard block
 block discarded – undo
631 631
         // if there are cap restriction generators, use them to make the default cap restrictions
632 632
         if ($this->_cap_restriction_generators !== false) {
633 633
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
634
-                if (! $generator_object) {
634
+                if ( ! $generator_object) {
635 635
                     continue;
636 636
                 }
637
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
637
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
638 638
                     throw new EE_Error(
639 639
                         sprintf(
640 640
                             __(
@@ -647,12 +647,12 @@  discard block
 block discarded – undo
647 647
                     );
648 648
                 }
649 649
                 $action = $this->cap_action_for_context($context);
650
-                if (! $generator_object->construction_finalized()) {
650
+                if ( ! $generator_object->construction_finalized()) {
651 651
                     $generator_object->_construct_finalize($this, $action);
652 652
                 }
653 653
             }
654 654
         }
655
-        do_action('AHEE__' . get_class($this) . '__construct__end');
655
+        do_action('AHEE__'.get_class($this).'__construct__end');
656 656
     }
657 657
 
658 658
 
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
     public static function instance($timezone = null)
700 700
     {
701 701
         // check if instance of Espresso_model already exists
702
-        if (! static::$_instance instanceof static) {
702
+        if ( ! static::$_instance instanceof static) {
703 703
             // instantiate Espresso_model
704 704
             static::$_instance = new static(
705 705
                 $timezone,
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
             foreach ($r->getDefaultProperties() as $property => $value) {
739 739
                 // don't set instance to null like it was originally,
740 740
                 // but it's static anyways, and we're ignoring static properties (for now at least)
741
-                if (! isset($static_properties[ $property ])) {
741
+                if ( ! isset($static_properties[$property])) {
742 742
                     static::$_instance->{$property} = $value;
743 743
                 }
744 744
             }
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
      */
763 763
     private static function getLoader()
764 764
     {
765
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
765
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
766 766
             EEM_Base::$loader = LoaderFactory::getLoader();
767 767
         }
768 768
         return EEM_Base::$loader;
@@ -782,7 +782,7 @@  discard block
 block discarded – undo
782 782
      */
783 783
     public function status_array($translated = false)
784 784
     {
785
-        if (! array_key_exists('Status', $this->_model_relations)) {
785
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
786 786
             return array();
787 787
         }
788 788
         $model_name = $this->get_this_model_name();
@@ -790,7 +790,7 @@  discard block
 block discarded – undo
790 790
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
791 791
         $status_array = array();
792 792
         foreach ($stati as $status) {
793
-            $status_array[ $status->ID() ] = $status->get('STS_code');
793
+            $status_array[$status->ID()] = $status->get('STS_code');
794 794
         }
795 795
         return $translated
796 796
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -967,7 +967,7 @@  discard block
 block discarded – undo
967 967
     {
968 968
         $wp_user_field_name = $this->wp_user_field_name();
969 969
         if ($wp_user_field_name) {
970
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
970
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
971 971
         }
972 972
         return $query_params;
973 973
     }
@@ -985,17 +985,17 @@  discard block
 block discarded – undo
985 985
     public function wp_user_field_name()
986 986
     {
987 987
         try {
988
-            if (! empty($this->_model_chain_to_wp_user)) {
988
+            if ( ! empty($this->_model_chain_to_wp_user)) {
989 989
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
990 990
                 $last_model_name = end($models_to_follow_to_wp_users);
991 991
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
992
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
992
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
993 993
             } else {
994 994
                 $model_with_fk_to_wp_users = $this;
995 995
                 $model_chain_to_wp_user = '';
996 996
             }
997 997
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
998
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
998
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
999 999
         } catch (EE_Error $e) {
1000 1000
             return false;
1001 1001
         }
@@ -1072,11 +1072,11 @@  discard block
 block discarded – undo
1072 1072
         if ($this->_custom_selections instanceof CustomSelects) {
1073 1073
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1074 1074
             $select_expressions .= $select_expressions
1075
-                ? ', ' . $custom_expressions
1075
+                ? ', '.$custom_expressions
1076 1076
                 : $custom_expressions;
1077 1077
         }
1078 1078
 
1079
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1079
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1080 1080
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1081 1081
     }
1082 1082
 
@@ -1093,7 +1093,7 @@  discard block
 block discarded – undo
1093 1093
      */
1094 1094
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1095 1095
     {
1096
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1096
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1097 1097
             return null;
1098 1098
         }
1099 1099
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1142,7 +1142,7 @@  discard block
 block discarded – undo
1142 1142
         if (is_array($columns_to_select)) {
1143 1143
             $select_sql_array = array();
1144 1144
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1145
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1145
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1146 1146
                     throw new EE_Error(
1147 1147
                         sprintf(
1148 1148
                             __(
@@ -1154,7 +1154,7 @@  discard block
 block discarded – undo
1154 1154
                         )
1155 1155
                     );
1156 1156
                 }
1157
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1157
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1158 1158
                     throw new EE_Error(
1159 1159
                         sprintf(
1160 1160
                             esc_html__(
@@ -1226,12 +1226,12 @@  discard block
 block discarded – undo
1226 1226
      */
1227 1227
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1228 1228
     {
1229
-        if (! isset($query_params[0])) {
1229
+        if ( ! isset($query_params[0])) {
1230 1230
             $query_params[0] = array();
1231 1231
         }
1232 1232
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1233 1233
         if ($conditions_from_id === null) {
1234
-            $query_params[0][ $this->primary_key_name() ] = $id;
1234
+            $query_params[0][$this->primary_key_name()] = $id;
1235 1235
         } else {
1236 1236
             // no primary key, so the $id must be from the get_index_primary_key_string()
1237 1237
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1251,7 +1251,7 @@  discard block
 block discarded – undo
1251 1251
      */
1252 1252
     public function get_one($query_params = array())
1253 1253
     {
1254
-        if (! is_array($query_params)) {
1254
+        if ( ! is_array($query_params)) {
1255 1255
             EE_Error::doing_it_wrong(
1256 1256
                 'EEM_Base::get_one',
1257 1257
                 sprintf(
@@ -1449,7 +1449,7 @@  discard block
 block discarded – undo
1449 1449
                 return array();
1450 1450
             }
1451 1451
         }
1452
-        if (! is_array($query_params)) {
1452
+        if ( ! is_array($query_params)) {
1453 1453
             EE_Error::doing_it_wrong(
1454 1454
                 'EEM_Base::_get_consecutive',
1455 1455
                 sprintf(
@@ -1461,7 +1461,7 @@  discard block
 block discarded – undo
1461 1461
             $query_params = array();
1462 1462
         }
1463 1463
         // let's add the where query param for consecutive look up.
1464
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1464
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1465 1465
         $query_params['limit'] = $limit;
1466 1466
         // set direction
1467 1467
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1542,7 +1542,7 @@  discard block
 block discarded – undo
1542 1542
     {
1543 1543
         $field_settings = $this->field_settings_for($field_name);
1544 1544
         // if not a valid EE_Datetime_Field then throw error
1545
-        if (! $field_settings instanceof EE_Datetime_Field) {
1545
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1546 1546
             throw new EE_Error(sprintf(__(
1547 1547
                 'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1548 1548
                 'event_espresso'
@@ -1692,7 +1692,7 @@  discard block
 block discarded – undo
1692 1692
      */
1693 1693
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1694 1694
     {
1695
-        if (! is_array($query_params)) {
1695
+        if ( ! is_array($query_params)) {
1696 1696
             EE_Error::doing_it_wrong(
1697 1697
                 'EEM_Base::update',
1698 1698
                 sprintf(
@@ -1740,7 +1740,7 @@  discard block
 block discarded – undo
1740 1740
             $wpdb_result = (array) $wpdb_result;
1741 1741
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1742 1742
             if ($this->has_primary_key_field()) {
1743
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1743
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1744 1744
             } else {
1745 1745
                 // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1746 1746
                 $main_table_pk_value = null;
@@ -1754,8 +1754,8 @@  discard block
 block discarded – undo
1754 1754
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1755 1755
                     // if there is no private key for this table on the results, it means there's no entry
1756 1756
                     // in this table, right? so insert a row in the current table, using any fields available
1757
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1758
-                           && $wpdb_result[ $this_table_pk_column ])
1757
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1758
+                           && $wpdb_result[$this_table_pk_column])
1759 1759
                     ) {
1760 1760
                         $success = $this->_insert_into_specific_table(
1761 1761
                             $table_obj,
@@ -1763,7 +1763,7 @@  discard block
 block discarded – undo
1763 1763
                             $main_table_pk_value
1764 1764
                         );
1765 1765
                         // if we died here, report the error
1766
-                        if (! $success) {
1766
+                        if ( ! $success) {
1767 1767
                             return false;
1768 1768
                         }
1769 1769
                     }
@@ -1791,10 +1791,10 @@  discard block
 block discarded – undo
1791 1791
                 $model_objs_affected_ids = array();
1792 1792
                 foreach ($models_affected_key_columns as $row) {
1793 1793
                     $combined_index_key = $this->get_index_primary_key_string($row);
1794
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1794
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1795 1795
                 }
1796 1796
             }
1797
-            if (! $model_objs_affected_ids) {
1797
+            if ( ! $model_objs_affected_ids) {
1798 1798
                 // wait wait wait- if nothing was affected let's stop here
1799 1799
                 return 0;
1800 1800
             }
@@ -1821,7 +1821,7 @@  discard block
 block discarded – undo
1821 1821
                . $model_query_info->get_full_join_sql()
1822 1822
                . " SET "
1823 1823
                . $this->_construct_update_sql($fields_n_values)
1824
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1824
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1825 1825
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1826 1826
         /**
1827 1827
          * Action called after a model update call has been made.
@@ -1832,7 +1832,7 @@  discard block
 block discarded – undo
1832 1832
          * @param int      $rows_affected
1833 1833
          */
1834 1834
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1835
-        return $rows_affected;// how many supposedly got updated
1835
+        return $rows_affected; // how many supposedly got updated
1836 1836
     }
1837 1837
 
1838 1838
 
@@ -1860,7 +1860,7 @@  discard block
 block discarded – undo
1860 1860
         }
1861 1861
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1862 1862
         $select_expressions = $field->get_qualified_column();
1863
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1863
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1864 1864
         return $this->_do_wpdb_query('get_col', array($SQL));
1865 1865
     }
1866 1866
 
@@ -1878,7 +1878,7 @@  discard block
 block discarded – undo
1878 1878
     {
1879 1879
         $query_params['limit'] = 1;
1880 1880
         $col = $this->get_col($query_params, $field_to_select);
1881
-        if (! empty($col)) {
1881
+        if ( ! empty($col)) {
1882 1882
             return reset($col);
1883 1883
         }
1884 1884
         return null;
@@ -1909,7 +1909,7 @@  discard block
 block discarded – undo
1909 1909
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1910 1910
             $value_sql = $prepared_value === null ? 'NULL'
1911 1911
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1912
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1912
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1913 1913
         }
1914 1914
         return implode(",", $cols_n_values);
1915 1915
     }
@@ -2052,12 +2052,12 @@  discard block
 block discarded – undo
2052 2052
         // there was no error with the delete query.
2053 2053
         if ($this->has_primary_key_field()
2054 2054
             && $rows_deleted !== false
2055
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2055
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2056 2056
         ) {
2057
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2057
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2058 2058
             foreach ($ids_for_removal as $id) {
2059
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2060
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2059
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2060
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2061 2061
                 }
2062 2062
             }
2063 2063
 
@@ -2092,7 +2092,7 @@  discard block
 block discarded – undo
2092 2092
          * @param int      $rows_deleted
2093 2093
          */
2094 2094
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2095
-        return $rows_deleted;// how many supposedly got deleted
2095
+        return $rows_deleted; // how many supposedly got deleted
2096 2096
     }
2097 2097
 
2098 2098
 
@@ -2185,15 +2185,15 @@  discard block
 block discarded – undo
2185 2185
                 // make sure there's no related entities blocking its deletion (if we're checking)
2186 2186
                 if ($allow_blocking
2187 2187
                     && $this->delete_is_blocked_by_related_models(
2188
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2188
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2189 2189
                     )
2190 2190
                 ) {
2191 2191
                     continue;
2192 2192
                 }
2193 2193
                 // primary table deletes
2194
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2195
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2196
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2194
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2195
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2196
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2197 2197
                 }
2198 2198
             }
2199 2199
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2202,8 +2202,8 @@  discard block
 block discarded – undo
2202 2202
                 $ids_to_delete_indexed_by_column_for_row = array();
2203 2203
                 foreach ($fields as $cpk_field) {
2204 2204
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2205
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2206
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2205
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2206
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2207 2207
                     }
2208 2208
                 }
2209 2209
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2243,7 +2243,7 @@  discard block
 block discarded – undo
2243 2243
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2244 2244
                 // make sure we have unique $ids
2245 2245
                 $ids = array_unique($ids);
2246
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2246
+                $query[] = $column.' IN('.implode(',', $ids).')';
2247 2247
             }
2248 2248
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2249 2249
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2251,7 +2251,7 @@  discard block
 block discarded – undo
2251 2251
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2252 2252
                 $values_for_each_combined_primary_key_for_a_row = array();
2253 2253
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2254
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2254
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2255 2255
                 }
2256 2256
                 $ways_to_identify_a_row[] = '('
2257 2257
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2323,8 +2323,8 @@  discard block
 block discarded – undo
2323 2323
                 $column_to_count = '*';
2324 2324
             }
2325 2325
         }
2326
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2327
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2326
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2327
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2328 2328
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2329 2329
     }
2330 2330
 
@@ -2347,7 +2347,7 @@  discard block
 block discarded – undo
2347 2347
             $field_obj = $this->get_primary_key_field();
2348 2348
         }
2349 2349
         $column_to_count = $field_obj->get_qualified_column();
2350
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2350
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2351 2351
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2352 2352
         $data_type = $field_obj->get_wpdb_data_type();
2353 2353
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2374,7 +2374,7 @@  discard block
 block discarded – undo
2374 2374
         // if we're in maintenance mode level 2, DON'T run any queries
2375 2375
         // because level 2 indicates the database needs updating and
2376 2376
         // is probably out of sync with the code
2377
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2377
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2378 2378
             throw new EE_Error(sprintf(__(
2379 2379
                 "Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2380 2380
                 "event_espresso"
@@ -2382,7 +2382,7 @@  discard block
 block discarded – undo
2382 2382
         }
2383 2383
         /** @type WPDB $wpdb */
2384 2384
         global $wpdb;
2385
-        if (! method_exists($wpdb, $wpdb_method)) {
2385
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2386 2386
             throw new EE_Error(sprintf(__(
2387 2387
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2388 2388
                 'event_espresso'
@@ -2396,7 +2396,7 @@  discard block
 block discarded – undo
2396 2396
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2397 2397
         if (WP_DEBUG) {
2398 2398
             $wpdb->show_errors($old_show_errors_value);
2399
-            if (! empty($wpdb->last_error)) {
2399
+            if ( ! empty($wpdb->last_error)) {
2400 2400
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2401 2401
             }
2402 2402
             if ($result === false) {
@@ -2461,7 +2461,7 @@  discard block
 block discarded – undo
2461 2461
                     return $result;
2462 2462
                     break;
2463 2463
             }
2464
-            if (! empty($error_message)) {
2464
+            if ( ! empty($error_message)) {
2465 2465
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2466 2466
                 trigger_error($error_message);
2467 2467
             }
@@ -2541,11 +2541,11 @@  discard block
 block discarded – undo
2541 2541
      */
2542 2542
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2543 2543
     {
2544
-        return " FROM " . $model_query_info->get_full_join_sql() .
2545
-               $model_query_info->get_where_sql() .
2546
-               $model_query_info->get_group_by_sql() .
2547
-               $model_query_info->get_having_sql() .
2548
-               $model_query_info->get_order_by_sql() .
2544
+        return " FROM ".$model_query_info->get_full_join_sql().
2545
+               $model_query_info->get_where_sql().
2546
+               $model_query_info->get_group_by_sql().
2547
+               $model_query_info->get_having_sql().
2548
+               $model_query_info->get_order_by_sql().
2549 2549
                $model_query_info->get_limit_sql();
2550 2550
     }
2551 2551
 
@@ -2741,12 +2741,12 @@  discard block
 block discarded – undo
2741 2741
         $related_model = $this->get_related_model_obj($model_name);
2742 2742
         // we're just going to use the query params on the related model's normal get_all query,
2743 2743
         // except add a condition to say to match the current mod
2744
-        if (! isset($query_params['default_where_conditions'])) {
2744
+        if ( ! isset($query_params['default_where_conditions'])) {
2745 2745
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2746 2746
         }
2747 2747
         $this_model_name = $this->get_this_model_name();
2748 2748
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2749
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2749
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2750 2750
         return $related_model->count($query_params, $field_to_count, $distinct);
2751 2751
     }
2752 2752
 
@@ -2766,7 +2766,7 @@  discard block
 block discarded – undo
2766 2766
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2767 2767
     {
2768 2768
         $related_model = $this->get_related_model_obj($model_name);
2769
-        if (! is_array($query_params)) {
2769
+        if ( ! is_array($query_params)) {
2770 2770
             EE_Error::doing_it_wrong(
2771 2771
                 'EEM_Base::sum_related',
2772 2772
                 sprintf(
@@ -2779,12 +2779,12 @@  discard block
 block discarded – undo
2779 2779
         }
2780 2780
         // we're just going to use the query params on the related model's normal get_all query,
2781 2781
         // except add a condition to say to match the current mod
2782
-        if (! isset($query_params['default_where_conditions'])) {
2782
+        if ( ! isset($query_params['default_where_conditions'])) {
2783 2783
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2784 2784
         }
2785 2785
         $this_model_name = $this->get_this_model_name();
2786 2786
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2787
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2787
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2788 2788
         return $related_model->sum($query_params, $field_to_sum);
2789 2789
     }
2790 2790
 
@@ -2837,7 +2837,7 @@  discard block
 block discarded – undo
2837 2837
                 $field_with_model_name = $field;
2838 2838
             }
2839 2839
         }
2840
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2840
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2841 2841
             throw new EE_Error(sprintf(
2842 2842
                 __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2843 2843
                 $this->get_this_model_name()
@@ -2973,13 +2973,13 @@  discard block
 block discarded – undo
2973 2973
                 || $this->get_primary_key_field()
2974 2974
                    instanceof
2975 2975
                    EE_Primary_Key_String_Field)
2976
-            && isset($fields_n_values[ $this->primary_key_name() ])
2976
+            && isset($fields_n_values[$this->primary_key_name()])
2977 2977
         ) {
2978
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2978
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2979 2979
         }
2980 2980
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2981 2981
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2982
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2982
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2983 2983
         }
2984 2984
         // if there is nothing to base this search on, then we shouldn't find anything
2985 2985
         if (empty($query_params)) {
@@ -3057,15 +3057,15 @@  discard block
 block discarded – undo
3057 3057
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3058 3058
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3059 3059
             if ($prepared_value !== null) {
3060
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3060
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3061 3061
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3062 3062
             }
3063 3063
         }
3064 3064
         if ($table instanceof EE_Secondary_Table && $new_id) {
3065 3065
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3066 3066
             // so add the fk to the main table as a column
3067
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3068
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3067
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3068
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
3069 3069
         }
3070 3070
         // insert the new entry
3071 3071
         $result = $this->_do_wpdb_query(
@@ -3082,7 +3082,7 @@  discard block
 block discarded – undo
3082 3082
             }
3083 3083
             // it's not an auto-increment primary key, so
3084 3084
             // it must have been supplied
3085
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3085
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3086 3086
         }
3087 3087
         // we can't return a  primary key because there is none. instead return
3088 3088
         // a unique string indicating this model
@@ -3104,16 +3104,16 @@  discard block
 block discarded – undo
3104 3104
     protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3105 3105
     {
3106 3106
         // if this field doesn't allow nullable, don't allow it
3107
-        if (! $field_obj->is_nullable()
3107
+        if ( ! $field_obj->is_nullable()
3108 3108
             && (
3109
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3110
-                || $fields_n_values[ $field_obj->get_name() ] === null
3109
+                ! isset($fields_n_values[$field_obj->get_name()])
3110
+                || $fields_n_values[$field_obj->get_name()] === null
3111 3111
             )
3112 3112
         ) {
3113
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3113
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3114 3114
         }
3115
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3116
-            ? $fields_n_values[ $field_obj->get_name() ]
3115
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3116
+            ? $fields_n_values[$field_obj->get_name()]
3117 3117
             : null;
3118 3118
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3119 3119
     }
@@ -3214,7 +3214,7 @@  discard block
 block discarded – undo
3214 3214
      */
3215 3215
     public function get_table_obj_by_alias($table_alias = '')
3216 3216
     {
3217
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3217
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3218 3218
     }
3219 3219
 
3220 3220
 
@@ -3229,7 +3229,7 @@  discard block
 block discarded – undo
3229 3229
         $other_tables = array();
3230 3230
         foreach ($this->_tables as $table_alias => $table) {
3231 3231
             if ($table instanceof EE_Secondary_Table) {
3232
-                $other_tables[ $table_alias ] = $table;
3232
+                $other_tables[$table_alias] = $table;
3233 3233
             }
3234 3234
         }
3235 3235
         return $other_tables;
@@ -3245,7 +3245,7 @@  discard block
 block discarded – undo
3245 3245
      */
3246 3246
     public function _get_fields_for_table($table_alias)
3247 3247
     {
3248
-        return $this->_fields[ $table_alias ];
3248
+        return $this->_fields[$table_alias];
3249 3249
     }
3250 3250
 
3251 3251
 
@@ -3274,7 +3274,7 @@  discard block
 block discarded – undo
3274 3274
                     $query_info_carrier,
3275 3275
                     'group_by'
3276 3276
                 );
3277
-            } elseif (! empty($query_params['group_by'])) {
3277
+            } elseif ( ! empty($query_params['group_by'])) {
3278 3278
                 $this->_extract_related_model_info_from_query_param(
3279 3279
                     $query_params['group_by'],
3280 3280
                     $query_info_carrier,
@@ -3296,7 +3296,7 @@  discard block
 block discarded – undo
3296 3296
                     $query_info_carrier,
3297 3297
                     'order_by'
3298 3298
                 );
3299
-            } elseif (! empty($query_params['order_by'])) {
3299
+            } elseif ( ! empty($query_params['order_by'])) {
3300 3300
                 $this->_extract_related_model_info_from_query_param(
3301 3301
                     $query_params['order_by'],
3302 3302
                     $query_info_carrier,
@@ -3332,7 +3332,7 @@  discard block
 block discarded – undo
3332 3332
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3333 3333
         $query_param_type
3334 3334
     ) {
3335
-        if (! empty($sub_query_params)) {
3335
+        if ( ! empty($sub_query_params)) {
3336 3336
             $sub_query_params = (array) $sub_query_params;
3337 3337
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3338 3338
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3347,7 +3347,7 @@  discard block
 block discarded – undo
3347 3347
                 // of array('Registration.TXN_ID'=>23)
3348 3348
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3349 3349
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3350
-                    if (! is_array($possibly_array_of_params)) {
3350
+                    if ( ! is_array($possibly_array_of_params)) {
3351 3351
                         throw new EE_Error(sprintf(
3352 3352
                             __(
3353 3353
                                 "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
@@ -3370,7 +3370,7 @@  discard block
 block discarded – undo
3370 3370
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3371 3371
                     // indicating that $possible_array_of_params[1] is actually a field name,
3372 3372
                     // from which we should extract query parameters!
3373
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3373
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3374 3374
                         throw new EE_Error(sprintf(__(
3375 3375
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3376 3376
                             "event_espresso"
@@ -3405,8 +3405,8 @@  discard block
 block discarded – undo
3405 3405
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3406 3406
         $query_param_type
3407 3407
     ) {
3408
-        if (! empty($sub_query_params)) {
3409
-            if (! is_array($sub_query_params)) {
3408
+        if ( ! empty($sub_query_params)) {
3409
+            if ( ! is_array($sub_query_params)) {
3410 3410
                 throw new EE_Error(sprintf(
3411 3411
                     __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3412 3412
                     $sub_query_params
@@ -3440,7 +3440,7 @@  discard block
 block discarded – undo
3440 3440
      */
3441 3441
     public function _create_model_query_info_carrier($query_params)
3442 3442
     {
3443
-        if (! is_array($query_params)) {
3443
+        if ( ! is_array($query_params)) {
3444 3444
             EE_Error::doing_it_wrong(
3445 3445
                 'EEM_Base::_create_model_query_info_carrier',
3446 3446
                 sprintf(
@@ -3515,7 +3515,7 @@  discard block
 block discarded – undo
3515 3515
         // set limit
3516 3516
         if (array_key_exists('limit', $query_params)) {
3517 3517
             if (is_array($query_params['limit'])) {
3518
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3518
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3519 3519
                     $e = sprintf(
3520 3520
                         __(
3521 3521
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3523,12 +3523,12 @@  discard block
 block discarded – undo
3523 3523
                         ),
3524 3524
                         http_build_query($query_params['limit'])
3525 3525
                     );
3526
-                    throw new EE_Error($e . "|" . $e);
3526
+                    throw new EE_Error($e."|".$e);
3527 3527
                 }
3528 3528
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3529
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3530
-            } elseif (! empty($query_params['limit'])) {
3531
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3529
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3530
+            } elseif ( ! empty($query_params['limit'])) {
3531
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3532 3532
             }
3533 3533
         }
3534 3534
         // set order by
@@ -3560,10 +3560,10 @@  discard block
 block discarded – undo
3560 3560
                 $order_array = array();
3561 3561
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3562 3562
                     $order = $this->_extract_order($order);
3563
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3563
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3564 3564
                 }
3565
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3566
-            } elseif (! empty($query_params['order_by'])) {
3565
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3566
+            } elseif ( ! empty($query_params['order_by'])) {
3567 3567
                 $this->_extract_related_model_info_from_query_param(
3568 3568
                     $query_params['order_by'],
3569 3569
                     $query_object,
@@ -3574,18 +3574,18 @@  discard block
 block discarded – undo
3574 3574
                     ? $this->_extract_order($query_params['order'])
3575 3575
                     : 'DESC';
3576 3576
                 $query_object->set_order_by_sql(
3577
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3577
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3578 3578
                 );
3579 3579
             }
3580 3580
         }
3581 3581
         // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3582
-        if (! array_key_exists('order_by', $query_params)
3582
+        if ( ! array_key_exists('order_by', $query_params)
3583 3583
             && array_key_exists('order', $query_params)
3584 3584
             && ! empty($query_params['order'])
3585 3585
         ) {
3586 3586
             $pk_field = $this->get_primary_key_field();
3587 3587
             $order = $this->_extract_order($query_params['order']);
3588
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3588
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3589 3589
         }
3590 3590
         // set group by
3591 3591
         if (array_key_exists('group_by', $query_params)) {
@@ -3595,10 +3595,10 @@  discard block
 block discarded – undo
3595 3595
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3596 3596
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3597 3597
                 }
3598
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3599
-            } elseif (! empty($query_params['group_by'])) {
3598
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3599
+            } elseif ( ! empty($query_params['group_by'])) {
3600 3600
                 $query_object->set_group_by_sql(
3601
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3601
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3602 3602
                 );
3603 3603
             }
3604 3604
         }
@@ -3608,7 +3608,7 @@  discard block
 block discarded – undo
3608 3608
         }
3609 3609
         // now, just verify they didn't pass anything wack
3610 3610
         foreach ($query_params as $query_key => $query_value) {
3611
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3611
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3612 3612
                 throw new EE_Error(
3613 3613
                     sprintf(
3614 3614
                         __(
@@ -3716,7 +3716,7 @@  discard block
 block discarded – undo
3716 3716
         $where_query_params = array()
3717 3717
     ) {
3718 3718
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3719
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3719
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3720 3720
             throw new EE_Error(sprintf(
3721 3721
                 __(
3722 3722
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3848,19 +3848,19 @@  discard block
 block discarded – undo
3848 3848
     ) {
3849 3849
         $null_friendly_where_conditions = array();
3850 3850
         $none_overridden = true;
3851
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3851
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3852 3852
         foreach ($default_where_conditions as $key => $val) {
3853
-            if (isset($provided_where_conditions[ $key ])) {
3853
+            if (isset($provided_where_conditions[$key])) {
3854 3854
                 $none_overridden = false;
3855 3855
             } else {
3856
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3856
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3857 3857
             }
3858 3858
         }
3859 3859
         if ($none_overridden && $default_where_conditions) {
3860 3860
             if ($model->has_primary_key_field()) {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3861
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3862 3862
                                                                                 . "."
3863
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3863
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3864 3864
             }/*else{
3865 3865
                 //@todo NO PK, use other defaults
3866 3866
             }*/
@@ -3966,7 +3966,7 @@  discard block
 block discarded – undo
3966 3966
             foreach ($tables as $table_obj) {
3967 3967
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3968 3968
                                        . $table_obj->get_fully_qualified_pk_column();
3969
-                if (! in_array($qualified_pk_column, $selects)) {
3969
+                if ( ! in_array($qualified_pk_column, $selects)) {
3970 3970
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3971 3971
                 }
3972 3972
             }
@@ -4115,9 +4115,9 @@  discard block
 block discarded – undo
4115 4115
         $query_parameter_type
4116 4116
     ) {
4117 4117
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4118
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4118
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4119 4119
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4120
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4120
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4121 4121
                 if ($possible_join_string === '') {
4122 4122
                     // nothing left to $query_param
4123 4123
                     // we should actually end in a field name, not a model like this!
@@ -4247,7 +4247,7 @@  discard block
 block discarded – undo
4247 4247
     {
4248 4248
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4249 4249
         if ($SQL) {
4250
-            return " WHERE " . $SQL;
4250
+            return " WHERE ".$SQL;
4251 4251
         }
4252 4252
         return '';
4253 4253
     }
@@ -4266,7 +4266,7 @@  discard block
 block discarded – undo
4266 4266
     {
4267 4267
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4268 4268
         if ($SQL) {
4269
-            return " HAVING " . $SQL;
4269
+            return " HAVING ".$SQL;
4270 4270
         }
4271 4271
         return '';
4272 4272
     }
@@ -4285,7 +4285,7 @@  discard block
 block discarded – undo
4285 4285
     {
4286 4286
         $where_clauses = array();
4287 4287
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4288
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4288
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4289 4289
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4290 4290
                 switch ($query_param) {
4291 4291
                     case 'not':
@@ -4319,7 +4319,7 @@  discard block
 block discarded – undo
4319 4319
             } else {
4320 4320
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4321 4321
                 // if it's not a normal field, maybe it's a custom selection?
4322
-                if (! $field_obj) {
4322
+                if ( ! $field_obj) {
4323 4323
                     if ($this->_custom_selections instanceof CustomSelects) {
4324 4324
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4325 4325
                     } else {
@@ -4330,7 +4330,7 @@  discard block
 block discarded – undo
4330 4330
                     }
4331 4331
                 }
4332 4332
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4333
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4333
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4334 4334
             }
4335 4335
         }
4336 4336
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4353,7 +4353,7 @@  discard block
 block discarded – undo
4353 4353
                 $field->get_model_name(),
4354 4354
                 $query_param
4355 4355
             );
4356
-            return $table_alias_prefix . $field->get_qualified_column();
4356
+            return $table_alias_prefix.$field->get_qualified_column();
4357 4357
         }
4358 4358
         if ($this->_custom_selections instanceof CustomSelects
4359 4359
             && in_array($query_param, $this->_custom_selections->columnAliases(), true)
@@ -4412,7 +4412,7 @@  discard block
 block discarded – undo
4412 4412
     {
4413 4413
         if (is_array($op_and_value)) {
4414 4414
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4415
-            if (! $operator) {
4415
+            if ( ! $operator) {
4416 4416
                 $php_array_like_string = array();
4417 4417
                 foreach ($op_and_value as $key => $value) {
4418 4418
                     $php_array_like_string[] = "$key=>$value";
@@ -4434,14 +4434,14 @@  discard block
 block discarded – undo
4434 4434
         }
4435 4435
         // check to see if the value is actually another field
4436 4436
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4437
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4437
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4438 4438
         }
4439 4439
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4440 4440
             // in this case, the value should be an array, or at least a comma-separated list
4441 4441
             // it will need to handle a little differently
4442 4442
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4443 4443
             // note: $cleaned_value has already been run through $wpdb->prepare()
4444
-            return $operator . SP . $cleaned_value;
4444
+            return $operator.SP.$cleaned_value;
4445 4445
         }
4446 4446
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4447 4447
             // the value should be an array with count of two.
@@ -4457,7 +4457,7 @@  discard block
 block discarded – undo
4457 4457
                 );
4458 4458
             }
4459 4459
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4460
-            return $operator . SP . $cleaned_value;
4460
+            return $operator.SP.$cleaned_value;
4461 4461
         }
4462 4462
         if (in_array($operator, $this->valid_null_style_operators())) {
4463 4463
             if ($value !== null) {
@@ -4477,10 +4477,10 @@  discard block
 block discarded – undo
4477 4477
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4478 4478
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4479 4479
             // remove other junk. So just treat it as a string.
4480
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4480
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4481 4481
         }
4482
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4483
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4482
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4483
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4484 4484
         }
4485 4485
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4486 4486
             throw new EE_Error(
@@ -4494,7 +4494,7 @@  discard block
 block discarded – undo
4494 4494
                 )
4495 4495
             );
4496 4496
         }
4497
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4497
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4498 4498
             throw new EE_Error(
4499 4499
                 sprintf(
4500 4500
                     __(
@@ -4534,7 +4534,7 @@  discard block
 block discarded – undo
4534 4534
         foreach ($values as $value) {
4535 4535
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4536 4536
         }
4537
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4537
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4538 4538
     }
4539 4539
 
4540 4540
 
@@ -4575,7 +4575,7 @@  discard block
 block discarded – undo
4575 4575
                                 . $main_table->get_table_name()
4576 4576
                                 . " WHERE FALSE";
4577 4577
         }
4578
-        return "(" . implode(",", $cleaned_values) . ")";
4578
+        return "(".implode(",", $cleaned_values).")";
4579 4579
     }
4580 4580
 
4581 4581
 
@@ -4596,7 +4596,7 @@  discard block
 block discarded – undo
4596 4596
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4597 4597
             );
4598 4598
         } //$field_obj should really just be a data type
4599
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4599
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4600 4600
             throw new EE_Error(
4601 4601
                 sprintf(
4602 4602
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4629,14 +4629,14 @@  discard block
 block discarded – undo
4629 4629
             ), $query_param_name));
4630 4630
         }
4631 4631
         $number_of_parts = count($query_param_parts);
4632
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4632
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4633 4633
         if ($number_of_parts === 1) {
4634 4634
             $field_name = $last_query_param_part;
4635 4635
             $model_obj = $this;
4636 4636
         } else {// $number_of_parts >= 2
4637 4637
             // the last part is the column name, and there are only 2parts. therefore...
4638 4638
             $field_name = $last_query_param_part;
4639
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4639
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4640 4640
         }
4641 4641
         try {
4642 4642
             return $model_obj->field_settings_for($field_name);
@@ -4658,7 +4658,7 @@  discard block
 block discarded – undo
4658 4658
     public function _get_qualified_column_for_field($field_name)
4659 4659
     {
4660 4660
         $all_fields = $this->field_settings();
4661
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4661
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4662 4662
         if ($field) {
4663 4663
             return $field->get_qualified_column();
4664 4664
         }
@@ -4729,10 +4729,10 @@  discard block
 block discarded – undo
4729 4729
      */
4730 4730
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4731 4731
     {
4732
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4732
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4733 4733
         $qualified_columns = array();
4734 4734
         foreach ($this->field_settings() as $field_name => $field) {
4735
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4735
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4736 4736
         }
4737 4737
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4738 4738
     }
@@ -4756,11 +4756,11 @@  discard block
 block discarded – undo
4756 4756
             if ($table_obj instanceof EE_Primary_Table) {
4757 4757
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4758 4758
                     ? $table_obj->get_select_join_limit($limit)
4759
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4759
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4760 4760
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4761 4761
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4762 4762
                     ? $table_obj->get_select_join_limit_join($limit)
4763
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4763
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4764 4764
             }
4765 4765
         }
4766 4766
         return $SQL;
@@ -4832,7 +4832,7 @@  discard block
 block discarded – undo
4832 4832
         foreach ($this->field_settings() as $field_obj) {
4833 4833
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4834 4834
             /** @var $field_obj EE_Model_Field_Base */
4835
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4835
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4836 4836
         }
4837 4837
         return $data_types;
4838 4838
     }
@@ -4848,14 +4848,14 @@  discard block
 block discarded – undo
4848 4848
      */
4849 4849
     public function get_related_model_obj($model_name)
4850 4850
     {
4851
-        $model_classname = "EEM_" . $model_name;
4852
-        if (! class_exists($model_classname)) {
4851
+        $model_classname = "EEM_".$model_name;
4852
+        if ( ! class_exists($model_classname)) {
4853 4853
             throw new EE_Error(sprintf(__(
4854 4854
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4855 4855
                 'event_espresso'
4856 4856
             ), $model_name, $model_classname));
4857 4857
         }
4858
-        return call_user_func($model_classname . "::instance");
4858
+        return call_user_func($model_classname."::instance");
4859 4859
     }
4860 4860
 
4861 4861
 
@@ -4884,7 +4884,7 @@  discard block
 block discarded – undo
4884 4884
         $belongs_to_relations = array();
4885 4885
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4886 4886
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4887
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4887
+                $belongs_to_relations[$model_name] = $relation_obj;
4888 4888
             }
4889 4889
         }
4890 4890
         return $belongs_to_relations;
@@ -4902,7 +4902,7 @@  discard block
 block discarded – undo
4902 4902
     public function related_settings_for($relation_name)
4903 4903
     {
4904 4904
         $relatedModels = $this->relation_settings();
4905
-        if (! array_key_exists($relation_name, $relatedModels)) {
4905
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4906 4906
             throw new EE_Error(
4907 4907
                 sprintf(
4908 4908
                     __(
@@ -4915,7 +4915,7 @@  discard block
 block discarded – undo
4915 4915
                 )
4916 4916
             );
4917 4917
         }
4918
-        return $relatedModels[ $relation_name ];
4918
+        return $relatedModels[$relation_name];
4919 4919
     }
4920 4920
 
4921 4921
 
@@ -4932,14 +4932,14 @@  discard block
 block discarded – undo
4932 4932
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4933 4933
     {
4934 4934
         $fieldSettings = $this->field_settings($include_db_only_fields);
4935
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4935
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4936 4936
             throw new EE_Error(sprintf(
4937 4937
                 __("There is no field/column '%s' on '%s'", 'event_espresso'),
4938 4938
                 $fieldName,
4939 4939
                 get_class($this)
4940 4940
             ));
4941 4941
         }
4942
-        return $fieldSettings[ $fieldName ];
4942
+        return $fieldSettings[$fieldName];
4943 4943
     }
4944 4944
 
4945 4945
 
@@ -4953,7 +4953,7 @@  discard block
 block discarded – undo
4953 4953
     public function has_field($fieldName)
4954 4954
     {
4955 4955
         $fieldSettings = $this->field_settings(true);
4956
-        if (isset($fieldSettings[ $fieldName ])) {
4956
+        if (isset($fieldSettings[$fieldName])) {
4957 4957
             return true;
4958 4958
         }
4959 4959
         return false;
@@ -4970,7 +4970,7 @@  discard block
 block discarded – undo
4970 4970
     public function has_relation($relation_name)
4971 4971
     {
4972 4972
         $relations = $this->relation_settings();
4973
-        if (isset($relations[ $relation_name ])) {
4973
+        if (isset($relations[$relation_name])) {
4974 4974
             return true;
4975 4975
         }
4976 4976
         return false;
@@ -5008,7 +5008,7 @@  discard block
 block discarded – undo
5008 5008
                     break;
5009 5009
                 }
5010 5010
             }
5011
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5011
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5012 5012
                 throw new EE_Error(sprintf(
5013 5013
                     __("There is no Primary Key defined on model %s", 'event_espresso'),
5014 5014
                     get_class($this)
@@ -5069,23 +5069,23 @@  discard block
 block discarded – undo
5069 5069
      */
5070 5070
     public function get_foreign_key_to($model_name)
5071 5071
     {
5072
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5072
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5073 5073
             foreach ($this->field_settings() as $field) {
5074 5074
                 if ($field instanceof EE_Foreign_Key_Field_Base
5075 5075
                     && in_array($model_name, $field->get_model_names_pointed_to())
5076 5076
                 ) {
5077
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5077
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5078 5078
                     break;
5079 5079
                 }
5080 5080
             }
5081
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5081
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5082 5082
                 throw new EE_Error(sprintf(__(
5083 5083
                     "There is no foreign key field pointing to model %s on model %s",
5084 5084
                     'event_espresso'
5085 5085
                 ), $model_name, get_class($this)));
5086 5086
             }
5087 5087
         }
5088
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5088
+        return $this->_cache_foreign_key_to_fields[$model_name];
5089 5089
     }
5090 5090
 
5091 5091
 
@@ -5101,7 +5101,7 @@  discard block
 block discarded – undo
5101 5101
     public function get_table_for_alias($table_alias)
5102 5102
     {
5103 5103
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5104
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5104
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5105 5105
     }
5106 5106
 
5107 5107
 
@@ -5120,7 +5120,7 @@  discard block
 block discarded – undo
5120 5120
                 $this->_cached_fields = array();
5121 5121
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5122 5122
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5123
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5123
+                        $this->_cached_fields[$field_name] = $field_obj;
5124 5124
                     }
5125 5125
                 }
5126 5126
             }
@@ -5131,8 +5131,8 @@  discard block
 block discarded – undo
5131 5131
             foreach ($this->_fields as $fields_corresponding_to_table) {
5132 5132
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5133 5133
                     /** @var $field_obj EE_Model_Field_Base */
5134
-                    if (! $field_obj->is_db_only_field()) {
5135
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5134
+                    if ( ! $field_obj->is_db_only_field()) {
5135
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5136 5136
                     }
5137 5137
                 }
5138 5138
             }
@@ -5173,12 +5173,12 @@  discard block
 block discarded – undo
5173 5173
                     $primary_key_field->get_qualified_column(),
5174 5174
                     $primary_key_field->get_table_column()
5175 5175
                 );
5176
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5176
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5177 5177
                     continue;
5178 5178
                 }
5179 5179
             }
5180 5180
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5181
-            if (! $classInstance) {
5181
+            if ( ! $classInstance) {
5182 5182
                 throw new EE_Error(
5183 5183
                     sprintf(
5184 5184
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5191,7 +5191,7 @@  discard block
 block discarded – undo
5191 5191
             $classInstance->set_timezone($this->_timezone);
5192 5192
             // make sure if there is any timezone setting present that we set the timezone for the object
5193 5193
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5194
-            $array_of_objects[ $key ] = $classInstance;
5194
+            $array_of_objects[$key] = $classInstance;
5195 5195
             // also, for all the relations of type BelongsTo, see if we can cache
5196 5196
             // those related models
5197 5197
             // (we could do this for other relations too, but if there are conditions
@@ -5235,9 +5235,9 @@  discard block
 block discarded – undo
5235 5235
         $results = array();
5236 5236
         if ($this->_custom_selections instanceof CustomSelects) {
5237 5237
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5238
-                if (isset($db_results_row[ $alias ])) {
5239
-                    $results[ $alias ] = $this->convertValueToDataType(
5240
-                        $db_results_row[ $alias ],
5238
+                if (isset($db_results_row[$alias])) {
5239
+                    $results[$alias] = $this->convertValueToDataType(
5240
+                        $db_results_row[$alias],
5241 5241
                         $this->_custom_selections->getDataTypeForAlias($alias)
5242 5242
                     );
5243 5243
                 }
@@ -5279,7 +5279,7 @@  discard block
 block discarded – undo
5279 5279
         $this_model_fields_and_values = array();
5280 5280
         // setup the row using default values;
5281 5281
         foreach ($this->field_settings() as $field_name => $field_obj) {
5282
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5282
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5283 5283
         }
5284 5284
         $className = $this->_get_class_name();
5285 5285
         $classInstance = EE_Registry::instance()
@@ -5297,20 +5297,20 @@  discard block
 block discarded – undo
5297 5297
      */
5298 5298
     public function instantiate_class_from_array_or_object($cols_n_values)
5299 5299
     {
5300
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5300
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5301 5301
             $cols_n_values = get_object_vars($cols_n_values);
5302 5302
         }
5303 5303
         $primary_key = null;
5304 5304
         // make sure the array only has keys that are fields/columns on this model
5305 5305
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5306
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5307
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5306
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5307
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5308 5308
         }
5309 5309
         $className = $this->_get_class_name();
5310 5310
         // check we actually found results that we can use to build our model object
5311 5311
         // if not, return null
5312 5312
         if ($this->has_primary_key_field()) {
5313
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5313
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5314 5314
                 return null;
5315 5315
             }
5316 5316
         } elseif ($this->unique_indexes()) {
@@ -5322,7 +5322,7 @@  discard block
 block discarded – undo
5322 5322
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5323 5323
         if ($primary_key) {
5324 5324
             $classInstance = $this->get_from_entity_map($primary_key);
5325
-            if (! $classInstance) {
5325
+            if ( ! $classInstance) {
5326 5326
                 $classInstance = EE_Registry::instance()
5327 5327
                                             ->load_class(
5328 5328
                                                 $className,
@@ -5355,8 +5355,8 @@  discard block
 block discarded – undo
5355 5355
      */
5356 5356
     public function get_from_entity_map($id)
5357 5357
     {
5358
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5359
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5358
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5359
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5360 5360
     }
5361 5361
 
5362 5362
 
@@ -5379,7 +5379,7 @@  discard block
 block discarded – undo
5379 5379
     public function add_to_entity_map(EE_Base_Class $object)
5380 5380
     {
5381 5381
         $className = $this->_get_class_name();
5382
-        if (! $object instanceof $className) {
5382
+        if ( ! $object instanceof $className) {
5383 5383
             throw new EE_Error(sprintf(
5384 5384
                 __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5385 5385
                 is_object($object) ? get_class($object) : $object,
@@ -5387,7 +5387,7 @@  discard block
 block discarded – undo
5387 5387
             ));
5388 5388
         }
5389 5389
         /** @var $object EE_Base_Class */
5390
-        if (! $object->ID()) {
5390
+        if ( ! $object->ID()) {
5391 5391
             throw new EE_Error(sprintf(__(
5392 5392
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5393 5393
                 "event_espresso"
@@ -5398,7 +5398,7 @@  discard block
 block discarded – undo
5398 5398
         if ($classInstance) {
5399 5399
             return $classInstance;
5400 5400
         }
5401
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5401
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5402 5402
         return $object;
5403 5403
     }
5404 5404
 
@@ -5414,11 +5414,11 @@  discard block
 block discarded – undo
5414 5414
     public function clear_entity_map($id = null)
5415 5415
     {
5416 5416
         if (empty($id)) {
5417
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5417
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5418 5418
             return true;
5419 5419
         }
5420
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5421
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5420
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5421
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5422 5422
             return true;
5423 5423
         }
5424 5424
         return false;
@@ -5461,17 +5461,17 @@  discard block
 block discarded – undo
5461 5461
             // there is a primary key on this table and its not set. Use defaults for all its columns
5462 5462
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5463 5463
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5464
-                    if (! $field_obj->is_db_only_field()) {
5464
+                    if ( ! $field_obj->is_db_only_field()) {
5465 5465
                         // prepare field as if its coming from db
5466 5466
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5467
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5467
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5468 5468
                     }
5469 5469
                 }
5470 5470
             } else {
5471 5471
                 // the table's rows existed. Use their values
5472 5472
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5473
-                    if (! $field_obj->is_db_only_field()) {
5474
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5473
+                    if ( ! $field_obj->is_db_only_field()) {
5474
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5475 5475
                             $cols_n_values,
5476 5476
                             $field_obj->get_qualified_column(),
5477 5477
                             $field_obj->get_table_column()
@@ -5497,10 +5497,10 @@  discard block
 block discarded – undo
5497 5497
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5498 5498
         // does the field on the model relate to this column retrieved from the db?
5499 5499
         // or is it a db-only field? (not relating to the model)
5500
-        if (isset($cols_n_values[ $qualified_column ])) {
5501
-            $value = $cols_n_values[ $qualified_column ];
5502
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5503
-            $value = $cols_n_values[ $regular_column ];
5500
+        if (isset($cols_n_values[$qualified_column])) {
5501
+            $value = $cols_n_values[$qualified_column];
5502
+        } elseif (isset($cols_n_values[$regular_column])) {
5503
+            $value = $cols_n_values[$regular_column];
5504 5504
         }
5505 5505
         return $value;
5506 5506
     }
@@ -5533,7 +5533,7 @@  discard block
 block discarded – undo
5533 5533
                     $obj_in_map->clear_cache($relation_name, null, true);
5534 5534
                 }
5535 5535
             }
5536
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5536
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5537 5537
             return $obj_in_map;
5538 5538
         }
5539 5539
         return $this->get_one_by_ID($id);
@@ -5586,7 +5586,7 @@  discard block
 block discarded – undo
5586 5586
      */
5587 5587
     private function _get_class_name()
5588 5588
     {
5589
-        return "EE_" . $this->get_this_model_name();
5589
+        return "EE_".$this->get_this_model_name();
5590 5590
     }
5591 5591
 
5592 5592
 
@@ -5634,7 +5634,7 @@  discard block
 block discarded – undo
5634 5634
     {
5635 5635
         $className = get_class($this);
5636 5636
         $tagName = "FHEE__{$className}__{$methodName}";
5637
-        if (! has_filter($tagName)) {
5637
+        if ( ! has_filter($tagName)) {
5638 5638
             throw new EE_Error(
5639 5639
                 sprintf(
5640 5640
                     __(
@@ -5805,7 +5805,7 @@  discard block
 block discarded – undo
5805 5805
         $unique_indexes = array();
5806 5806
         foreach ($this->_indexes as $name => $index) {
5807 5807
             if ($index instanceof EE_Unique_Index) {
5808
-                $unique_indexes [ $name ] = $index;
5808
+                $unique_indexes [$name] = $index;
5809 5809
             }
5810 5810
         }
5811 5811
         return $unique_indexes;
@@ -5868,7 +5868,7 @@  discard block
 block discarded – undo
5868 5868
         $key_vals_in_combined_pk = array();
5869 5869
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5870 5870
         foreach ($key_fields as $key_field_name => $field_obj) {
5871
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5871
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5872 5872
                 return null;
5873 5873
             }
5874 5874
         }
@@ -5889,7 +5889,7 @@  discard block
 block discarded – undo
5889 5889
     {
5890 5890
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5891 5891
         foreach ($keys_it_should_have as $key) {
5892
-            if (! isset($key_vals[ $key ])) {
5892
+            if ( ! isset($key_vals[$key])) {
5893 5893
                 return false;
5894 5894
             }
5895 5895
         }
@@ -5922,8 +5922,8 @@  discard block
 block discarded – undo
5922 5922
         }
5923 5923
         // even copies obviously won't have the same ID, so remove the primary key
5924 5924
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5925
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5926
-            unset($attributes_array[ $this->primary_key_name() ]);
5925
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5926
+            unset($attributes_array[$this->primary_key_name()]);
5927 5927
         }
5928 5928
         if (isset($query_params[0])) {
5929 5929
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5945,7 +5945,7 @@  discard block
 block discarded – undo
5945 5945
      */
5946 5946
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5947 5947
     {
5948
-        if (! is_array($query_params)) {
5948
+        if ( ! is_array($query_params)) {
5949 5949
             EE_Error::doing_it_wrong(
5950 5950
                 'EEM_Base::get_one_copy',
5951 5951
                 sprintf(
@@ -5995,7 +5995,7 @@  discard block
 block discarded – undo
5995 5995
      */
5996 5996
     private function _prepare_operator_for_sql($operator_supplied)
5997 5997
     {
5998
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5998
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5999 5999
             : null;
6000 6000
         if ($sql_operator) {
6001 6001
             return $sql_operator;
@@ -6086,7 +6086,7 @@  discard block
 block discarded – undo
6086 6086
         $objs = $this->get_all($query_params);
6087 6087
         $names = array();
6088 6088
         foreach ($objs as $obj) {
6089
-            $names[ $obj->ID() ] = $obj->name();
6089
+            $names[$obj->ID()] = $obj->name();
6090 6090
         }
6091 6091
         return $names;
6092 6092
     }
@@ -6107,7 +6107,7 @@  discard block
 block discarded – undo
6107 6107
      */
6108 6108
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6109 6109
     {
6110
-        if (! $this->has_primary_key_field()) {
6110
+        if ( ! $this->has_primary_key_field()) {
6111 6111
             if (WP_DEBUG) {
6112 6112
                 EE_Error::add_error(
6113 6113
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6120,7 +6120,7 @@  discard block
 block discarded – undo
6120 6120
         $IDs = array();
6121 6121
         foreach ($model_objects as $model_object) {
6122 6122
             $id = $model_object->ID();
6123
-            if (! $id) {
6123
+            if ( ! $id) {
6124 6124
                 if ($filter_out_empty_ids) {
6125 6125
                     continue;
6126 6126
                 }
@@ -6170,22 +6170,22 @@  discard block
 block discarded – undo
6170 6170
     {
6171 6171
         EEM_Base::verify_is_valid_cap_context($context);
6172 6172
         // check if we ought to run the restriction generator first
6173
-        if (isset($this->_cap_restriction_generators[ $context ])
6174
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6175
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6173
+        if (isset($this->_cap_restriction_generators[$context])
6174
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6175
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6176 6176
         ) {
6177
-            $this->_cap_restrictions[ $context ] = array_merge(
6178
-                $this->_cap_restrictions[ $context ],
6179
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6177
+            $this->_cap_restrictions[$context] = array_merge(
6178
+                $this->_cap_restrictions[$context],
6179
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6180 6180
             );
6181 6181
         }
6182 6182
         // and make sure we've finalized the construction of each restriction
6183
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6183
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6184 6184
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6185 6185
                 $where_conditions_obj->_finalize_construct($this);
6186 6186
             }
6187 6187
         }
6188
-        return $this->_cap_restrictions[ $context ];
6188
+        return $this->_cap_restrictions[$context];
6189 6189
     }
6190 6190
 
6191 6191
 
@@ -6215,10 +6215,10 @@  discard block
 block discarded – undo
6215 6215
         $missing_caps = array();
6216 6216
         $cap_restrictions = $this->cap_restrictions($context);
6217 6217
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6218
-            if (! EE_Capabilities::instance()
6219
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6218
+            if ( ! EE_Capabilities::instance()
6219
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6220 6220
             ) {
6221
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6221
+                $missing_caps[$cap] = $restriction_if_no_cap;
6222 6222
             }
6223 6223
         }
6224 6224
         return $missing_caps;
@@ -6253,8 +6253,8 @@  discard block
 block discarded – undo
6253 6253
     public function cap_action_for_context($context)
6254 6254
     {
6255 6255
         $mapping = $this->cap_contexts_to_cap_action_map();
6256
-        if (isset($mapping[ $context ])) {
6257
-            return $mapping[ $context ];
6256
+        if (isset($mapping[$context])) {
6257
+            return $mapping[$context];
6258 6258
         }
6259 6259
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6260 6260
             return $action;
@@ -6371,7 +6371,7 @@  discard block
 block discarded – undo
6371 6371
     {
6372 6372
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6373 6373
             if ($query_param_key === $logic_query_param_key
6374
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6374
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6375 6375
             ) {
6376 6376
                 return true;
6377 6377
             }
Please login to merge, or discard this patch.
core/db_classes/EE_Registration.class.php 3 patches
Doc Comments   +4 added lines, -3 removed lines patch added patch discarded remove patch
@@ -1164,7 +1164,7 @@  discard block
 block discarded – undo
1164 1164
      * Sets deleted
1165 1165
      *
1166 1166
      * @param boolean $deleted
1167
-     * @return bool
1167
+     * @return boolean|null
1168 1168
      * @throws EE_Error
1169 1169
      * @throws RuntimeException
1170 1170
      */
@@ -1222,6 +1222,7 @@  discard block
 block discarded – undo
1222 1222
      * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1223 1223
      * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1224 1224
      *                                          consider registration status as well as datetime access.
1225
+     * @param integer $DTT_OR_ID
1225 1226
      * @return bool
1226 1227
      * @throws EE_Error
1227 1228
      */
@@ -1392,7 +1393,7 @@  discard block
 block discarded – undo
1392 1393
      * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1393 1394
      * "Latest" is defined by the `DTT_EVT_start` column.
1394 1395
      *
1395
-     * @return EE_Datetime|null
1396
+     * @return null|EE_Base_Class
1396 1397
      * @throws EE_Error
1397 1398
      */
1398 1399
     public function get_latest_related_datetime()
@@ -1688,7 +1689,7 @@  discard block
 block discarded – undo
1688 1689
      * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1689 1690
      * Note: if there are no payments on the registration there will be no payment method returned.
1690 1691
      *
1691
-     * @return EE_Payment_Method|null
1692
+     * @return null|EE_Base_Class
1692 1693
      */
1693 1694
     public function payment_method()
1694 1695
     {
Please login to merge, or discard this patch.
Indentation   +2067 added lines, -2067 removed lines patch added patch discarded remove patch
@@ -17,2071 +17,2071 @@
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * Used to reference when a registration has never been checked in.
22
-     *
23
-     * @deprecated use \EE_Checkin::status_checked_never instead
24
-     * @type int
25
-     */
26
-    const checkin_status_never = 2;
27
-
28
-    /**
29
-     * Used to reference when a registration has been checked in.
30
-     *
31
-     * @deprecated use \EE_Checkin::status_checked_in instead
32
-     * @type int
33
-     */
34
-    const checkin_status_in = 1;
35
-
36
-
37
-    /**
38
-     * Used to reference when a registration has been checked out.
39
-     *
40
-     * @deprecated use \EE_Checkin::status_checked_out instead
41
-     * @type int
42
-     */
43
-    const checkin_status_out = 0;
44
-
45
-
46
-    /**
47
-     * extra meta key for tracking reg status os trashed registrations
48
-     *
49
-     * @type string
50
-     */
51
-    const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
-
53
-
54
-    /**
55
-     * extra meta key for tracking if registration has reserved ticket
56
-     *
57
-     * @type string
58
-     */
59
-    const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
60
-
61
-
62
-    /**
63
-     * @param array  $props_n_values          incoming values
64
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
65
-     *                                        used.)
66
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
67
-     *                                        date_format and the second value is the time format
68
-     * @return EE_Registration
69
-     * @throws EE_Error
70
-     */
71
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
72
-    {
73
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
74
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
75
-    }
76
-
77
-
78
-    /**
79
-     * @param array  $props_n_values  incoming values from the database
80
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
-     *                                the website will be used.
82
-     * @return EE_Registration
83
-     */
84
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
85
-    {
86
-        return new self($props_n_values, true, $timezone);
87
-    }
88
-
89
-
90
-    /**
91
-     *        Set Event ID
92
-     *
93
-     * @param        int $EVT_ID Event ID
94
-     * @throws EE_Error
95
-     * @throws RuntimeException
96
-     */
97
-    public function set_event($EVT_ID = 0)
98
-    {
99
-        $this->set('EVT_ID', $EVT_ID);
100
-    }
101
-
102
-
103
-    /**
104
-     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
105
-     * be routed to internal methods
106
-     *
107
-     * @param string $field_name
108
-     * @param mixed  $field_value
109
-     * @param bool   $use_default
110
-     * @throws EE_Error
111
-     * @throws EntityNotFoundException
112
-     * @throws InvalidArgumentException
113
-     * @throws InvalidDataTypeException
114
-     * @throws InvalidInterfaceException
115
-     * @throws ReflectionException
116
-     * @throws RuntimeException
117
-     */
118
-    public function set($field_name, $field_value, $use_default = false)
119
-    {
120
-        switch ($field_name) {
121
-            case 'REG_code':
122
-                if (! empty($field_value) && $this->reg_code() === null) {
123
-                    $this->set_reg_code($field_value, $use_default);
124
-                }
125
-                break;
126
-            case 'STS_ID':
127
-                $this->set_status($field_value, $use_default);
128
-                break;
129
-            default:
130
-                parent::set($field_name, $field_value, $use_default);
131
-        }
132
-    }
133
-
134
-
135
-    /**
136
-     * Set Status ID
137
-     * updates the registration status and ALSO...
138
-     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
139
-     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
140
-     *
141
-     * @param string                $new_STS_ID
142
-     * @param boolean               $use_default
143
-     * @param ContextInterface|null $context
144
-     * @return bool
145
-     * @throws EE_Error
146
-     * @throws EntityNotFoundException
147
-     * @throws InvalidArgumentException
148
-     * @throws ReflectionException
149
-     * @throws RuntimeException
150
-     * @throws InvalidDataTypeException
151
-     * @throws InvalidInterfaceException
152
-     */
153
-    public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
154
-    {
155
-        // get current REG_Status
156
-        $old_STS_ID = $this->status_ID();
157
-        // if status has changed
158
-        if ($old_STS_ID !== $new_STS_ID // and that status has actually changed
159
-            && ! empty($old_STS_ID) // and that old status is actually set
160
-            && ! empty($new_STS_ID) // as well as the new status
161
-            && $this->ID() // ensure registration is in the db
162
-        ) {
163
-            // TO approved
164
-            if ($new_STS_ID === EEM_Registration::status_id_approved) {
165
-                // reserve a space by incrementing ticket and datetime sold values
166
-                $this->_reserve_registration_space();
167
-                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
168
-                // OR FROM  approved
169
-            } elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
170
-                // release a space by decrementing ticket and datetime sold values
171
-                $this->_release_registration_space();
172
-                do_action(
173
-                    'AHEE__EE_Registration__set_status__from_approved',
174
-                    $this,
175
-                    $old_STS_ID,
176
-                    $new_STS_ID,
177
-                    $context
178
-                );
179
-            }
180
-            // update status
181
-            parent::set('STS_ID', $new_STS_ID, $use_default);
182
-            $this->_update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, $context);
183
-            if ($this->statusChangeUpdatesTransaction($context)) {
184
-                $this->updateTransactionAfterStatusChange();
185
-            }
186
-            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
187
-            return true;
188
-        }
189
-        // even though the old value matches the new value, it's still good to
190
-        // allow the parent set method to have a say
191
-        parent::set('STS_ID', $new_STS_ID, $use_default);
192
-        return true;
193
-    }
194
-
195
-
196
-    /**
197
-     * update REGs and TXN when cancelled or declined registrations involved
198
-     *
199
-     * @param string                $new_STS_ID
200
-     * @param string                $old_STS_ID
201
-     * @param ContextInterface|null $context
202
-     * @throws EE_Error
203
-     * @throws InvalidArgumentException
204
-     * @throws InvalidDataTypeException
205
-     * @throws InvalidInterfaceException
206
-     * @throws ReflectionException
207
-     */
208
-    private function _update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
209
-    {
210
-        // these reg statuses should not be considered in any calculations involving monies owing
211
-        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
212
-        // true if registration has been cancelled or declined
213
-        $this->updateIfCanceled(
214
-            $closed_reg_statuses,
215
-            $new_STS_ID,
216
-            $old_STS_ID,
217
-            $context
218
-        );
219
-        $this->updateIfDeclined(
220
-            $closed_reg_statuses,
221
-            $new_STS_ID,
222
-            $old_STS_ID,
223
-            $context
224
-        );
225
-    }
226
-
227
-
228
-    /**
229
-     * update REGs and TXN when cancelled or declined registrations involved
230
-     *
231
-     * @param array                 $closed_reg_statuses
232
-     * @param string                $new_STS_ID
233
-     * @param string                $old_STS_ID
234
-     * @param ContextInterface|null $context
235
-     * @throws EE_Error
236
-     * @throws InvalidArgumentException
237
-     * @throws InvalidDataTypeException
238
-     * @throws InvalidInterfaceException
239
-     * @throws ReflectionException
240
-     */
241
-    private function updateIfCanceled(
242
-        array $closed_reg_statuses,
243
-        $new_STS_ID,
244
-        $old_STS_ID,
245
-        ContextInterface $context = null
246
-    ) {
247
-        // true if registration has been cancelled or declined
248
-        if (in_array($new_STS_ID, $closed_reg_statuses, true)
249
-            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
250
-        ) {
251
-            /** @type EE_Registration_Processor $registration_processor */
252
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
253
-            /** @type EE_Transaction_Processor $transaction_processor */
254
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
255
-            // cancelled or declined registration
256
-            $registration_processor->update_registration_after_being_canceled_or_declined(
257
-                $this,
258
-                $closed_reg_statuses
259
-            );
260
-            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
261
-                $this,
262
-                $closed_reg_statuses,
263
-                false
264
-            );
265
-            do_action(
266
-                'AHEE__EE_Registration__set_status__canceled_or_declined',
267
-                $this,
268
-                $old_STS_ID,
269
-                $new_STS_ID,
270
-                $context
271
-            );
272
-            return;
273
-        }
274
-    }
275
-
276
-
277
-    /**
278
-     * update REGs and TXN when cancelled or declined registrations involved
279
-     *
280
-     * @param array                 $closed_reg_statuses
281
-     * @param string                $new_STS_ID
282
-     * @param string                $old_STS_ID
283
-     * @param ContextInterface|null $context
284
-     * @throws EE_Error
285
-     * @throws InvalidArgumentException
286
-     * @throws InvalidDataTypeException
287
-     * @throws InvalidInterfaceException
288
-     * @throws ReflectionException
289
-     */
290
-    private function updateIfDeclined(
291
-        array $closed_reg_statuses,
292
-        $new_STS_ID,
293
-        $old_STS_ID,
294
-        ContextInterface $context = null
295
-    ) {
296
-        // true if reinstating cancelled or declined registration
297
-        if (in_array($old_STS_ID, $closed_reg_statuses, true)
298
-            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
299
-        ) {
300
-            /** @type EE_Registration_Processor $registration_processor */
301
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
302
-            /** @type EE_Transaction_Processor $transaction_processor */
303
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
304
-            // reinstating cancelled or declined registration
305
-            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
306
-                $this,
307
-                $closed_reg_statuses
308
-            );
309
-            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
310
-                $this,
311
-                $closed_reg_statuses,
312
-                false
313
-            );
314
-            do_action(
315
-                'AHEE__EE_Registration__set_status__after_reinstated',
316
-                $this,
317
-                $old_STS_ID,
318
-                $new_STS_ID,
319
-                $context
320
-            );
321
-        }
322
-    }
323
-
324
-
325
-    /**
326
-     * @param ContextInterface|null $context
327
-     * @return bool
328
-     */
329
-    private function statusChangeUpdatesTransaction(ContextInterface $context = null)
330
-    {
331
-        $contexts_that_do_not_update_transaction = (array) apply_filters(
332
-            'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
333
-            array('spco_reg_step_attendee_information_process_registrations'),
334
-            $context,
335
-            $this
336
-        );
337
-        return ! (
338
-            $context instanceof ContextInterface
339
-            && in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
340
-        );
341
-    }
342
-
343
-
344
-    /**
345
-     * @throws EE_Error
346
-     * @throws EntityNotFoundException
347
-     * @throws InvalidArgumentException
348
-     * @throws InvalidDataTypeException
349
-     * @throws InvalidInterfaceException
350
-     * @throws ReflectionException
351
-     * @throws RuntimeException
352
-     */
353
-    private function updateTransactionAfterStatusChange()
354
-    {
355
-        /** @type EE_Transaction_Payments $transaction_payments */
356
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
357
-        $transaction_payments->recalculate_transaction_total($this->transaction(), false);
358
-        $this->transaction()->update_status_based_on_total_paid(true);
359
-    }
360
-
361
-
362
-    /**
363
-     *        get Status ID
364
-     */
365
-    public function status_ID()
366
-    {
367
-        return $this->get('STS_ID');
368
-    }
369
-
370
-
371
-    /**
372
-     * Gets the ticket this registration is for
373
-     *
374
-     * @param boolean $include_archived whether to include archived tickets or not.
375
-     *
376
-     * @return EE_Ticket|EE_Base_Class
377
-     * @throws EE_Error
378
-     */
379
-    public function ticket($include_archived = true)
380
-    {
381
-        $query_params = array();
382
-        if ($include_archived) {
383
-            $query_params['default_where_conditions'] = 'none';
384
-        }
385
-        return $this->get_first_related('Ticket', $query_params);
386
-    }
387
-
388
-
389
-    /**
390
-     * Gets the event this registration is for
391
-     *
392
-     * @return EE_Event
393
-     * @throws EE_Error
394
-     * @throws EntityNotFoundException
395
-     */
396
-    public function event()
397
-    {
398
-        $event = $this->get_first_related('Event');
399
-        if (! $event instanceof \EE_Event) {
400
-            throw new EntityNotFoundException('Event ID', $this->event_ID());
401
-        }
402
-        return $event;
403
-    }
404
-
405
-
406
-    /**
407
-     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
408
-     * with the author of the event this registration is for.
409
-     *
410
-     * @since 4.5.0
411
-     * @return int
412
-     * @throws EE_Error
413
-     * @throws EntityNotFoundException
414
-     */
415
-    public function wp_user()
416
-    {
417
-        $event = $this->event();
418
-        if ($event instanceof EE_Event) {
419
-            return $event->wp_user();
420
-        }
421
-        return 0;
422
-    }
423
-
424
-
425
-    /**
426
-     * increments this registration's related ticket sold and corresponding datetime sold values
427
-     *
428
-     * @return void
429
-     * @throws DomainException
430
-     * @throws EE_Error
431
-     * @throws EntityNotFoundException
432
-     * @throws InvalidArgumentException
433
-     * @throws InvalidDataTypeException
434
-     * @throws InvalidInterfaceException
435
-     * @throws ReflectionException
436
-     * @throws UnexpectedEntityException
437
-     */
438
-    private function _reserve_registration_space()
439
-    {
440
-        // reserved ticket and datetime counts will be decremented as sold counts are incremented
441
-        // so stop tracking that this reg has a ticket reserved
442
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
443
-        $ticket = $this->ticket();
444
-        $ticket->increase_sold();
445
-        $ticket->save();
446
-        // possibly set event status to sold out
447
-        $this->event()->perform_sold_out_status_check();
448
-    }
449
-
450
-
451
-    /**
452
-     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
453
-     *
454
-     * @return void
455
-     * @throws DomainException
456
-     * @throws EE_Error
457
-     * @throws EntityNotFoundException
458
-     * @throws InvalidArgumentException
459
-     * @throws InvalidDataTypeException
460
-     * @throws InvalidInterfaceException
461
-     * @throws ReflectionException
462
-     * @throws UnexpectedEntityException
463
-     */
464
-    private function _release_registration_space()
465
-    {
466
-        $ticket = $this->ticket();
467
-        $ticket->decrease_sold();
468
-        $ticket->save();
469
-        // possibly change event status from sold out back to previous status
470
-        $this->event()->perform_sold_out_status_check();
471
-    }
472
-
473
-
474
-    /**
475
-     * tracks this registration's ticket reservation in extra meta
476
-     * and can increment related ticket reserved and corresponding datetime reserved values
477
-     *
478
-     * @param bool $update_ticket if true, will increment ticket and datetime reserved count
479
-     * @return void
480
-     * @throws EE_Error
481
-     * @throws InvalidArgumentException
482
-     * @throws InvalidDataTypeException
483
-     * @throws InvalidInterfaceException
484
-     * @throws ReflectionException
485
-     */
486
-    public function reserve_ticket($update_ticket = false, $source = 'unknown')
487
-    {
488
-        // only reserve ticket if space is not currently reserved
489
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
490
-            $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
491
-            // IMPORTANT !!!
492
-            // although checking $update_ticket first would be more efficient,
493
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
494
-            if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
495
-                && $update_ticket
496
-            ) {
497
-                $ticket = $this->ticket();
498
-                $ticket->increase_reserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
499
-                $ticket->save();
500
-            }
501
-        }
502
-    }
503
-
504
-
505
-    /**
506
-     * stops tracking this registration's ticket reservation in extra meta
507
-     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
508
-     *
509
-     * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
510
-     * @return void
511
-     * @throws EE_Error
512
-     * @throws InvalidArgumentException
513
-     * @throws InvalidDataTypeException
514
-     * @throws InvalidInterfaceException
515
-     * @throws ReflectionException
516
-     */
517
-    public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
518
-    {
519
-        // only release ticket if space is currently reserved
520
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
521
-            $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
522
-            // IMPORTANT !!!
523
-            // although checking $update_ticket first would be more efficient,
524
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
525
-            if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
526
-                && $update_ticket
527
-            ) {
528
-                $ticket = $this->ticket();
529
-                $ticket->decrease_reserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
530
-                $ticket->save();
531
-            }
532
-        }
533
-    }
534
-
535
-
536
-    /**
537
-     * Set Attendee ID
538
-     *
539
-     * @param        int $ATT_ID Attendee ID
540
-     * @throws EE_Error
541
-     * @throws RuntimeException
542
-     */
543
-    public function set_attendee_id($ATT_ID = 0)
544
-    {
545
-        $this->set('ATT_ID', $ATT_ID);
546
-    }
547
-
548
-
549
-    /**
550
-     *        Set Transaction ID
551
-     *
552
-     * @param        int $TXN_ID Transaction ID
553
-     * @throws EE_Error
554
-     * @throws RuntimeException
555
-     */
556
-    public function set_transaction_id($TXN_ID = 0)
557
-    {
558
-        $this->set('TXN_ID', $TXN_ID);
559
-    }
560
-
561
-
562
-    /**
563
-     *        Set Session
564
-     *
565
-     * @param    string $REG_session PHP Session ID
566
-     * @throws EE_Error
567
-     * @throws RuntimeException
568
-     */
569
-    public function set_session($REG_session = '')
570
-    {
571
-        $this->set('REG_session', $REG_session);
572
-    }
573
-
574
-
575
-    /**
576
-     *        Set Registration URL Link
577
-     *
578
-     * @param    string $REG_url_link Registration URL Link
579
-     * @throws EE_Error
580
-     * @throws RuntimeException
581
-     */
582
-    public function set_reg_url_link($REG_url_link = '')
583
-    {
584
-        $this->set('REG_url_link', $REG_url_link);
585
-    }
586
-
587
-
588
-    /**
589
-     *        Set Attendee Counter
590
-     *
591
-     * @param        int $REG_count Primary Attendee
592
-     * @throws EE_Error
593
-     * @throws RuntimeException
594
-     */
595
-    public function set_count($REG_count = 1)
596
-    {
597
-        $this->set('REG_count', $REG_count);
598
-    }
599
-
600
-
601
-    /**
602
-     *        Set Group Size
603
-     *
604
-     * @param        boolean $REG_group_size Group Registration
605
-     * @throws EE_Error
606
-     * @throws RuntimeException
607
-     */
608
-    public function set_group_size($REG_group_size = false)
609
-    {
610
-        $this->set('REG_group_size', $REG_group_size);
611
-    }
612
-
613
-
614
-    /**
615
-     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
616
-     *    EEM_Registration::status_id_not_approved
617
-     *
618
-     * @return        boolean
619
-     */
620
-    public function is_not_approved()
621
-    {
622
-        return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
623
-    }
624
-
625
-
626
-    /**
627
-     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
628
-     *    EEM_Registration::status_id_pending_payment
629
-     *
630
-     * @return        boolean
631
-     */
632
-    public function is_pending_payment()
633
-    {
634
-        return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
635
-    }
636
-
637
-
638
-    /**
639
-     *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
640
-     *
641
-     * @return        boolean
642
-     */
643
-    public function is_approved()
644
-    {
645
-        return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
646
-    }
647
-
648
-
649
-    /**
650
-     *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
651
-     *
652
-     * @return        boolean
653
-     */
654
-    public function is_cancelled()
655
-    {
656
-        return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
657
-    }
658
-
659
-
660
-    /**
661
-     *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
662
-     *
663
-     * @return        boolean
664
-     */
665
-    public function is_declined()
666
-    {
667
-        return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
668
-    }
669
-
670
-
671
-    /**
672
-     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
673
-     *    EEM_Registration::status_id_incomplete
674
-     *
675
-     * @return        boolean
676
-     */
677
-    public function is_incomplete()
678
-    {
679
-        return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
680
-    }
681
-
682
-
683
-    /**
684
-     *        Set Registration Date
685
-     *
686
-     * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
687
-     *                                                 Date
688
-     * @throws EE_Error
689
-     * @throws RuntimeException
690
-     */
691
-    public function set_reg_date($REG_date = false)
692
-    {
693
-        $this->set('REG_date', $REG_date);
694
-    }
695
-
696
-
697
-    /**
698
-     *    Set final price owing for this registration after all ticket/price modifications
699
-     *
700
-     * @access    public
701
-     * @param    float $REG_final_price
702
-     * @throws EE_Error
703
-     * @throws RuntimeException
704
-     */
705
-    public function set_final_price($REG_final_price = 0.00)
706
-    {
707
-        $this->set('REG_final_price', $REG_final_price);
708
-    }
709
-
710
-
711
-    /**
712
-     *    Set amount paid towards this registration's final price
713
-     *
714
-     * @access    public
715
-     * @param    float $REG_paid
716
-     * @throws EE_Error
717
-     * @throws RuntimeException
718
-     */
719
-    public function set_paid($REG_paid = 0.00)
720
-    {
721
-        $this->set('REG_paid', $REG_paid);
722
-    }
723
-
724
-
725
-    /**
726
-     *        Attendee Is Going
727
-     *
728
-     * @param        boolean $REG_att_is_going Attendee Is Going
729
-     * @throws EE_Error
730
-     * @throws RuntimeException
731
-     */
732
-    public function set_att_is_going($REG_att_is_going = false)
733
-    {
734
-        $this->set('REG_att_is_going', $REG_att_is_going);
735
-    }
736
-
737
-
738
-    /**
739
-     * Gets the related attendee
740
-     *
741
-     * @return EE_Attendee
742
-     * @throws EE_Error
743
-     */
744
-    public function attendee()
745
-    {
746
-        return $this->get_first_related('Attendee');
747
-    }
748
-
749
-
750
-    /**
751
-     *        get Event ID
752
-     */
753
-    public function event_ID()
754
-    {
755
-        return $this->get('EVT_ID');
756
-    }
757
-
758
-
759
-    /**
760
-     *        get Event ID
761
-     */
762
-    public function event_name()
763
-    {
764
-        $event = $this->event_obj();
765
-        if ($event) {
766
-            return $event->name();
767
-        } else {
768
-            return null;
769
-        }
770
-    }
771
-
772
-
773
-    /**
774
-     * Fetches the event this registration is for
775
-     *
776
-     * @return EE_Event
777
-     * @throws EE_Error
778
-     */
779
-    public function event_obj()
780
-    {
781
-        return $this->get_first_related('Event');
782
-    }
783
-
784
-
785
-    /**
786
-     *        get Attendee ID
787
-     */
788
-    public function attendee_ID()
789
-    {
790
-        return $this->get('ATT_ID');
791
-    }
792
-
793
-
794
-    /**
795
-     *        get PHP Session ID
796
-     */
797
-    public function session_ID()
798
-    {
799
-        return $this->get('REG_session');
800
-    }
801
-
802
-
803
-    /**
804
-     * Gets the string which represents the URL trigger for the receipt template in the message template system.
805
-     *
806
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
807
-     * @return string
808
-     */
809
-    public function receipt_url($messenger = 'html')
810
-    {
811
-
812
-        /**
813
-         * The below will be deprecated one version after this.  We check first if there is a custom receipt template
814
-         * already in use on old system.  If there is then we just return the standard url for it.
815
-         *
816
-         * @since 4.5.0
817
-         */
818
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
819
-        $has_custom = EEH_Template::locate_template(
820
-            $template_relative_path,
821
-            array(),
822
-            true,
823
-            true,
824
-            true
825
-        );
826
-
827
-        if ($has_custom) {
828
-            return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
829
-        }
830
-        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
831
-    }
832
-
833
-
834
-    /**
835
-     * Gets the string which represents the URL trigger for the invoice template in the message template system.
836
-     *
837
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
838
-     * @return string
839
-     * @throws EE_Error
840
-     */
841
-    public function invoice_url($messenger = 'html')
842
-    {
843
-        /**
844
-         * The below will be deprecated one version after this.  We check first if there is a custom invoice template
845
-         * already in use on old system.  If there is then we just return the standard url for it.
846
-         *
847
-         * @since 4.5.0
848
-         */
849
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
850
-        $has_custom = EEH_Template::locate_template(
851
-            $template_relative_path,
852
-            array(),
853
-            true,
854
-            true,
855
-            true
856
-        );
857
-
858
-        if ($has_custom) {
859
-            if ($messenger == 'html') {
860
-                return $this->invoice_url('launch');
861
-            }
862
-            $route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
863
-
864
-            $query_args = array('ee' => $route, 'id' => $this->reg_url_link());
865
-            if ($messenger == 'html') {
866
-                $query_args['html'] = true;
867
-            }
868
-            return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
869
-        }
870
-        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
871
-    }
872
-
873
-
874
-    /**
875
-     * get Registration URL Link
876
-     *
877
-     * @access public
878
-     * @return string
879
-     * @throws EE_Error
880
-     */
881
-    public function reg_url_link()
882
-    {
883
-        return (string) $this->get('REG_url_link');
884
-    }
885
-
886
-
887
-    /**
888
-     * Echoes out invoice_url()
889
-     *
890
-     * @param string $type 'download','launch', or 'html' (default is 'launch')
891
-     * @return void
892
-     * @throws EE_Error
893
-     */
894
-    public function e_invoice_url($type = 'launch')
895
-    {
896
-        echo $this->invoice_url($type);
897
-    }
898
-
899
-
900
-    /**
901
-     * Echoes out payment_overview_url
902
-     */
903
-    public function e_payment_overview_url()
904
-    {
905
-        echo $this->payment_overview_url();
906
-    }
907
-
908
-
909
-    /**
910
-     * Gets the URL for the checkout payment options reg step
911
-     * with this registration's REG_url_link added as a query parameter
912
-     *
913
-     * @param bool $clear_session Set to true when you want to clear the session on revisiting the
914
-     *                            payment overview url.
915
-     * @return string
916
-     * @throws InvalidInterfaceException
917
-     * @throws InvalidDataTypeException
918
-     * @throws EE_Error
919
-     * @throws InvalidArgumentException
920
-     */
921
-    public function payment_overview_url($clear_session = false)
922
-    {
923
-        return add_query_arg(
924
-            (array) apply_filters(
925
-                'FHEE__EE_Registration__payment_overview_url__query_args',
926
-                array(
927
-                    'e_reg_url_link' => $this->reg_url_link(),
928
-                    'step'           => 'payment_options',
929
-                    'revisit'        => true,
930
-                    'clear_session'  => (bool) $clear_session,
931
-                ),
932
-                $this
933
-            ),
934
-            EE_Registry::instance()->CFG->core->reg_page_url()
935
-        );
936
-    }
937
-
938
-
939
-    /**
940
-     * Gets the URL for the checkout attendee information reg step
941
-     * with this registration's REG_url_link added as a query parameter
942
-     *
943
-     * @return string
944
-     * @throws InvalidInterfaceException
945
-     * @throws InvalidDataTypeException
946
-     * @throws EE_Error
947
-     * @throws InvalidArgumentException
948
-     */
949
-    public function edit_attendee_information_url()
950
-    {
951
-        return add_query_arg(
952
-            (array) apply_filters(
953
-                'FHEE__EE_Registration__edit_attendee_information_url__query_args',
954
-                array(
955
-                    'e_reg_url_link' => $this->reg_url_link(),
956
-                    'step'           => 'attendee_information',
957
-                    'revisit'        => true,
958
-                ),
959
-                $this
960
-            ),
961
-            EE_Registry::instance()->CFG->core->reg_page_url()
962
-        );
963
-    }
964
-
965
-
966
-    /**
967
-     * Simply generates and returns the appropriate admin_url link to edit this registration
968
-     *
969
-     * @return string
970
-     * @throws EE_Error
971
-     */
972
-    public function get_admin_edit_url()
973
-    {
974
-        return EEH_URL::add_query_args_and_nonce(
975
-            array(
976
-                'page'    => 'espresso_registrations',
977
-                'action'  => 'view_registration',
978
-                '_REG_ID' => $this->ID(),
979
-            ),
980
-            admin_url('admin.php')
981
-        );
982
-    }
983
-
984
-
985
-    /**
986
-     *    is_primary_registrant?
987
-     */
988
-    public function is_primary_registrant()
989
-    {
990
-        return $this->get('REG_count') == 1 ? true : false;
991
-    }
992
-
993
-
994
-    /**
995
-     * This returns the primary registration object for this registration group (which may be this object).
996
-     *
997
-     * @return EE_Registration
998
-     * @throws EE_Error
999
-     */
1000
-    public function get_primary_registration()
1001
-    {
1002
-        if ($this->is_primary_registrant()) {
1003
-            return $this;
1004
-        }
1005
-
1006
-        // k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1007
-        /** @var EE_Registration $primary_registrant */
1008
-        $primary_registrant = EEM_Registration::instance()->get_one(
1009
-            array(
1010
-                array(
1011
-                    'TXN_ID'    => $this->transaction_ID(),
1012
-                    'REG_count' => 1,
1013
-                ),
1014
-            )
1015
-        );
1016
-        return $primary_registrant;
1017
-    }
1018
-
1019
-
1020
-    /**
1021
-     *        get  Attendee Number
1022
-     *
1023
-     * @access        public
1024
-     */
1025
-    public function count()
1026
-    {
1027
-        return $this->get('REG_count');
1028
-    }
1029
-
1030
-
1031
-    /**
1032
-     *        get Group Size
1033
-     */
1034
-    public function group_size()
1035
-    {
1036
-        return $this->get('REG_group_size');
1037
-    }
1038
-
1039
-
1040
-    /**
1041
-     *        get Registration Date
1042
-     */
1043
-    public function date()
1044
-    {
1045
-        return $this->get('REG_date');
1046
-    }
1047
-
1048
-
1049
-    /**
1050
-     * gets a pretty date
1051
-     *
1052
-     * @param string $date_format
1053
-     * @param string $time_format
1054
-     * @return string
1055
-     * @throws EE_Error
1056
-     */
1057
-    public function pretty_date($date_format = null, $time_format = null)
1058
-    {
1059
-        return $this->get_datetime('REG_date', $date_format, $time_format);
1060
-    }
1061
-
1062
-
1063
-    /**
1064
-     * final_price
1065
-     * the registration's share of the transaction total, so that the
1066
-     * sum of all the transaction's REG_final_prices equal the transaction's total
1067
-     *
1068
-     * @return float
1069
-     * @throws EE_Error
1070
-     */
1071
-    public function final_price()
1072
-    {
1073
-        return $this->get('REG_final_price');
1074
-    }
1075
-
1076
-
1077
-    /**
1078
-     * pretty_final_price
1079
-     *  final price as formatted string, with correct decimal places and currency symbol
1080
-     *
1081
-     * @return string
1082
-     * @throws EE_Error
1083
-     */
1084
-    public function pretty_final_price()
1085
-    {
1086
-        return $this->get_pretty('REG_final_price');
1087
-    }
1088
-
1089
-
1090
-    /**
1091
-     * get paid (yeah)
1092
-     *
1093
-     * @return float
1094
-     * @throws EE_Error
1095
-     */
1096
-    public function paid()
1097
-    {
1098
-        return $this->get('REG_paid');
1099
-    }
1100
-
1101
-
1102
-    /**
1103
-     * pretty_paid
1104
-     *
1105
-     * @return float
1106
-     * @throws EE_Error
1107
-     */
1108
-    public function pretty_paid()
1109
-    {
1110
-        return $this->get_pretty('REG_paid');
1111
-    }
1112
-
1113
-
1114
-    /**
1115
-     * owes_monies_and_can_pay
1116
-     * whether or not this registration has monies owing and it's' status allows payment
1117
-     *
1118
-     * @param array $requires_payment
1119
-     * @return bool
1120
-     * @throws EE_Error
1121
-     */
1122
-    public function owes_monies_and_can_pay($requires_payment = array())
1123
-    {
1124
-        // these reg statuses require payment (if event is not free)
1125
-        $requires_payment = ! empty($requires_payment)
1126
-            ? $requires_payment
1127
-            : EEM_Registration::reg_statuses_that_allow_payment();
1128
-        if (in_array($this->status_ID(), $requires_payment) &&
1129
-            $this->final_price() != 0 &&
1130
-            $this->final_price() != $this->paid()
1131
-        ) {
1132
-            return true;
1133
-        } else {
1134
-            return false;
1135
-        }
1136
-    }
1137
-
1138
-
1139
-    /**
1140
-     * Prints out the return value of $this->pretty_status()
1141
-     *
1142
-     * @param bool $show_icons
1143
-     * @return void
1144
-     * @throws EE_Error
1145
-     */
1146
-    public function e_pretty_status($show_icons = false)
1147
-    {
1148
-        echo $this->pretty_status($show_icons);
1149
-    }
1150
-
1151
-
1152
-    /**
1153
-     * Returns a nice version of the status for displaying to customers
1154
-     *
1155
-     * @param bool $show_icons
1156
-     * @return string
1157
-     * @throws EE_Error
1158
-     */
1159
-    public function pretty_status($show_icons = false)
1160
-    {
1161
-        $status = EEM_Status::instance()->localized_status(
1162
-            array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1163
-            false,
1164
-            'sentence'
1165
-        );
1166
-        $icon = '';
1167
-        switch ($this->status_ID()) {
1168
-            case EEM_Registration::status_id_approved:
1169
-                $icon = $show_icons
1170
-                    ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1171
-                    : '';
1172
-                break;
1173
-            case EEM_Registration::status_id_pending_payment:
1174
-                $icon = $show_icons
1175
-                    ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1176
-                    : '';
1177
-                break;
1178
-            case EEM_Registration::status_id_not_approved:
1179
-                $icon = $show_icons
1180
-                    ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1181
-                    : '';
1182
-                break;
1183
-            case EEM_Registration::status_id_cancelled:
1184
-                $icon = $show_icons
1185
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1186
-                    : '';
1187
-                break;
1188
-            case EEM_Registration::status_id_incomplete:
1189
-                $icon = $show_icons
1190
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1191
-                    : '';
1192
-                break;
1193
-            case EEM_Registration::status_id_declined:
1194
-                $icon = $show_icons
1195
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1196
-                    : '';
1197
-                break;
1198
-            case EEM_Registration::status_id_wait_list:
1199
-                $icon = $show_icons
1200
-                    ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1201
-                    : '';
1202
-                break;
1203
-        }
1204
-        return $icon . $status[ $this->status_ID() ];
1205
-    }
1206
-
1207
-
1208
-    /**
1209
-     *        get Attendee Is Going
1210
-     */
1211
-    public function att_is_going()
1212
-    {
1213
-        return $this->get('REG_att_is_going');
1214
-    }
1215
-
1216
-
1217
-    /**
1218
-     * Gets related answers
1219
-     *
1220
-     * @param array $query_params like EEM_Base::get_all
1221
-     * @return EE_Answer[]
1222
-     * @throws EE_Error
1223
-     */
1224
-    public function answers($query_params = null)
1225
-    {
1226
-        return $this->get_many_related('Answer', $query_params);
1227
-    }
1228
-
1229
-
1230
-    /**
1231
-     * Gets the registration's answer value to the specified question
1232
-     * (either the question's ID or a question object)
1233
-     *
1234
-     * @param EE_Question|int $question
1235
-     * @param bool            $pretty_value
1236
-     * @return array|string if pretty_value= true, the result will always be a string
1237
-     * (because the answer might be an array of answer values, so passing pretty_value=true
1238
-     * will convert it into some kind of string)
1239
-     * @throws EE_Error
1240
-     */
1241
-    public function answer_value_to_question($question, $pretty_value = true)
1242
-    {
1243
-        $question_id = EEM_Question::instance()->ensure_is_ID($question);
1244
-        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1245
-    }
1246
-
1247
-
1248
-    /**
1249
-     * question_groups
1250
-     * returns an array of EE_Question_Group objects for this registration
1251
-     *
1252
-     * @return EE_Question_Group[]
1253
-     * @throws EE_Error
1254
-     * @throws EntityNotFoundException
1255
-     */
1256
-    public function question_groups()
1257
-    {
1258
-        $question_groups = array();
1259
-        if ($this->event() instanceof EE_Event) {
1260
-            $question_groups = $this->event()->question_groups(
1261
-                array(
1262
-                    array(
1263
-                        'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1264
-                    ),
1265
-                    'order_by' => array('QSG_order' => 'ASC'),
1266
-                )
1267
-            );
1268
-        }
1269
-        return $question_groups;
1270
-    }
1271
-
1272
-
1273
-    /**
1274
-     * count_question_groups
1275
-     * returns a count of the number of EE_Question_Group objects for this registration
1276
-     *
1277
-     * @return int
1278
-     * @throws EE_Error
1279
-     * @throws EntityNotFoundException
1280
-     */
1281
-    public function count_question_groups()
1282
-    {
1283
-        $qg_count = 0;
1284
-        if ($this->event() instanceof EE_Event) {
1285
-            $qg_count = $this->event()->count_related(
1286
-                'Question_Group',
1287
-                array(
1288
-                    array(
1289
-                        'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1290
-                    ),
1291
-                )
1292
-            );
1293
-        }
1294
-        return $qg_count;
1295
-    }
1296
-
1297
-
1298
-    /**
1299
-     * Returns the registration date in the 'standard' string format
1300
-     * (function may be improved in the future to allow for different formats and timezones)
1301
-     *
1302
-     * @return string
1303
-     * @throws EE_Error
1304
-     */
1305
-    public function reg_date()
1306
-    {
1307
-        return $this->get_datetime('REG_date');
1308
-    }
1309
-
1310
-
1311
-    /**
1312
-     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1313
-     * the ticket this registration purchased, or the datetime they have registered
1314
-     * to attend)
1315
-     *
1316
-     * @return EE_Datetime_Ticket
1317
-     * @throws EE_Error
1318
-     */
1319
-    public function datetime_ticket()
1320
-    {
1321
-        return $this->get_first_related('Datetime_Ticket');
1322
-    }
1323
-
1324
-
1325
-    /**
1326
-     * Sets the registration's datetime_ticket.
1327
-     *
1328
-     * @param EE_Datetime_Ticket $datetime_ticket
1329
-     * @return EE_Datetime_Ticket
1330
-     * @throws EE_Error
1331
-     */
1332
-    public function set_datetime_ticket($datetime_ticket)
1333
-    {
1334
-        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1335
-    }
1336
-
1337
-    /**
1338
-     * Gets deleted
1339
-     *
1340
-     * @return bool
1341
-     * @throws EE_Error
1342
-     */
1343
-    public function deleted()
1344
-    {
1345
-        return $this->get('REG_deleted');
1346
-    }
1347
-
1348
-    /**
1349
-     * Sets deleted
1350
-     *
1351
-     * @param boolean $deleted
1352
-     * @return bool
1353
-     * @throws EE_Error
1354
-     * @throws RuntimeException
1355
-     */
1356
-    public function set_deleted($deleted)
1357
-    {
1358
-        if ($deleted) {
1359
-            $this->delete();
1360
-        } else {
1361
-            $this->restore();
1362
-        }
1363
-    }
1364
-
1365
-
1366
-    /**
1367
-     * Get the status object of this object
1368
-     *
1369
-     * @return EE_Status
1370
-     * @throws EE_Error
1371
-     */
1372
-    public function status_obj()
1373
-    {
1374
-        return $this->get_first_related('Status');
1375
-    }
1376
-
1377
-
1378
-    /**
1379
-     * Returns the number of times this registration has checked into any of the datetimes
1380
-     * its available for
1381
-     *
1382
-     * @return int
1383
-     * @throws EE_Error
1384
-     */
1385
-    public function count_checkins()
1386
-    {
1387
-        return $this->get_model()->count_related($this, 'Checkin');
1388
-    }
1389
-
1390
-
1391
-    /**
1392
-     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1393
-     * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1394
-     *
1395
-     * @return int
1396
-     * @throws EE_Error
1397
-     */
1398
-    public function count_checkins_not_checkedout()
1399
-    {
1400
-        return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1401
-    }
1402
-
1403
-
1404
-    /**
1405
-     * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1406
-     *
1407
-     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1408
-     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1409
-     *                                          consider registration status as well as datetime access.
1410
-     * @return bool
1411
-     * @throws EE_Error
1412
-     */
1413
-    public function can_checkin($DTT_OR_ID, $check_approved = true)
1414
-    {
1415
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1416
-
1417
-        // first check registration status
1418
-        if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1419
-            return false;
1420
-        }
1421
-        // is there a datetime ticket that matches this dtt_ID?
1422
-        if (! (EEM_Datetime_Ticket::instance()->exists(
1423
-            array(
1424
-                array(
1425
-                    'TKT_ID' => $this->get('TKT_ID'),
1426
-                    'DTT_ID' => $DTT_ID,
1427
-                ),
1428
-            )
1429
-        ))
1430
-        ) {
1431
-            return false;
1432
-        }
1433
-
1434
-        // final check is against TKT_uses
1435
-        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1436
-    }
1437
-
1438
-
1439
-    /**
1440
-     * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1441
-     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1442
-     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1443
-     * then return false.  Otherwise return true.
1444
-     *
1445
-     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1446
-     * @return bool true means can checkin.  false means cannot checkin.
1447
-     * @throws EE_Error
1448
-     */
1449
-    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1450
-    {
1451
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1452
-
1453
-        if (! $DTT_ID) {
1454
-            return false;
1455
-        }
1456
-
1457
-        $max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1458
-
1459
-        // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1460
-        // check-in or not.
1461
-        if (! $max_uses || $max_uses === EE_INF) {
1462
-            return true;
1463
-        }
1464
-
1465
-        // does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1466
-        // go ahead and toggle.
1467
-        if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1468
-            return true;
1469
-        }
1470
-
1471
-        // made it here so the last check is whether the number of checkins per unique datetime on this registration
1472
-        // disallows further check-ins.
1473
-        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1474
-            array(
1475
-                array(
1476
-                    'REG_ID' => $this->ID(),
1477
-                    'CHK_in' => true,
1478
-                ),
1479
-            ),
1480
-            'DTT_ID',
1481
-            true
1482
-        );
1483
-        // checkins have already reached their max number of uses
1484
-        // so registrant can NOT checkin
1485
-        if ($count_unique_dtt_checkins >= $max_uses) {
1486
-            EE_Error::add_error(
1487
-                esc_html__(
1488
-                    'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1489
-                    'event_espresso'
1490
-                ),
1491
-                __FILE__,
1492
-                __FUNCTION__,
1493
-                __LINE__
1494
-            );
1495
-            return false;
1496
-        }
1497
-        return true;
1498
-    }
1499
-
1500
-
1501
-    /**
1502
-     * toggle Check-in status for this registration
1503
-     * Check-ins are toggled in the following order:
1504
-     * never checked in -> checked in
1505
-     * checked in -> checked out
1506
-     * checked out -> checked in
1507
-     *
1508
-     * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1509
-     *                      If not included or null, then it is assumed latest datetime is being toggled.
1510
-     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1511
-     *                      can be checked in or not.  Otherwise this forces change in checkin status.
1512
-     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1513
-     * @throws EE_Error
1514
-     */
1515
-    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1516
-    {
1517
-        if (empty($DTT_ID)) {
1518
-            $datetime = $this->get_latest_related_datetime();
1519
-            $DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1520
-            // verify the registration can checkin for the given DTT_ID
1521
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1522
-            EE_Error::add_error(
1523
-                sprintf(
1524
-                    esc_html__(
1525
-                        'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1526
-                        'event_espresso'
1527
-                    ),
1528
-                    $this->ID(),
1529
-                    $DTT_ID
1530
-                ),
1531
-                __FILE__,
1532
-                __FUNCTION__,
1533
-                __LINE__
1534
-            );
1535
-            return false;
1536
-        }
1537
-        $status_paths = array(
1538
-            EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1539
-            EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1540
-            EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1541
-        );
1542
-        // start by getting the current status so we know what status we'll be changing to.
1543
-        $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1544
-        $status_to = $status_paths[ $cur_status ];
1545
-        // database only records true for checked IN or false for checked OUT
1546
-        // no record ( null ) means checked in NEVER, but we obviously don't save that
1547
-        $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1548
-        // add relation - note Check-ins are always creating new rows
1549
-        // because we are keeping track of Check-ins over time.
1550
-        // Eventually we'll probably want to show a list table
1551
-        // for the individual Check-ins so that they can be managed.
1552
-        $checkin = EE_Checkin::new_instance(
1553
-            array(
1554
-                'REG_ID' => $this->ID(),
1555
-                'DTT_ID' => $DTT_ID,
1556
-                'CHK_in' => $new_status,
1557
-            )
1558
-        );
1559
-        // if the record could not be saved then return false
1560
-        if ($checkin->save() === 0) {
1561
-            if (WP_DEBUG) {
1562
-                global $wpdb;
1563
-                $error = sprintf(
1564
-                    esc_html__(
1565
-                        'Registration check in update failed because of the following database error: %1$s%2$s',
1566
-                        'event_espresso'
1567
-                    ),
1568
-                    '<br />',
1569
-                    $wpdb->last_error
1570
-                );
1571
-            } else {
1572
-                $error = esc_html__(
1573
-                    'Registration check in update failed because of an unknown database error',
1574
-                    'event_espresso'
1575
-                );
1576
-            }
1577
-            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1578
-            return false;
1579
-        }
1580
-        return $status_to;
1581
-    }
1582
-
1583
-
1584
-    /**
1585
-     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1586
-     * "Latest" is defined by the `DTT_EVT_start` column.
1587
-     *
1588
-     * @return EE_Datetime|null
1589
-     * @throws EE_Error
1590
-     */
1591
-    public function get_latest_related_datetime()
1592
-    {
1593
-        return EEM_Datetime::instance()->get_one(
1594
-            array(
1595
-                array(
1596
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1597
-                ),
1598
-                'order_by' => array('DTT_EVT_start' => 'DESC'),
1599
-            )
1600
-        );
1601
-    }
1602
-
1603
-
1604
-    /**
1605
-     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1606
-     * "Earliest" is defined by the `DTT_EVT_start` column.
1607
-     *
1608
-     * @throws EE_Error
1609
-     */
1610
-    public function get_earliest_related_datetime()
1611
-    {
1612
-        return EEM_Datetime::instance()->get_one(
1613
-            array(
1614
-                array(
1615
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1616
-                ),
1617
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
1618
-            )
1619
-        );
1620
-    }
1621
-
1622
-
1623
-    /**
1624
-     * This method simply returns the check-in status for this registration and the given datetime.
1625
-     * If neither the datetime nor the checkin values are provided as arguments,
1626
-     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1627
-     *
1628
-     * @param  int       $DTT_ID  The ID of the datetime we're checking against
1629
-     *                            (if empty we'll get the primary datetime for
1630
-     *                            this registration (via event) and use it's ID);
1631
-     * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1632
-     *
1633
-     * @return int                Integer representing Check-in status.
1634
-     * @throws EE_Error
1635
-     */
1636
-    public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1637
-    {
1638
-        $checkin_query_params = array(
1639
-            'order_by' => array('CHK_timestamp' => 'DESC'),
1640
-        );
1641
-
1642
-        if ($DTT_ID > 0) {
1643
-            $checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1644
-        }
1645
-
1646
-        // get checkin object (if exists)
1647
-        $checkin = $checkin instanceof EE_Checkin
1648
-            ? $checkin
1649
-            : $this->get_first_related('Checkin', $checkin_query_params);
1650
-        if ($checkin instanceof EE_Checkin) {
1651
-            if ($checkin->get('CHK_in')) {
1652
-                return EE_Checkin::status_checked_in; // checked in
1653
-            }
1654
-            return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1655
-        }
1656
-        return EE_Checkin::status_checked_never; // never been checked in
1657
-    }
1658
-
1659
-
1660
-    /**
1661
-     * This method returns a localized message for the toggled Check-in message.
1662
-     *
1663
-     * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1664
-     *                     then it is assumed Check-in for primary datetime was toggled.
1665
-     * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1666
-     *                     message can be customized with the attendee name.
1667
-     * @return string internationalized message
1668
-     * @throws EE_Error
1669
-     */
1670
-    public function get_checkin_msg($DTT_ID, $error = false)
1671
-    {
1672
-        // let's get the attendee first so we can include the name of the attendee
1673
-        $attendee = $this->get_first_related('Attendee');
1674
-        if ($attendee instanceof EE_Attendee) {
1675
-            if ($error) {
1676
-                return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1677
-            }
1678
-            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1679
-            // what is the status message going to be?
1680
-            switch ($cur_status) {
1681
-                case EE_Checkin::status_checked_never:
1682
-                    return sprintf(
1683
-                        __("%s has been removed from Check-in records", "event_espresso"),
1684
-                        $attendee->full_name()
1685
-                    );
1686
-                    break;
1687
-                case EE_Checkin::status_checked_in:
1688
-                    return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1689
-                    break;
1690
-                case EE_Checkin::status_checked_out:
1691
-                    return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1692
-                    break;
1693
-            }
1694
-        }
1695
-        return esc_html__("The check-in status could not be determined.", "event_espresso");
1696
-    }
1697
-
1698
-
1699
-    /**
1700
-     * Returns the related EE_Transaction to this registration
1701
-     *
1702
-     * @return EE_Transaction
1703
-     * @throws EE_Error
1704
-     * @throws EntityNotFoundException
1705
-     */
1706
-    public function transaction()
1707
-    {
1708
-        $transaction = $this->get_first_related('Transaction');
1709
-        if (! $transaction instanceof \EE_Transaction) {
1710
-            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1711
-        }
1712
-        return $transaction;
1713
-    }
1714
-
1715
-
1716
-    /**
1717
-     *        get Registration Code
1718
-     */
1719
-    public function reg_code()
1720
-    {
1721
-        return $this->get('REG_code');
1722
-    }
1723
-
1724
-
1725
-    /**
1726
-     *        get Transaction ID
1727
-     */
1728
-    public function transaction_ID()
1729
-    {
1730
-        return $this->get('TXN_ID');
1731
-    }
1732
-
1733
-
1734
-    /**
1735
-     * @return int
1736
-     * @throws EE_Error
1737
-     */
1738
-    public function ticket_ID()
1739
-    {
1740
-        return $this->get('TKT_ID');
1741
-    }
1742
-
1743
-
1744
-    /**
1745
-     *        Set Registration Code
1746
-     *
1747
-     * @access    public
1748
-     * @param    string  $REG_code Registration Code
1749
-     * @param    boolean $use_default
1750
-     * @throws EE_Error
1751
-     */
1752
-    public function set_reg_code($REG_code, $use_default = false)
1753
-    {
1754
-        if (empty($REG_code)) {
1755
-            EE_Error::add_error(
1756
-                esc_html__('REG_code can not be empty.', 'event_espresso'),
1757
-                __FILE__,
1758
-                __FUNCTION__,
1759
-                __LINE__
1760
-            );
1761
-            return;
1762
-        }
1763
-        if (! $this->reg_code()) {
1764
-            parent::set('REG_code', $REG_code, $use_default);
1765
-        } else {
1766
-            EE_Error::doing_it_wrong(
1767
-                __CLASS__ . '::' . __FUNCTION__,
1768
-                esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1769
-                '4.6.0'
1770
-            );
1771
-        }
1772
-    }
1773
-
1774
-
1775
-    /**
1776
-     * Returns all other registrations in the same group as this registrant who have the same ticket option.
1777
-     * Note, if you want to just get all registrations in the same transaction (group), use:
1778
-     *    $registration->transaction()->registrations();
1779
-     *
1780
-     * @since 4.5.0
1781
-     * @return EE_Registration[] or empty array if this isn't a group registration.
1782
-     * @throws EE_Error
1783
-     */
1784
-    public function get_all_other_registrations_in_group()
1785
-    {
1786
-        if ($this->group_size() < 2) {
1787
-            return array();
1788
-        }
1789
-
1790
-        $query[0] = array(
1791
-            'TXN_ID' => $this->transaction_ID(),
1792
-            'REG_ID' => array('!=', $this->ID()),
1793
-            'TKT_ID' => $this->ticket_ID(),
1794
-        );
1795
-        /** @var EE_Registration[] $registrations */
1796
-        $registrations = $this->get_model()->get_all($query);
1797
-        return $registrations;
1798
-    }
1799
-
1800
-    /**
1801
-     * Return the link to the admin details for the object.
1802
-     *
1803
-     * @return string
1804
-     * @throws EE_Error
1805
-     */
1806
-    public function get_admin_details_link()
1807
-    {
1808
-        EE_Registry::instance()->load_helper('URL');
1809
-        return EEH_URL::add_query_args_and_nonce(
1810
-            array(
1811
-                'page'    => 'espresso_registrations',
1812
-                'action'  => 'view_registration',
1813
-                '_REG_ID' => $this->ID(),
1814
-            ),
1815
-            admin_url('admin.php')
1816
-        );
1817
-    }
1818
-
1819
-    /**
1820
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1821
-     *
1822
-     * @return string
1823
-     * @throws EE_Error
1824
-     */
1825
-    public function get_admin_edit_link()
1826
-    {
1827
-        return $this->get_admin_details_link();
1828
-    }
1829
-
1830
-    /**
1831
-     * Returns the link to a settings page for the object.
1832
-     *
1833
-     * @return string
1834
-     * @throws EE_Error
1835
-     */
1836
-    public function get_admin_settings_link()
1837
-    {
1838
-        return $this->get_admin_details_link();
1839
-    }
1840
-
1841
-    /**
1842
-     * Returns the link to the "overview" for the object (typically the "list table" view).
1843
-     *
1844
-     * @return string
1845
-     */
1846
-    public function get_admin_overview_link()
1847
-    {
1848
-        EE_Registry::instance()->load_helper('URL');
1849
-        return EEH_URL::add_query_args_and_nonce(
1850
-            array(
1851
-                'page' => 'espresso_registrations',
1852
-            ),
1853
-            admin_url('admin.php')
1854
-        );
1855
-    }
1856
-
1857
-
1858
-    /**
1859
-     * @param array $query_params
1860
-     *
1861
-     * @return \EE_Registration[]
1862
-     * @throws EE_Error
1863
-     */
1864
-    public function payments($query_params = array())
1865
-    {
1866
-        return $this->get_many_related('Payment', $query_params);
1867
-    }
1868
-
1869
-
1870
-    /**
1871
-     * @param array $query_params
1872
-     *
1873
-     * @return \EE_Registration_Payment[]
1874
-     * @throws EE_Error
1875
-     */
1876
-    public function registration_payments($query_params = array())
1877
-    {
1878
-        return $this->get_many_related('Registration_Payment', $query_params);
1879
-    }
1880
-
1881
-
1882
-    /**
1883
-     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1884
-     * Note: if there are no payments on the registration there will be no payment method returned.
1885
-     *
1886
-     * @return EE_Payment_Method|null
1887
-     */
1888
-    public function payment_method()
1889
-    {
1890
-        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1891
-    }
1892
-
1893
-
1894
-    /**
1895
-     * @return \EE_Line_Item
1896
-     * @throws EntityNotFoundException
1897
-     * @throws EE_Error
1898
-     */
1899
-    public function ticket_line_item()
1900
-    {
1901
-        $ticket = $this->ticket();
1902
-        $transaction = $this->transaction();
1903
-        $line_item = null;
1904
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1905
-            $transaction->total_line_item(),
1906
-            'Ticket',
1907
-            array($ticket->ID())
1908
-        );
1909
-        foreach ($ticket_line_items as $ticket_line_item) {
1910
-            if ($ticket_line_item instanceof \EE_Line_Item
1911
-                && $ticket_line_item->OBJ_type() === 'Ticket'
1912
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
1913
-            ) {
1914
-                $line_item = $ticket_line_item;
1915
-                break;
1916
-            }
1917
-        }
1918
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1919
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1920
-        }
1921
-        return $line_item;
1922
-    }
1923
-
1924
-
1925
-    /**
1926
-     * Soft Deletes this model object.
1927
-     *
1928
-     * @return boolean | int
1929
-     * @throws RuntimeException
1930
-     * @throws EE_Error
1931
-     */
1932
-    public function delete()
1933
-    {
1934
-        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1935
-            $this->set_status(EEM_Registration::status_id_cancelled);
1936
-        }
1937
-        return parent::delete();
1938
-    }
1939
-
1940
-
1941
-    /**
1942
-     * Restores whatever the previous status was on a registration before it was trashed (if possible)
1943
-     *
1944
-     * @throws EE_Error
1945
-     * @throws RuntimeException
1946
-     */
1947
-    public function restore()
1948
-    {
1949
-        $previous_status = $this->get_extra_meta(
1950
-            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1951
-            true,
1952
-            EEM_Registration::status_id_cancelled
1953
-        );
1954
-        if ($previous_status) {
1955
-            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1956
-            $this->set_status($previous_status);
1957
-        }
1958
-        return parent::restore();
1959
-    }
1960
-
1961
-
1962
-    /**
1963
-     * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1964
-     *
1965
-     * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1966
-     *                                           depending on whether the reg status changes to or from "Approved"
1967
-     * @return boolean whether the Registration status was updated
1968
-     * @throws EE_Error
1969
-     * @throws RuntimeException
1970
-     */
1971
-    public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
1972
-    {
1973
-        $paid = $this->paid();
1974
-        $price = $this->final_price();
1975
-        switch (true) {
1976
-            // overpaid or paid
1977
-            case EEH_Money::compare_floats($paid, $price, '>'):
1978
-            case EEH_Money::compare_floats($paid, $price):
1979
-                $new_status = EEM_Registration::status_id_approved;
1980
-                break;
1981
-            //  underpaid
1982
-            case EEH_Money::compare_floats($paid, $price, '<'):
1983
-                $new_status = EEM_Registration::status_id_pending_payment;
1984
-                break;
1985
-            // uhhh Houston...
1986
-            default:
1987
-                throw new RuntimeException(
1988
-                    esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
1989
-                );
1990
-        }
1991
-        if ($new_status !== $this->status_ID()) {
1992
-            if ($trigger_set_status_logic) {
1993
-                return $this->set_status($new_status);
1994
-            }
1995
-            parent::set('STS_ID', $new_status);
1996
-            return true;
1997
-        }
1998
-        return false;
1999
-    }
2000
-
2001
-
2002
-    /*************************** DEPRECATED ***************************/
2003
-
2004
-
2005
-    /**
2006
-     * @deprecated
2007
-     * @since     4.7.0
2008
-     * @access    public
2009
-     */
2010
-    public function price_paid()
2011
-    {
2012
-        EE_Error::doing_it_wrong(
2013
-            'EE_Registration::price_paid()',
2014
-            esc_html__(
2015
-                'This method is deprecated, please use EE_Registration::final_price() instead.',
2016
-                'event_espresso'
2017
-            ),
2018
-            '4.7.0'
2019
-        );
2020
-        return $this->final_price();
2021
-    }
2022
-
2023
-
2024
-    /**
2025
-     * @deprecated
2026
-     * @since     4.7.0
2027
-     * @access    public
2028
-     * @param    float $REG_final_price
2029
-     * @throws EE_Error
2030
-     * @throws RuntimeException
2031
-     */
2032
-    public function set_price_paid($REG_final_price = 0.00)
2033
-    {
2034
-        EE_Error::doing_it_wrong(
2035
-            'EE_Registration::set_price_paid()',
2036
-            esc_html__(
2037
-                'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2038
-                'event_espresso'
2039
-            ),
2040
-            '4.7.0'
2041
-        );
2042
-        $this->set_final_price($REG_final_price);
2043
-    }
2044
-
2045
-
2046
-    /**
2047
-     * @deprecated
2048
-     * @since 4.7.0
2049
-     * @return string
2050
-     * @throws EE_Error
2051
-     */
2052
-    public function pretty_price_paid()
2053
-    {
2054
-        EE_Error::doing_it_wrong(
2055
-            'EE_Registration::pretty_price_paid()',
2056
-            esc_html__(
2057
-                'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2058
-                'event_espresso'
2059
-            ),
2060
-            '4.7.0'
2061
-        );
2062
-        return $this->pretty_final_price();
2063
-    }
2064
-
2065
-
2066
-    /**
2067
-     * Gets the primary datetime related to this registration via the related Event to this registration
2068
-     *
2069
-     * @deprecated 4.9.17
2070
-     * @return EE_Datetime
2071
-     * @throws EE_Error
2072
-     * @throws EntityNotFoundException
2073
-     */
2074
-    public function get_related_primary_datetime()
2075
-    {
2076
-        EE_Error::doing_it_wrong(
2077
-            __METHOD__,
2078
-            esc_html__(
2079
-                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2080
-                'event_espresso'
2081
-            ),
2082
-            '4.9.17',
2083
-            '5.0.0'
2084
-        );
2085
-        return $this->event()->primary_datetime();
2086
-    }
20
+	/**
21
+	 * Used to reference when a registration has never been checked in.
22
+	 *
23
+	 * @deprecated use \EE_Checkin::status_checked_never instead
24
+	 * @type int
25
+	 */
26
+	const checkin_status_never = 2;
27
+
28
+	/**
29
+	 * Used to reference when a registration has been checked in.
30
+	 *
31
+	 * @deprecated use \EE_Checkin::status_checked_in instead
32
+	 * @type int
33
+	 */
34
+	const checkin_status_in = 1;
35
+
36
+
37
+	/**
38
+	 * Used to reference when a registration has been checked out.
39
+	 *
40
+	 * @deprecated use \EE_Checkin::status_checked_out instead
41
+	 * @type int
42
+	 */
43
+	const checkin_status_out = 0;
44
+
45
+
46
+	/**
47
+	 * extra meta key for tracking reg status os trashed registrations
48
+	 *
49
+	 * @type string
50
+	 */
51
+	const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
+
53
+
54
+	/**
55
+	 * extra meta key for tracking if registration has reserved ticket
56
+	 *
57
+	 * @type string
58
+	 */
59
+	const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
60
+
61
+
62
+	/**
63
+	 * @param array  $props_n_values          incoming values
64
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
65
+	 *                                        used.)
66
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
67
+	 *                                        date_format and the second value is the time format
68
+	 * @return EE_Registration
69
+	 * @throws EE_Error
70
+	 */
71
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
72
+	{
73
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
74
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param array  $props_n_values  incoming values from the database
80
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
+	 *                                the website will be used.
82
+	 * @return EE_Registration
83
+	 */
84
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
85
+	{
86
+		return new self($props_n_values, true, $timezone);
87
+	}
88
+
89
+
90
+	/**
91
+	 *        Set Event ID
92
+	 *
93
+	 * @param        int $EVT_ID Event ID
94
+	 * @throws EE_Error
95
+	 * @throws RuntimeException
96
+	 */
97
+	public function set_event($EVT_ID = 0)
98
+	{
99
+		$this->set('EVT_ID', $EVT_ID);
100
+	}
101
+
102
+
103
+	/**
104
+	 * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
105
+	 * be routed to internal methods
106
+	 *
107
+	 * @param string $field_name
108
+	 * @param mixed  $field_value
109
+	 * @param bool   $use_default
110
+	 * @throws EE_Error
111
+	 * @throws EntityNotFoundException
112
+	 * @throws InvalidArgumentException
113
+	 * @throws InvalidDataTypeException
114
+	 * @throws InvalidInterfaceException
115
+	 * @throws ReflectionException
116
+	 * @throws RuntimeException
117
+	 */
118
+	public function set($field_name, $field_value, $use_default = false)
119
+	{
120
+		switch ($field_name) {
121
+			case 'REG_code':
122
+				if (! empty($field_value) && $this->reg_code() === null) {
123
+					$this->set_reg_code($field_value, $use_default);
124
+				}
125
+				break;
126
+			case 'STS_ID':
127
+				$this->set_status($field_value, $use_default);
128
+				break;
129
+			default:
130
+				parent::set($field_name, $field_value, $use_default);
131
+		}
132
+	}
133
+
134
+
135
+	/**
136
+	 * Set Status ID
137
+	 * updates the registration status and ALSO...
138
+	 * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
139
+	 * calls release_registration_space() if the reg status changes FROM approved to any other reg status
140
+	 *
141
+	 * @param string                $new_STS_ID
142
+	 * @param boolean               $use_default
143
+	 * @param ContextInterface|null $context
144
+	 * @return bool
145
+	 * @throws EE_Error
146
+	 * @throws EntityNotFoundException
147
+	 * @throws InvalidArgumentException
148
+	 * @throws ReflectionException
149
+	 * @throws RuntimeException
150
+	 * @throws InvalidDataTypeException
151
+	 * @throws InvalidInterfaceException
152
+	 */
153
+	public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
154
+	{
155
+		// get current REG_Status
156
+		$old_STS_ID = $this->status_ID();
157
+		// if status has changed
158
+		if ($old_STS_ID !== $new_STS_ID // and that status has actually changed
159
+			&& ! empty($old_STS_ID) // and that old status is actually set
160
+			&& ! empty($new_STS_ID) // as well as the new status
161
+			&& $this->ID() // ensure registration is in the db
162
+		) {
163
+			// TO approved
164
+			if ($new_STS_ID === EEM_Registration::status_id_approved) {
165
+				// reserve a space by incrementing ticket and datetime sold values
166
+				$this->_reserve_registration_space();
167
+				do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
168
+				// OR FROM  approved
169
+			} elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
170
+				// release a space by decrementing ticket and datetime sold values
171
+				$this->_release_registration_space();
172
+				do_action(
173
+					'AHEE__EE_Registration__set_status__from_approved',
174
+					$this,
175
+					$old_STS_ID,
176
+					$new_STS_ID,
177
+					$context
178
+				);
179
+			}
180
+			// update status
181
+			parent::set('STS_ID', $new_STS_ID, $use_default);
182
+			$this->_update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, $context);
183
+			if ($this->statusChangeUpdatesTransaction($context)) {
184
+				$this->updateTransactionAfterStatusChange();
185
+			}
186
+			do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
187
+			return true;
188
+		}
189
+		// even though the old value matches the new value, it's still good to
190
+		// allow the parent set method to have a say
191
+		parent::set('STS_ID', $new_STS_ID, $use_default);
192
+		return true;
193
+	}
194
+
195
+
196
+	/**
197
+	 * update REGs and TXN when cancelled or declined registrations involved
198
+	 *
199
+	 * @param string                $new_STS_ID
200
+	 * @param string                $old_STS_ID
201
+	 * @param ContextInterface|null $context
202
+	 * @throws EE_Error
203
+	 * @throws InvalidArgumentException
204
+	 * @throws InvalidDataTypeException
205
+	 * @throws InvalidInterfaceException
206
+	 * @throws ReflectionException
207
+	 */
208
+	private function _update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
209
+	{
210
+		// these reg statuses should not be considered in any calculations involving monies owing
211
+		$closed_reg_statuses = EEM_Registration::closed_reg_statuses();
212
+		// true if registration has been cancelled or declined
213
+		$this->updateIfCanceled(
214
+			$closed_reg_statuses,
215
+			$new_STS_ID,
216
+			$old_STS_ID,
217
+			$context
218
+		);
219
+		$this->updateIfDeclined(
220
+			$closed_reg_statuses,
221
+			$new_STS_ID,
222
+			$old_STS_ID,
223
+			$context
224
+		);
225
+	}
226
+
227
+
228
+	/**
229
+	 * update REGs and TXN when cancelled or declined registrations involved
230
+	 *
231
+	 * @param array                 $closed_reg_statuses
232
+	 * @param string                $new_STS_ID
233
+	 * @param string                $old_STS_ID
234
+	 * @param ContextInterface|null $context
235
+	 * @throws EE_Error
236
+	 * @throws InvalidArgumentException
237
+	 * @throws InvalidDataTypeException
238
+	 * @throws InvalidInterfaceException
239
+	 * @throws ReflectionException
240
+	 */
241
+	private function updateIfCanceled(
242
+		array $closed_reg_statuses,
243
+		$new_STS_ID,
244
+		$old_STS_ID,
245
+		ContextInterface $context = null
246
+	) {
247
+		// true if registration has been cancelled or declined
248
+		if (in_array($new_STS_ID, $closed_reg_statuses, true)
249
+			&& ! in_array($old_STS_ID, $closed_reg_statuses, true)
250
+		) {
251
+			/** @type EE_Registration_Processor $registration_processor */
252
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
253
+			/** @type EE_Transaction_Processor $transaction_processor */
254
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
255
+			// cancelled or declined registration
256
+			$registration_processor->update_registration_after_being_canceled_or_declined(
257
+				$this,
258
+				$closed_reg_statuses
259
+			);
260
+			$transaction_processor->update_transaction_after_canceled_or_declined_registration(
261
+				$this,
262
+				$closed_reg_statuses,
263
+				false
264
+			);
265
+			do_action(
266
+				'AHEE__EE_Registration__set_status__canceled_or_declined',
267
+				$this,
268
+				$old_STS_ID,
269
+				$new_STS_ID,
270
+				$context
271
+			);
272
+			return;
273
+		}
274
+	}
275
+
276
+
277
+	/**
278
+	 * update REGs and TXN when cancelled or declined registrations involved
279
+	 *
280
+	 * @param array                 $closed_reg_statuses
281
+	 * @param string                $new_STS_ID
282
+	 * @param string                $old_STS_ID
283
+	 * @param ContextInterface|null $context
284
+	 * @throws EE_Error
285
+	 * @throws InvalidArgumentException
286
+	 * @throws InvalidDataTypeException
287
+	 * @throws InvalidInterfaceException
288
+	 * @throws ReflectionException
289
+	 */
290
+	private function updateIfDeclined(
291
+		array $closed_reg_statuses,
292
+		$new_STS_ID,
293
+		$old_STS_ID,
294
+		ContextInterface $context = null
295
+	) {
296
+		// true if reinstating cancelled or declined registration
297
+		if (in_array($old_STS_ID, $closed_reg_statuses, true)
298
+			&& ! in_array($new_STS_ID, $closed_reg_statuses, true)
299
+		) {
300
+			/** @type EE_Registration_Processor $registration_processor */
301
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
302
+			/** @type EE_Transaction_Processor $transaction_processor */
303
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
304
+			// reinstating cancelled or declined registration
305
+			$registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
306
+				$this,
307
+				$closed_reg_statuses
308
+			);
309
+			$transaction_processor->update_transaction_after_reinstating_canceled_registration(
310
+				$this,
311
+				$closed_reg_statuses,
312
+				false
313
+			);
314
+			do_action(
315
+				'AHEE__EE_Registration__set_status__after_reinstated',
316
+				$this,
317
+				$old_STS_ID,
318
+				$new_STS_ID,
319
+				$context
320
+			);
321
+		}
322
+	}
323
+
324
+
325
+	/**
326
+	 * @param ContextInterface|null $context
327
+	 * @return bool
328
+	 */
329
+	private function statusChangeUpdatesTransaction(ContextInterface $context = null)
330
+	{
331
+		$contexts_that_do_not_update_transaction = (array) apply_filters(
332
+			'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
333
+			array('spco_reg_step_attendee_information_process_registrations'),
334
+			$context,
335
+			$this
336
+		);
337
+		return ! (
338
+			$context instanceof ContextInterface
339
+			&& in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
340
+		);
341
+	}
342
+
343
+
344
+	/**
345
+	 * @throws EE_Error
346
+	 * @throws EntityNotFoundException
347
+	 * @throws InvalidArgumentException
348
+	 * @throws InvalidDataTypeException
349
+	 * @throws InvalidInterfaceException
350
+	 * @throws ReflectionException
351
+	 * @throws RuntimeException
352
+	 */
353
+	private function updateTransactionAfterStatusChange()
354
+	{
355
+		/** @type EE_Transaction_Payments $transaction_payments */
356
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
357
+		$transaction_payments->recalculate_transaction_total($this->transaction(), false);
358
+		$this->transaction()->update_status_based_on_total_paid(true);
359
+	}
360
+
361
+
362
+	/**
363
+	 *        get Status ID
364
+	 */
365
+	public function status_ID()
366
+	{
367
+		return $this->get('STS_ID');
368
+	}
369
+
370
+
371
+	/**
372
+	 * Gets the ticket this registration is for
373
+	 *
374
+	 * @param boolean $include_archived whether to include archived tickets or not.
375
+	 *
376
+	 * @return EE_Ticket|EE_Base_Class
377
+	 * @throws EE_Error
378
+	 */
379
+	public function ticket($include_archived = true)
380
+	{
381
+		$query_params = array();
382
+		if ($include_archived) {
383
+			$query_params['default_where_conditions'] = 'none';
384
+		}
385
+		return $this->get_first_related('Ticket', $query_params);
386
+	}
387
+
388
+
389
+	/**
390
+	 * Gets the event this registration is for
391
+	 *
392
+	 * @return EE_Event
393
+	 * @throws EE_Error
394
+	 * @throws EntityNotFoundException
395
+	 */
396
+	public function event()
397
+	{
398
+		$event = $this->get_first_related('Event');
399
+		if (! $event instanceof \EE_Event) {
400
+			throw new EntityNotFoundException('Event ID', $this->event_ID());
401
+		}
402
+		return $event;
403
+	}
404
+
405
+
406
+	/**
407
+	 * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
408
+	 * with the author of the event this registration is for.
409
+	 *
410
+	 * @since 4.5.0
411
+	 * @return int
412
+	 * @throws EE_Error
413
+	 * @throws EntityNotFoundException
414
+	 */
415
+	public function wp_user()
416
+	{
417
+		$event = $this->event();
418
+		if ($event instanceof EE_Event) {
419
+			return $event->wp_user();
420
+		}
421
+		return 0;
422
+	}
423
+
424
+
425
+	/**
426
+	 * increments this registration's related ticket sold and corresponding datetime sold values
427
+	 *
428
+	 * @return void
429
+	 * @throws DomainException
430
+	 * @throws EE_Error
431
+	 * @throws EntityNotFoundException
432
+	 * @throws InvalidArgumentException
433
+	 * @throws InvalidDataTypeException
434
+	 * @throws InvalidInterfaceException
435
+	 * @throws ReflectionException
436
+	 * @throws UnexpectedEntityException
437
+	 */
438
+	private function _reserve_registration_space()
439
+	{
440
+		// reserved ticket and datetime counts will be decremented as sold counts are incremented
441
+		// so stop tracking that this reg has a ticket reserved
442
+		$this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
443
+		$ticket = $this->ticket();
444
+		$ticket->increase_sold();
445
+		$ticket->save();
446
+		// possibly set event status to sold out
447
+		$this->event()->perform_sold_out_status_check();
448
+	}
449
+
450
+
451
+	/**
452
+	 * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
453
+	 *
454
+	 * @return void
455
+	 * @throws DomainException
456
+	 * @throws EE_Error
457
+	 * @throws EntityNotFoundException
458
+	 * @throws InvalidArgumentException
459
+	 * @throws InvalidDataTypeException
460
+	 * @throws InvalidInterfaceException
461
+	 * @throws ReflectionException
462
+	 * @throws UnexpectedEntityException
463
+	 */
464
+	private function _release_registration_space()
465
+	{
466
+		$ticket = $this->ticket();
467
+		$ticket->decrease_sold();
468
+		$ticket->save();
469
+		// possibly change event status from sold out back to previous status
470
+		$this->event()->perform_sold_out_status_check();
471
+	}
472
+
473
+
474
+	/**
475
+	 * tracks this registration's ticket reservation in extra meta
476
+	 * and can increment related ticket reserved and corresponding datetime reserved values
477
+	 *
478
+	 * @param bool $update_ticket if true, will increment ticket and datetime reserved count
479
+	 * @return void
480
+	 * @throws EE_Error
481
+	 * @throws InvalidArgumentException
482
+	 * @throws InvalidDataTypeException
483
+	 * @throws InvalidInterfaceException
484
+	 * @throws ReflectionException
485
+	 */
486
+	public function reserve_ticket($update_ticket = false, $source = 'unknown')
487
+	{
488
+		// only reserve ticket if space is not currently reserved
489
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
490
+			$this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
491
+			// IMPORTANT !!!
492
+			// although checking $update_ticket first would be more efficient,
493
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
494
+			if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
495
+				&& $update_ticket
496
+			) {
497
+				$ticket = $this->ticket();
498
+				$ticket->increase_reserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
499
+				$ticket->save();
500
+			}
501
+		}
502
+	}
503
+
504
+
505
+	/**
506
+	 * stops tracking this registration's ticket reservation in extra meta
507
+	 * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
508
+	 *
509
+	 * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
510
+	 * @return void
511
+	 * @throws EE_Error
512
+	 * @throws InvalidArgumentException
513
+	 * @throws InvalidDataTypeException
514
+	 * @throws InvalidInterfaceException
515
+	 * @throws ReflectionException
516
+	 */
517
+	public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
518
+	{
519
+		// only release ticket if space is currently reserved
520
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
521
+			$this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
522
+			// IMPORTANT !!!
523
+			// although checking $update_ticket first would be more efficient,
524
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
525
+			if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
526
+				&& $update_ticket
527
+			) {
528
+				$ticket = $this->ticket();
529
+				$ticket->decrease_reserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
530
+				$ticket->save();
531
+			}
532
+		}
533
+	}
534
+
535
+
536
+	/**
537
+	 * Set Attendee ID
538
+	 *
539
+	 * @param        int $ATT_ID Attendee ID
540
+	 * @throws EE_Error
541
+	 * @throws RuntimeException
542
+	 */
543
+	public function set_attendee_id($ATT_ID = 0)
544
+	{
545
+		$this->set('ATT_ID', $ATT_ID);
546
+	}
547
+
548
+
549
+	/**
550
+	 *        Set Transaction ID
551
+	 *
552
+	 * @param        int $TXN_ID Transaction ID
553
+	 * @throws EE_Error
554
+	 * @throws RuntimeException
555
+	 */
556
+	public function set_transaction_id($TXN_ID = 0)
557
+	{
558
+		$this->set('TXN_ID', $TXN_ID);
559
+	}
560
+
561
+
562
+	/**
563
+	 *        Set Session
564
+	 *
565
+	 * @param    string $REG_session PHP Session ID
566
+	 * @throws EE_Error
567
+	 * @throws RuntimeException
568
+	 */
569
+	public function set_session($REG_session = '')
570
+	{
571
+		$this->set('REG_session', $REG_session);
572
+	}
573
+
574
+
575
+	/**
576
+	 *        Set Registration URL Link
577
+	 *
578
+	 * @param    string $REG_url_link Registration URL Link
579
+	 * @throws EE_Error
580
+	 * @throws RuntimeException
581
+	 */
582
+	public function set_reg_url_link($REG_url_link = '')
583
+	{
584
+		$this->set('REG_url_link', $REG_url_link);
585
+	}
586
+
587
+
588
+	/**
589
+	 *        Set Attendee Counter
590
+	 *
591
+	 * @param        int $REG_count Primary Attendee
592
+	 * @throws EE_Error
593
+	 * @throws RuntimeException
594
+	 */
595
+	public function set_count($REG_count = 1)
596
+	{
597
+		$this->set('REG_count', $REG_count);
598
+	}
599
+
600
+
601
+	/**
602
+	 *        Set Group Size
603
+	 *
604
+	 * @param        boolean $REG_group_size Group Registration
605
+	 * @throws EE_Error
606
+	 * @throws RuntimeException
607
+	 */
608
+	public function set_group_size($REG_group_size = false)
609
+	{
610
+		$this->set('REG_group_size', $REG_group_size);
611
+	}
612
+
613
+
614
+	/**
615
+	 *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
616
+	 *    EEM_Registration::status_id_not_approved
617
+	 *
618
+	 * @return        boolean
619
+	 */
620
+	public function is_not_approved()
621
+	{
622
+		return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
623
+	}
624
+
625
+
626
+	/**
627
+	 *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
628
+	 *    EEM_Registration::status_id_pending_payment
629
+	 *
630
+	 * @return        boolean
631
+	 */
632
+	public function is_pending_payment()
633
+	{
634
+		return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
635
+	}
636
+
637
+
638
+	/**
639
+	 *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
640
+	 *
641
+	 * @return        boolean
642
+	 */
643
+	public function is_approved()
644
+	{
645
+		return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
646
+	}
647
+
648
+
649
+	/**
650
+	 *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
651
+	 *
652
+	 * @return        boolean
653
+	 */
654
+	public function is_cancelled()
655
+	{
656
+		return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
657
+	}
658
+
659
+
660
+	/**
661
+	 *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
662
+	 *
663
+	 * @return        boolean
664
+	 */
665
+	public function is_declined()
666
+	{
667
+		return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
668
+	}
669
+
670
+
671
+	/**
672
+	 *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
673
+	 *    EEM_Registration::status_id_incomplete
674
+	 *
675
+	 * @return        boolean
676
+	 */
677
+	public function is_incomplete()
678
+	{
679
+		return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
680
+	}
681
+
682
+
683
+	/**
684
+	 *        Set Registration Date
685
+	 *
686
+	 * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
687
+	 *                                                 Date
688
+	 * @throws EE_Error
689
+	 * @throws RuntimeException
690
+	 */
691
+	public function set_reg_date($REG_date = false)
692
+	{
693
+		$this->set('REG_date', $REG_date);
694
+	}
695
+
696
+
697
+	/**
698
+	 *    Set final price owing for this registration after all ticket/price modifications
699
+	 *
700
+	 * @access    public
701
+	 * @param    float $REG_final_price
702
+	 * @throws EE_Error
703
+	 * @throws RuntimeException
704
+	 */
705
+	public function set_final_price($REG_final_price = 0.00)
706
+	{
707
+		$this->set('REG_final_price', $REG_final_price);
708
+	}
709
+
710
+
711
+	/**
712
+	 *    Set amount paid towards this registration's final price
713
+	 *
714
+	 * @access    public
715
+	 * @param    float $REG_paid
716
+	 * @throws EE_Error
717
+	 * @throws RuntimeException
718
+	 */
719
+	public function set_paid($REG_paid = 0.00)
720
+	{
721
+		$this->set('REG_paid', $REG_paid);
722
+	}
723
+
724
+
725
+	/**
726
+	 *        Attendee Is Going
727
+	 *
728
+	 * @param        boolean $REG_att_is_going Attendee Is Going
729
+	 * @throws EE_Error
730
+	 * @throws RuntimeException
731
+	 */
732
+	public function set_att_is_going($REG_att_is_going = false)
733
+	{
734
+		$this->set('REG_att_is_going', $REG_att_is_going);
735
+	}
736
+
737
+
738
+	/**
739
+	 * Gets the related attendee
740
+	 *
741
+	 * @return EE_Attendee
742
+	 * @throws EE_Error
743
+	 */
744
+	public function attendee()
745
+	{
746
+		return $this->get_first_related('Attendee');
747
+	}
748
+
749
+
750
+	/**
751
+	 *        get Event ID
752
+	 */
753
+	public function event_ID()
754
+	{
755
+		return $this->get('EVT_ID');
756
+	}
757
+
758
+
759
+	/**
760
+	 *        get Event ID
761
+	 */
762
+	public function event_name()
763
+	{
764
+		$event = $this->event_obj();
765
+		if ($event) {
766
+			return $event->name();
767
+		} else {
768
+			return null;
769
+		}
770
+	}
771
+
772
+
773
+	/**
774
+	 * Fetches the event this registration is for
775
+	 *
776
+	 * @return EE_Event
777
+	 * @throws EE_Error
778
+	 */
779
+	public function event_obj()
780
+	{
781
+		return $this->get_first_related('Event');
782
+	}
783
+
784
+
785
+	/**
786
+	 *        get Attendee ID
787
+	 */
788
+	public function attendee_ID()
789
+	{
790
+		return $this->get('ATT_ID');
791
+	}
792
+
793
+
794
+	/**
795
+	 *        get PHP Session ID
796
+	 */
797
+	public function session_ID()
798
+	{
799
+		return $this->get('REG_session');
800
+	}
801
+
802
+
803
+	/**
804
+	 * Gets the string which represents the URL trigger for the receipt template in the message template system.
805
+	 *
806
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
807
+	 * @return string
808
+	 */
809
+	public function receipt_url($messenger = 'html')
810
+	{
811
+
812
+		/**
813
+		 * The below will be deprecated one version after this.  We check first if there is a custom receipt template
814
+		 * already in use on old system.  If there is then we just return the standard url for it.
815
+		 *
816
+		 * @since 4.5.0
817
+		 */
818
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
819
+		$has_custom = EEH_Template::locate_template(
820
+			$template_relative_path,
821
+			array(),
822
+			true,
823
+			true,
824
+			true
825
+		);
826
+
827
+		if ($has_custom) {
828
+			return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
829
+		}
830
+		return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
831
+	}
832
+
833
+
834
+	/**
835
+	 * Gets the string which represents the URL trigger for the invoice template in the message template system.
836
+	 *
837
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
838
+	 * @return string
839
+	 * @throws EE_Error
840
+	 */
841
+	public function invoice_url($messenger = 'html')
842
+	{
843
+		/**
844
+		 * The below will be deprecated one version after this.  We check first if there is a custom invoice template
845
+		 * already in use on old system.  If there is then we just return the standard url for it.
846
+		 *
847
+		 * @since 4.5.0
848
+		 */
849
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
850
+		$has_custom = EEH_Template::locate_template(
851
+			$template_relative_path,
852
+			array(),
853
+			true,
854
+			true,
855
+			true
856
+		);
857
+
858
+		if ($has_custom) {
859
+			if ($messenger == 'html') {
860
+				return $this->invoice_url('launch');
861
+			}
862
+			$route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
863
+
864
+			$query_args = array('ee' => $route, 'id' => $this->reg_url_link());
865
+			if ($messenger == 'html') {
866
+				$query_args['html'] = true;
867
+			}
868
+			return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
869
+		}
870
+		return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
871
+	}
872
+
873
+
874
+	/**
875
+	 * get Registration URL Link
876
+	 *
877
+	 * @access public
878
+	 * @return string
879
+	 * @throws EE_Error
880
+	 */
881
+	public function reg_url_link()
882
+	{
883
+		return (string) $this->get('REG_url_link');
884
+	}
885
+
886
+
887
+	/**
888
+	 * Echoes out invoice_url()
889
+	 *
890
+	 * @param string $type 'download','launch', or 'html' (default is 'launch')
891
+	 * @return void
892
+	 * @throws EE_Error
893
+	 */
894
+	public function e_invoice_url($type = 'launch')
895
+	{
896
+		echo $this->invoice_url($type);
897
+	}
898
+
899
+
900
+	/**
901
+	 * Echoes out payment_overview_url
902
+	 */
903
+	public function e_payment_overview_url()
904
+	{
905
+		echo $this->payment_overview_url();
906
+	}
907
+
908
+
909
+	/**
910
+	 * Gets the URL for the checkout payment options reg step
911
+	 * with this registration's REG_url_link added as a query parameter
912
+	 *
913
+	 * @param bool $clear_session Set to true when you want to clear the session on revisiting the
914
+	 *                            payment overview url.
915
+	 * @return string
916
+	 * @throws InvalidInterfaceException
917
+	 * @throws InvalidDataTypeException
918
+	 * @throws EE_Error
919
+	 * @throws InvalidArgumentException
920
+	 */
921
+	public function payment_overview_url($clear_session = false)
922
+	{
923
+		return add_query_arg(
924
+			(array) apply_filters(
925
+				'FHEE__EE_Registration__payment_overview_url__query_args',
926
+				array(
927
+					'e_reg_url_link' => $this->reg_url_link(),
928
+					'step'           => 'payment_options',
929
+					'revisit'        => true,
930
+					'clear_session'  => (bool) $clear_session,
931
+				),
932
+				$this
933
+			),
934
+			EE_Registry::instance()->CFG->core->reg_page_url()
935
+		);
936
+	}
937
+
938
+
939
+	/**
940
+	 * Gets the URL for the checkout attendee information reg step
941
+	 * with this registration's REG_url_link added as a query parameter
942
+	 *
943
+	 * @return string
944
+	 * @throws InvalidInterfaceException
945
+	 * @throws InvalidDataTypeException
946
+	 * @throws EE_Error
947
+	 * @throws InvalidArgumentException
948
+	 */
949
+	public function edit_attendee_information_url()
950
+	{
951
+		return add_query_arg(
952
+			(array) apply_filters(
953
+				'FHEE__EE_Registration__edit_attendee_information_url__query_args',
954
+				array(
955
+					'e_reg_url_link' => $this->reg_url_link(),
956
+					'step'           => 'attendee_information',
957
+					'revisit'        => true,
958
+				),
959
+				$this
960
+			),
961
+			EE_Registry::instance()->CFG->core->reg_page_url()
962
+		);
963
+	}
964
+
965
+
966
+	/**
967
+	 * Simply generates and returns the appropriate admin_url link to edit this registration
968
+	 *
969
+	 * @return string
970
+	 * @throws EE_Error
971
+	 */
972
+	public function get_admin_edit_url()
973
+	{
974
+		return EEH_URL::add_query_args_and_nonce(
975
+			array(
976
+				'page'    => 'espresso_registrations',
977
+				'action'  => 'view_registration',
978
+				'_REG_ID' => $this->ID(),
979
+			),
980
+			admin_url('admin.php')
981
+		);
982
+	}
983
+
984
+
985
+	/**
986
+	 *    is_primary_registrant?
987
+	 */
988
+	public function is_primary_registrant()
989
+	{
990
+		return $this->get('REG_count') == 1 ? true : false;
991
+	}
992
+
993
+
994
+	/**
995
+	 * This returns the primary registration object for this registration group (which may be this object).
996
+	 *
997
+	 * @return EE_Registration
998
+	 * @throws EE_Error
999
+	 */
1000
+	public function get_primary_registration()
1001
+	{
1002
+		if ($this->is_primary_registrant()) {
1003
+			return $this;
1004
+		}
1005
+
1006
+		// k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1007
+		/** @var EE_Registration $primary_registrant */
1008
+		$primary_registrant = EEM_Registration::instance()->get_one(
1009
+			array(
1010
+				array(
1011
+					'TXN_ID'    => $this->transaction_ID(),
1012
+					'REG_count' => 1,
1013
+				),
1014
+			)
1015
+		);
1016
+		return $primary_registrant;
1017
+	}
1018
+
1019
+
1020
+	/**
1021
+	 *        get  Attendee Number
1022
+	 *
1023
+	 * @access        public
1024
+	 */
1025
+	public function count()
1026
+	{
1027
+		return $this->get('REG_count');
1028
+	}
1029
+
1030
+
1031
+	/**
1032
+	 *        get Group Size
1033
+	 */
1034
+	public function group_size()
1035
+	{
1036
+		return $this->get('REG_group_size');
1037
+	}
1038
+
1039
+
1040
+	/**
1041
+	 *        get Registration Date
1042
+	 */
1043
+	public function date()
1044
+	{
1045
+		return $this->get('REG_date');
1046
+	}
1047
+
1048
+
1049
+	/**
1050
+	 * gets a pretty date
1051
+	 *
1052
+	 * @param string $date_format
1053
+	 * @param string $time_format
1054
+	 * @return string
1055
+	 * @throws EE_Error
1056
+	 */
1057
+	public function pretty_date($date_format = null, $time_format = null)
1058
+	{
1059
+		return $this->get_datetime('REG_date', $date_format, $time_format);
1060
+	}
1061
+
1062
+
1063
+	/**
1064
+	 * final_price
1065
+	 * the registration's share of the transaction total, so that the
1066
+	 * sum of all the transaction's REG_final_prices equal the transaction's total
1067
+	 *
1068
+	 * @return float
1069
+	 * @throws EE_Error
1070
+	 */
1071
+	public function final_price()
1072
+	{
1073
+		return $this->get('REG_final_price');
1074
+	}
1075
+
1076
+
1077
+	/**
1078
+	 * pretty_final_price
1079
+	 *  final price as formatted string, with correct decimal places and currency symbol
1080
+	 *
1081
+	 * @return string
1082
+	 * @throws EE_Error
1083
+	 */
1084
+	public function pretty_final_price()
1085
+	{
1086
+		return $this->get_pretty('REG_final_price');
1087
+	}
1088
+
1089
+
1090
+	/**
1091
+	 * get paid (yeah)
1092
+	 *
1093
+	 * @return float
1094
+	 * @throws EE_Error
1095
+	 */
1096
+	public function paid()
1097
+	{
1098
+		return $this->get('REG_paid');
1099
+	}
1100
+
1101
+
1102
+	/**
1103
+	 * pretty_paid
1104
+	 *
1105
+	 * @return float
1106
+	 * @throws EE_Error
1107
+	 */
1108
+	public function pretty_paid()
1109
+	{
1110
+		return $this->get_pretty('REG_paid');
1111
+	}
1112
+
1113
+
1114
+	/**
1115
+	 * owes_monies_and_can_pay
1116
+	 * whether or not this registration has monies owing and it's' status allows payment
1117
+	 *
1118
+	 * @param array $requires_payment
1119
+	 * @return bool
1120
+	 * @throws EE_Error
1121
+	 */
1122
+	public function owes_monies_and_can_pay($requires_payment = array())
1123
+	{
1124
+		// these reg statuses require payment (if event is not free)
1125
+		$requires_payment = ! empty($requires_payment)
1126
+			? $requires_payment
1127
+			: EEM_Registration::reg_statuses_that_allow_payment();
1128
+		if (in_array($this->status_ID(), $requires_payment) &&
1129
+			$this->final_price() != 0 &&
1130
+			$this->final_price() != $this->paid()
1131
+		) {
1132
+			return true;
1133
+		} else {
1134
+			return false;
1135
+		}
1136
+	}
1137
+
1138
+
1139
+	/**
1140
+	 * Prints out the return value of $this->pretty_status()
1141
+	 *
1142
+	 * @param bool $show_icons
1143
+	 * @return void
1144
+	 * @throws EE_Error
1145
+	 */
1146
+	public function e_pretty_status($show_icons = false)
1147
+	{
1148
+		echo $this->pretty_status($show_icons);
1149
+	}
1150
+
1151
+
1152
+	/**
1153
+	 * Returns a nice version of the status for displaying to customers
1154
+	 *
1155
+	 * @param bool $show_icons
1156
+	 * @return string
1157
+	 * @throws EE_Error
1158
+	 */
1159
+	public function pretty_status($show_icons = false)
1160
+	{
1161
+		$status = EEM_Status::instance()->localized_status(
1162
+			array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1163
+			false,
1164
+			'sentence'
1165
+		);
1166
+		$icon = '';
1167
+		switch ($this->status_ID()) {
1168
+			case EEM_Registration::status_id_approved:
1169
+				$icon = $show_icons
1170
+					? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1171
+					: '';
1172
+				break;
1173
+			case EEM_Registration::status_id_pending_payment:
1174
+				$icon = $show_icons
1175
+					? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1176
+					: '';
1177
+				break;
1178
+			case EEM_Registration::status_id_not_approved:
1179
+				$icon = $show_icons
1180
+					? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1181
+					: '';
1182
+				break;
1183
+			case EEM_Registration::status_id_cancelled:
1184
+				$icon = $show_icons
1185
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1186
+					: '';
1187
+				break;
1188
+			case EEM_Registration::status_id_incomplete:
1189
+				$icon = $show_icons
1190
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1191
+					: '';
1192
+				break;
1193
+			case EEM_Registration::status_id_declined:
1194
+				$icon = $show_icons
1195
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1196
+					: '';
1197
+				break;
1198
+			case EEM_Registration::status_id_wait_list:
1199
+				$icon = $show_icons
1200
+					? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1201
+					: '';
1202
+				break;
1203
+		}
1204
+		return $icon . $status[ $this->status_ID() ];
1205
+	}
1206
+
1207
+
1208
+	/**
1209
+	 *        get Attendee Is Going
1210
+	 */
1211
+	public function att_is_going()
1212
+	{
1213
+		return $this->get('REG_att_is_going');
1214
+	}
1215
+
1216
+
1217
+	/**
1218
+	 * Gets related answers
1219
+	 *
1220
+	 * @param array $query_params like EEM_Base::get_all
1221
+	 * @return EE_Answer[]
1222
+	 * @throws EE_Error
1223
+	 */
1224
+	public function answers($query_params = null)
1225
+	{
1226
+		return $this->get_many_related('Answer', $query_params);
1227
+	}
1228
+
1229
+
1230
+	/**
1231
+	 * Gets the registration's answer value to the specified question
1232
+	 * (either the question's ID or a question object)
1233
+	 *
1234
+	 * @param EE_Question|int $question
1235
+	 * @param bool            $pretty_value
1236
+	 * @return array|string if pretty_value= true, the result will always be a string
1237
+	 * (because the answer might be an array of answer values, so passing pretty_value=true
1238
+	 * will convert it into some kind of string)
1239
+	 * @throws EE_Error
1240
+	 */
1241
+	public function answer_value_to_question($question, $pretty_value = true)
1242
+	{
1243
+		$question_id = EEM_Question::instance()->ensure_is_ID($question);
1244
+		return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1245
+	}
1246
+
1247
+
1248
+	/**
1249
+	 * question_groups
1250
+	 * returns an array of EE_Question_Group objects for this registration
1251
+	 *
1252
+	 * @return EE_Question_Group[]
1253
+	 * @throws EE_Error
1254
+	 * @throws EntityNotFoundException
1255
+	 */
1256
+	public function question_groups()
1257
+	{
1258
+		$question_groups = array();
1259
+		if ($this->event() instanceof EE_Event) {
1260
+			$question_groups = $this->event()->question_groups(
1261
+				array(
1262
+					array(
1263
+						'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1264
+					),
1265
+					'order_by' => array('QSG_order' => 'ASC'),
1266
+				)
1267
+			);
1268
+		}
1269
+		return $question_groups;
1270
+	}
1271
+
1272
+
1273
+	/**
1274
+	 * count_question_groups
1275
+	 * returns a count of the number of EE_Question_Group objects for this registration
1276
+	 *
1277
+	 * @return int
1278
+	 * @throws EE_Error
1279
+	 * @throws EntityNotFoundException
1280
+	 */
1281
+	public function count_question_groups()
1282
+	{
1283
+		$qg_count = 0;
1284
+		if ($this->event() instanceof EE_Event) {
1285
+			$qg_count = $this->event()->count_related(
1286
+				'Question_Group',
1287
+				array(
1288
+					array(
1289
+						'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1290
+					),
1291
+				)
1292
+			);
1293
+		}
1294
+		return $qg_count;
1295
+	}
1296
+
1297
+
1298
+	/**
1299
+	 * Returns the registration date in the 'standard' string format
1300
+	 * (function may be improved in the future to allow for different formats and timezones)
1301
+	 *
1302
+	 * @return string
1303
+	 * @throws EE_Error
1304
+	 */
1305
+	public function reg_date()
1306
+	{
1307
+		return $this->get_datetime('REG_date');
1308
+	}
1309
+
1310
+
1311
+	/**
1312
+	 * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1313
+	 * the ticket this registration purchased, or the datetime they have registered
1314
+	 * to attend)
1315
+	 *
1316
+	 * @return EE_Datetime_Ticket
1317
+	 * @throws EE_Error
1318
+	 */
1319
+	public function datetime_ticket()
1320
+	{
1321
+		return $this->get_first_related('Datetime_Ticket');
1322
+	}
1323
+
1324
+
1325
+	/**
1326
+	 * Sets the registration's datetime_ticket.
1327
+	 *
1328
+	 * @param EE_Datetime_Ticket $datetime_ticket
1329
+	 * @return EE_Datetime_Ticket
1330
+	 * @throws EE_Error
1331
+	 */
1332
+	public function set_datetime_ticket($datetime_ticket)
1333
+	{
1334
+		return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1335
+	}
1336
+
1337
+	/**
1338
+	 * Gets deleted
1339
+	 *
1340
+	 * @return bool
1341
+	 * @throws EE_Error
1342
+	 */
1343
+	public function deleted()
1344
+	{
1345
+		return $this->get('REG_deleted');
1346
+	}
1347
+
1348
+	/**
1349
+	 * Sets deleted
1350
+	 *
1351
+	 * @param boolean $deleted
1352
+	 * @return bool
1353
+	 * @throws EE_Error
1354
+	 * @throws RuntimeException
1355
+	 */
1356
+	public function set_deleted($deleted)
1357
+	{
1358
+		if ($deleted) {
1359
+			$this->delete();
1360
+		} else {
1361
+			$this->restore();
1362
+		}
1363
+	}
1364
+
1365
+
1366
+	/**
1367
+	 * Get the status object of this object
1368
+	 *
1369
+	 * @return EE_Status
1370
+	 * @throws EE_Error
1371
+	 */
1372
+	public function status_obj()
1373
+	{
1374
+		return $this->get_first_related('Status');
1375
+	}
1376
+
1377
+
1378
+	/**
1379
+	 * Returns the number of times this registration has checked into any of the datetimes
1380
+	 * its available for
1381
+	 *
1382
+	 * @return int
1383
+	 * @throws EE_Error
1384
+	 */
1385
+	public function count_checkins()
1386
+	{
1387
+		return $this->get_model()->count_related($this, 'Checkin');
1388
+	}
1389
+
1390
+
1391
+	/**
1392
+	 * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1393
+	 * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1394
+	 *
1395
+	 * @return int
1396
+	 * @throws EE_Error
1397
+	 */
1398
+	public function count_checkins_not_checkedout()
1399
+	{
1400
+		return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1401
+	}
1402
+
1403
+
1404
+	/**
1405
+	 * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1406
+	 *
1407
+	 * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1408
+	 * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1409
+	 *                                          consider registration status as well as datetime access.
1410
+	 * @return bool
1411
+	 * @throws EE_Error
1412
+	 */
1413
+	public function can_checkin($DTT_OR_ID, $check_approved = true)
1414
+	{
1415
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1416
+
1417
+		// first check registration status
1418
+		if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1419
+			return false;
1420
+		}
1421
+		// is there a datetime ticket that matches this dtt_ID?
1422
+		if (! (EEM_Datetime_Ticket::instance()->exists(
1423
+			array(
1424
+				array(
1425
+					'TKT_ID' => $this->get('TKT_ID'),
1426
+					'DTT_ID' => $DTT_ID,
1427
+				),
1428
+			)
1429
+		))
1430
+		) {
1431
+			return false;
1432
+		}
1433
+
1434
+		// final check is against TKT_uses
1435
+		return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1436
+	}
1437
+
1438
+
1439
+	/**
1440
+	 * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1441
+	 * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1442
+	 * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1443
+	 * then return false.  Otherwise return true.
1444
+	 *
1445
+	 * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1446
+	 * @return bool true means can checkin.  false means cannot checkin.
1447
+	 * @throws EE_Error
1448
+	 */
1449
+	public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1450
+	{
1451
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1452
+
1453
+		if (! $DTT_ID) {
1454
+			return false;
1455
+		}
1456
+
1457
+		$max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1458
+
1459
+		// if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1460
+		// check-in or not.
1461
+		if (! $max_uses || $max_uses === EE_INF) {
1462
+			return true;
1463
+		}
1464
+
1465
+		// does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1466
+		// go ahead and toggle.
1467
+		if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1468
+			return true;
1469
+		}
1470
+
1471
+		// made it here so the last check is whether the number of checkins per unique datetime on this registration
1472
+		// disallows further check-ins.
1473
+		$count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1474
+			array(
1475
+				array(
1476
+					'REG_ID' => $this->ID(),
1477
+					'CHK_in' => true,
1478
+				),
1479
+			),
1480
+			'DTT_ID',
1481
+			true
1482
+		);
1483
+		// checkins have already reached their max number of uses
1484
+		// so registrant can NOT checkin
1485
+		if ($count_unique_dtt_checkins >= $max_uses) {
1486
+			EE_Error::add_error(
1487
+				esc_html__(
1488
+					'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1489
+					'event_espresso'
1490
+				),
1491
+				__FILE__,
1492
+				__FUNCTION__,
1493
+				__LINE__
1494
+			);
1495
+			return false;
1496
+		}
1497
+		return true;
1498
+	}
1499
+
1500
+
1501
+	/**
1502
+	 * toggle Check-in status for this registration
1503
+	 * Check-ins are toggled in the following order:
1504
+	 * never checked in -> checked in
1505
+	 * checked in -> checked out
1506
+	 * checked out -> checked in
1507
+	 *
1508
+	 * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1509
+	 *                      If not included or null, then it is assumed latest datetime is being toggled.
1510
+	 * @param bool $verify  If true then can_checkin() is used to verify whether the person
1511
+	 *                      can be checked in or not.  Otherwise this forces change in checkin status.
1512
+	 * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1513
+	 * @throws EE_Error
1514
+	 */
1515
+	public function toggle_checkin_status($DTT_ID = null, $verify = false)
1516
+	{
1517
+		if (empty($DTT_ID)) {
1518
+			$datetime = $this->get_latest_related_datetime();
1519
+			$DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1520
+			// verify the registration can checkin for the given DTT_ID
1521
+		} elseif (! $this->can_checkin($DTT_ID, $verify)) {
1522
+			EE_Error::add_error(
1523
+				sprintf(
1524
+					esc_html__(
1525
+						'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1526
+						'event_espresso'
1527
+					),
1528
+					$this->ID(),
1529
+					$DTT_ID
1530
+				),
1531
+				__FILE__,
1532
+				__FUNCTION__,
1533
+				__LINE__
1534
+			);
1535
+			return false;
1536
+		}
1537
+		$status_paths = array(
1538
+			EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1539
+			EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1540
+			EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1541
+		);
1542
+		// start by getting the current status so we know what status we'll be changing to.
1543
+		$cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1544
+		$status_to = $status_paths[ $cur_status ];
1545
+		// database only records true for checked IN or false for checked OUT
1546
+		// no record ( null ) means checked in NEVER, but we obviously don't save that
1547
+		$new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1548
+		// add relation - note Check-ins are always creating new rows
1549
+		// because we are keeping track of Check-ins over time.
1550
+		// Eventually we'll probably want to show a list table
1551
+		// for the individual Check-ins so that they can be managed.
1552
+		$checkin = EE_Checkin::new_instance(
1553
+			array(
1554
+				'REG_ID' => $this->ID(),
1555
+				'DTT_ID' => $DTT_ID,
1556
+				'CHK_in' => $new_status,
1557
+			)
1558
+		);
1559
+		// if the record could not be saved then return false
1560
+		if ($checkin->save() === 0) {
1561
+			if (WP_DEBUG) {
1562
+				global $wpdb;
1563
+				$error = sprintf(
1564
+					esc_html__(
1565
+						'Registration check in update failed because of the following database error: %1$s%2$s',
1566
+						'event_espresso'
1567
+					),
1568
+					'<br />',
1569
+					$wpdb->last_error
1570
+				);
1571
+			} else {
1572
+				$error = esc_html__(
1573
+					'Registration check in update failed because of an unknown database error',
1574
+					'event_espresso'
1575
+				);
1576
+			}
1577
+			EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1578
+			return false;
1579
+		}
1580
+		return $status_to;
1581
+	}
1582
+
1583
+
1584
+	/**
1585
+	 * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1586
+	 * "Latest" is defined by the `DTT_EVT_start` column.
1587
+	 *
1588
+	 * @return EE_Datetime|null
1589
+	 * @throws EE_Error
1590
+	 */
1591
+	public function get_latest_related_datetime()
1592
+	{
1593
+		return EEM_Datetime::instance()->get_one(
1594
+			array(
1595
+				array(
1596
+					'Ticket.Registration.REG_ID' => $this->ID(),
1597
+				),
1598
+				'order_by' => array('DTT_EVT_start' => 'DESC'),
1599
+			)
1600
+		);
1601
+	}
1602
+
1603
+
1604
+	/**
1605
+	 * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1606
+	 * "Earliest" is defined by the `DTT_EVT_start` column.
1607
+	 *
1608
+	 * @throws EE_Error
1609
+	 */
1610
+	public function get_earliest_related_datetime()
1611
+	{
1612
+		return EEM_Datetime::instance()->get_one(
1613
+			array(
1614
+				array(
1615
+					'Ticket.Registration.REG_ID' => $this->ID(),
1616
+				),
1617
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
1618
+			)
1619
+		);
1620
+	}
1621
+
1622
+
1623
+	/**
1624
+	 * This method simply returns the check-in status for this registration and the given datetime.
1625
+	 * If neither the datetime nor the checkin values are provided as arguments,
1626
+	 * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1627
+	 *
1628
+	 * @param  int       $DTT_ID  The ID of the datetime we're checking against
1629
+	 *                            (if empty we'll get the primary datetime for
1630
+	 *                            this registration (via event) and use it's ID);
1631
+	 * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1632
+	 *
1633
+	 * @return int                Integer representing Check-in status.
1634
+	 * @throws EE_Error
1635
+	 */
1636
+	public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1637
+	{
1638
+		$checkin_query_params = array(
1639
+			'order_by' => array('CHK_timestamp' => 'DESC'),
1640
+		);
1641
+
1642
+		if ($DTT_ID > 0) {
1643
+			$checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1644
+		}
1645
+
1646
+		// get checkin object (if exists)
1647
+		$checkin = $checkin instanceof EE_Checkin
1648
+			? $checkin
1649
+			: $this->get_first_related('Checkin', $checkin_query_params);
1650
+		if ($checkin instanceof EE_Checkin) {
1651
+			if ($checkin->get('CHK_in')) {
1652
+				return EE_Checkin::status_checked_in; // checked in
1653
+			}
1654
+			return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1655
+		}
1656
+		return EE_Checkin::status_checked_never; // never been checked in
1657
+	}
1658
+
1659
+
1660
+	/**
1661
+	 * This method returns a localized message for the toggled Check-in message.
1662
+	 *
1663
+	 * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1664
+	 *                     then it is assumed Check-in for primary datetime was toggled.
1665
+	 * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1666
+	 *                     message can be customized with the attendee name.
1667
+	 * @return string internationalized message
1668
+	 * @throws EE_Error
1669
+	 */
1670
+	public function get_checkin_msg($DTT_ID, $error = false)
1671
+	{
1672
+		// let's get the attendee first so we can include the name of the attendee
1673
+		$attendee = $this->get_first_related('Attendee');
1674
+		if ($attendee instanceof EE_Attendee) {
1675
+			if ($error) {
1676
+				return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1677
+			}
1678
+			$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1679
+			// what is the status message going to be?
1680
+			switch ($cur_status) {
1681
+				case EE_Checkin::status_checked_never:
1682
+					return sprintf(
1683
+						__("%s has been removed from Check-in records", "event_espresso"),
1684
+						$attendee->full_name()
1685
+					);
1686
+					break;
1687
+				case EE_Checkin::status_checked_in:
1688
+					return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1689
+					break;
1690
+				case EE_Checkin::status_checked_out:
1691
+					return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1692
+					break;
1693
+			}
1694
+		}
1695
+		return esc_html__("The check-in status could not be determined.", "event_espresso");
1696
+	}
1697
+
1698
+
1699
+	/**
1700
+	 * Returns the related EE_Transaction to this registration
1701
+	 *
1702
+	 * @return EE_Transaction
1703
+	 * @throws EE_Error
1704
+	 * @throws EntityNotFoundException
1705
+	 */
1706
+	public function transaction()
1707
+	{
1708
+		$transaction = $this->get_first_related('Transaction');
1709
+		if (! $transaction instanceof \EE_Transaction) {
1710
+			throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1711
+		}
1712
+		return $transaction;
1713
+	}
1714
+
1715
+
1716
+	/**
1717
+	 *        get Registration Code
1718
+	 */
1719
+	public function reg_code()
1720
+	{
1721
+		return $this->get('REG_code');
1722
+	}
1723
+
1724
+
1725
+	/**
1726
+	 *        get Transaction ID
1727
+	 */
1728
+	public function transaction_ID()
1729
+	{
1730
+		return $this->get('TXN_ID');
1731
+	}
1732
+
1733
+
1734
+	/**
1735
+	 * @return int
1736
+	 * @throws EE_Error
1737
+	 */
1738
+	public function ticket_ID()
1739
+	{
1740
+		return $this->get('TKT_ID');
1741
+	}
1742
+
1743
+
1744
+	/**
1745
+	 *        Set Registration Code
1746
+	 *
1747
+	 * @access    public
1748
+	 * @param    string  $REG_code Registration Code
1749
+	 * @param    boolean $use_default
1750
+	 * @throws EE_Error
1751
+	 */
1752
+	public function set_reg_code($REG_code, $use_default = false)
1753
+	{
1754
+		if (empty($REG_code)) {
1755
+			EE_Error::add_error(
1756
+				esc_html__('REG_code can not be empty.', 'event_espresso'),
1757
+				__FILE__,
1758
+				__FUNCTION__,
1759
+				__LINE__
1760
+			);
1761
+			return;
1762
+		}
1763
+		if (! $this->reg_code()) {
1764
+			parent::set('REG_code', $REG_code, $use_default);
1765
+		} else {
1766
+			EE_Error::doing_it_wrong(
1767
+				__CLASS__ . '::' . __FUNCTION__,
1768
+				esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1769
+				'4.6.0'
1770
+			);
1771
+		}
1772
+	}
1773
+
1774
+
1775
+	/**
1776
+	 * Returns all other registrations in the same group as this registrant who have the same ticket option.
1777
+	 * Note, if you want to just get all registrations in the same transaction (group), use:
1778
+	 *    $registration->transaction()->registrations();
1779
+	 *
1780
+	 * @since 4.5.0
1781
+	 * @return EE_Registration[] or empty array if this isn't a group registration.
1782
+	 * @throws EE_Error
1783
+	 */
1784
+	public function get_all_other_registrations_in_group()
1785
+	{
1786
+		if ($this->group_size() < 2) {
1787
+			return array();
1788
+		}
1789
+
1790
+		$query[0] = array(
1791
+			'TXN_ID' => $this->transaction_ID(),
1792
+			'REG_ID' => array('!=', $this->ID()),
1793
+			'TKT_ID' => $this->ticket_ID(),
1794
+		);
1795
+		/** @var EE_Registration[] $registrations */
1796
+		$registrations = $this->get_model()->get_all($query);
1797
+		return $registrations;
1798
+	}
1799
+
1800
+	/**
1801
+	 * Return the link to the admin details for the object.
1802
+	 *
1803
+	 * @return string
1804
+	 * @throws EE_Error
1805
+	 */
1806
+	public function get_admin_details_link()
1807
+	{
1808
+		EE_Registry::instance()->load_helper('URL');
1809
+		return EEH_URL::add_query_args_and_nonce(
1810
+			array(
1811
+				'page'    => 'espresso_registrations',
1812
+				'action'  => 'view_registration',
1813
+				'_REG_ID' => $this->ID(),
1814
+			),
1815
+			admin_url('admin.php')
1816
+		);
1817
+	}
1818
+
1819
+	/**
1820
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1821
+	 *
1822
+	 * @return string
1823
+	 * @throws EE_Error
1824
+	 */
1825
+	public function get_admin_edit_link()
1826
+	{
1827
+		return $this->get_admin_details_link();
1828
+	}
1829
+
1830
+	/**
1831
+	 * Returns the link to a settings page for the object.
1832
+	 *
1833
+	 * @return string
1834
+	 * @throws EE_Error
1835
+	 */
1836
+	public function get_admin_settings_link()
1837
+	{
1838
+		return $this->get_admin_details_link();
1839
+	}
1840
+
1841
+	/**
1842
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
1843
+	 *
1844
+	 * @return string
1845
+	 */
1846
+	public function get_admin_overview_link()
1847
+	{
1848
+		EE_Registry::instance()->load_helper('URL');
1849
+		return EEH_URL::add_query_args_and_nonce(
1850
+			array(
1851
+				'page' => 'espresso_registrations',
1852
+			),
1853
+			admin_url('admin.php')
1854
+		);
1855
+	}
1856
+
1857
+
1858
+	/**
1859
+	 * @param array $query_params
1860
+	 *
1861
+	 * @return \EE_Registration[]
1862
+	 * @throws EE_Error
1863
+	 */
1864
+	public function payments($query_params = array())
1865
+	{
1866
+		return $this->get_many_related('Payment', $query_params);
1867
+	}
1868
+
1869
+
1870
+	/**
1871
+	 * @param array $query_params
1872
+	 *
1873
+	 * @return \EE_Registration_Payment[]
1874
+	 * @throws EE_Error
1875
+	 */
1876
+	public function registration_payments($query_params = array())
1877
+	{
1878
+		return $this->get_many_related('Registration_Payment', $query_params);
1879
+	}
1880
+
1881
+
1882
+	/**
1883
+	 * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1884
+	 * Note: if there are no payments on the registration there will be no payment method returned.
1885
+	 *
1886
+	 * @return EE_Payment_Method|null
1887
+	 */
1888
+	public function payment_method()
1889
+	{
1890
+		return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1891
+	}
1892
+
1893
+
1894
+	/**
1895
+	 * @return \EE_Line_Item
1896
+	 * @throws EntityNotFoundException
1897
+	 * @throws EE_Error
1898
+	 */
1899
+	public function ticket_line_item()
1900
+	{
1901
+		$ticket = $this->ticket();
1902
+		$transaction = $this->transaction();
1903
+		$line_item = null;
1904
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1905
+			$transaction->total_line_item(),
1906
+			'Ticket',
1907
+			array($ticket->ID())
1908
+		);
1909
+		foreach ($ticket_line_items as $ticket_line_item) {
1910
+			if ($ticket_line_item instanceof \EE_Line_Item
1911
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
1912
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
1913
+			) {
1914
+				$line_item = $ticket_line_item;
1915
+				break;
1916
+			}
1917
+		}
1918
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1919
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1920
+		}
1921
+		return $line_item;
1922
+	}
1923
+
1924
+
1925
+	/**
1926
+	 * Soft Deletes this model object.
1927
+	 *
1928
+	 * @return boolean | int
1929
+	 * @throws RuntimeException
1930
+	 * @throws EE_Error
1931
+	 */
1932
+	public function delete()
1933
+	{
1934
+		if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1935
+			$this->set_status(EEM_Registration::status_id_cancelled);
1936
+		}
1937
+		return parent::delete();
1938
+	}
1939
+
1940
+
1941
+	/**
1942
+	 * Restores whatever the previous status was on a registration before it was trashed (if possible)
1943
+	 *
1944
+	 * @throws EE_Error
1945
+	 * @throws RuntimeException
1946
+	 */
1947
+	public function restore()
1948
+	{
1949
+		$previous_status = $this->get_extra_meta(
1950
+			EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1951
+			true,
1952
+			EEM_Registration::status_id_cancelled
1953
+		);
1954
+		if ($previous_status) {
1955
+			$this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1956
+			$this->set_status($previous_status);
1957
+		}
1958
+		return parent::restore();
1959
+	}
1960
+
1961
+
1962
+	/**
1963
+	 * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1964
+	 *
1965
+	 * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1966
+	 *                                           depending on whether the reg status changes to or from "Approved"
1967
+	 * @return boolean whether the Registration status was updated
1968
+	 * @throws EE_Error
1969
+	 * @throws RuntimeException
1970
+	 */
1971
+	public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
1972
+	{
1973
+		$paid = $this->paid();
1974
+		$price = $this->final_price();
1975
+		switch (true) {
1976
+			// overpaid or paid
1977
+			case EEH_Money::compare_floats($paid, $price, '>'):
1978
+			case EEH_Money::compare_floats($paid, $price):
1979
+				$new_status = EEM_Registration::status_id_approved;
1980
+				break;
1981
+			//  underpaid
1982
+			case EEH_Money::compare_floats($paid, $price, '<'):
1983
+				$new_status = EEM_Registration::status_id_pending_payment;
1984
+				break;
1985
+			// uhhh Houston...
1986
+			default:
1987
+				throw new RuntimeException(
1988
+					esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
1989
+				);
1990
+		}
1991
+		if ($new_status !== $this->status_ID()) {
1992
+			if ($trigger_set_status_logic) {
1993
+				return $this->set_status($new_status);
1994
+			}
1995
+			parent::set('STS_ID', $new_status);
1996
+			return true;
1997
+		}
1998
+		return false;
1999
+	}
2000
+
2001
+
2002
+	/*************************** DEPRECATED ***************************/
2003
+
2004
+
2005
+	/**
2006
+	 * @deprecated
2007
+	 * @since     4.7.0
2008
+	 * @access    public
2009
+	 */
2010
+	public function price_paid()
2011
+	{
2012
+		EE_Error::doing_it_wrong(
2013
+			'EE_Registration::price_paid()',
2014
+			esc_html__(
2015
+				'This method is deprecated, please use EE_Registration::final_price() instead.',
2016
+				'event_espresso'
2017
+			),
2018
+			'4.7.0'
2019
+		);
2020
+		return $this->final_price();
2021
+	}
2022
+
2023
+
2024
+	/**
2025
+	 * @deprecated
2026
+	 * @since     4.7.0
2027
+	 * @access    public
2028
+	 * @param    float $REG_final_price
2029
+	 * @throws EE_Error
2030
+	 * @throws RuntimeException
2031
+	 */
2032
+	public function set_price_paid($REG_final_price = 0.00)
2033
+	{
2034
+		EE_Error::doing_it_wrong(
2035
+			'EE_Registration::set_price_paid()',
2036
+			esc_html__(
2037
+				'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2038
+				'event_espresso'
2039
+			),
2040
+			'4.7.0'
2041
+		);
2042
+		$this->set_final_price($REG_final_price);
2043
+	}
2044
+
2045
+
2046
+	/**
2047
+	 * @deprecated
2048
+	 * @since 4.7.0
2049
+	 * @return string
2050
+	 * @throws EE_Error
2051
+	 */
2052
+	public function pretty_price_paid()
2053
+	{
2054
+		EE_Error::doing_it_wrong(
2055
+			'EE_Registration::pretty_price_paid()',
2056
+			esc_html__(
2057
+				'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2058
+				'event_espresso'
2059
+			),
2060
+			'4.7.0'
2061
+		);
2062
+		return $this->pretty_final_price();
2063
+	}
2064
+
2065
+
2066
+	/**
2067
+	 * Gets the primary datetime related to this registration via the related Event to this registration
2068
+	 *
2069
+	 * @deprecated 4.9.17
2070
+	 * @return EE_Datetime
2071
+	 * @throws EE_Error
2072
+	 * @throws EntityNotFoundException
2073
+	 */
2074
+	public function get_related_primary_datetime()
2075
+	{
2076
+		EE_Error::doing_it_wrong(
2077
+			__METHOD__,
2078
+			esc_html__(
2079
+				'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2080
+				'event_espresso'
2081
+			),
2082
+			'4.9.17',
2083
+			'5.0.0'
2084
+		);
2085
+		return $this->event()->primary_datetime();
2086
+	}
2087 2087
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
     {
120 120
         switch ($field_name) {
121 121
             case 'REG_code':
122
-                if (! empty($field_value) && $this->reg_code() === null) {
122
+                if ( ! empty($field_value) && $this->reg_code() === null) {
123 123
                     $this->set_reg_code($field_value, $use_default);
124 124
                 }
125 125
                 break;
@@ -396,7 +396,7 @@  discard block
 block discarded – undo
396 396
     public function event()
397 397
     {
398 398
         $event = $this->get_first_related('Event');
399
-        if (! $event instanceof \EE_Event) {
399
+        if ( ! $event instanceof \EE_Event) {
400 400
             throw new EntityNotFoundException('Event ID', $this->event_ID());
401 401
         }
402 402
         return $event;
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
     {
440 440
         // reserved ticket and datetime counts will be decremented as sold counts are incremented
441 441
         // so stop tracking that this reg has a ticket reserved
442
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
442
+        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:".__LINE__.')');
443 443
         $ticket = $this->ticket();
444 444
         $ticket->increase_sold();
445 445
         $ticket->save();
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
                 && $update_ticket
496 496
             ) {
497 497
                 $ticket = $this->ticket();
498
-                $ticket->increase_reserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
498
+                $ticket->increase_reserved(1, "REG: {$this->ID()} (ln:".__LINE__.')');
499 499
                 $ticket->save();
500 500
             }
501 501
         }
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
                 && $update_ticket
527 527
             ) {
528 528
                 $ticket = $this->ticket();
529
-                $ticket->decrease_reserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
529
+                $ticket->decrease_reserved(1, true, "REG: {$this->ID()} (ln:".__LINE__.')');
530 530
                 $ticket->save();
531 531
             }
532 532
         }
@@ -1201,7 +1201,7 @@  discard block
 block discarded – undo
1201 1201
                     : '';
1202 1202
                 break;
1203 1203
         }
1204
-        return $icon . $status[ $this->status_ID() ];
1204
+        return $icon.$status[$this->status_ID()];
1205 1205
     }
1206 1206
 
1207 1207
 
@@ -1419,7 +1419,7 @@  discard block
 block discarded – undo
1419 1419
             return false;
1420 1420
         }
1421 1421
         // is there a datetime ticket that matches this dtt_ID?
1422
-        if (! (EEM_Datetime_Ticket::instance()->exists(
1422
+        if ( ! (EEM_Datetime_Ticket::instance()->exists(
1423 1423
             array(
1424 1424
                 array(
1425 1425
                     'TKT_ID' => $this->get('TKT_ID'),
@@ -1450,7 +1450,7 @@  discard block
 block discarded – undo
1450 1450
     {
1451 1451
         $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1452 1452
 
1453
-        if (! $DTT_ID) {
1453
+        if ( ! $DTT_ID) {
1454 1454
             return false;
1455 1455
         }
1456 1456
 
@@ -1458,7 +1458,7 @@  discard block
 block discarded – undo
1458 1458
 
1459 1459
         // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1460 1460
         // check-in or not.
1461
-        if (! $max_uses || $max_uses === EE_INF) {
1461
+        if ( ! $max_uses || $max_uses === EE_INF) {
1462 1462
             return true;
1463 1463
         }
1464 1464
 
@@ -1518,7 +1518,7 @@  discard block
 block discarded – undo
1518 1518
             $datetime = $this->get_latest_related_datetime();
1519 1519
             $DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1520 1520
             // verify the registration can checkin for the given DTT_ID
1521
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1521
+        } elseif ( ! $this->can_checkin($DTT_ID, $verify)) {
1522 1522
             EE_Error::add_error(
1523 1523
                 sprintf(
1524 1524
                     esc_html__(
@@ -1541,7 +1541,7 @@  discard block
 block discarded – undo
1541 1541
         );
1542 1542
         // start by getting the current status so we know what status we'll be changing to.
1543 1543
         $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1544
-        $status_to = $status_paths[ $cur_status ];
1544
+        $status_to = $status_paths[$cur_status];
1545 1545
         // database only records true for checked IN or false for checked OUT
1546 1546
         // no record ( null ) means checked in NEVER, but we obviously don't save that
1547 1547
         $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
@@ -1706,7 +1706,7 @@  discard block
 block discarded – undo
1706 1706
     public function transaction()
1707 1707
     {
1708 1708
         $transaction = $this->get_first_related('Transaction');
1709
-        if (! $transaction instanceof \EE_Transaction) {
1709
+        if ( ! $transaction instanceof \EE_Transaction) {
1710 1710
             throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1711 1711
         }
1712 1712
         return $transaction;
@@ -1760,11 +1760,11 @@  discard block
 block discarded – undo
1760 1760
             );
1761 1761
             return;
1762 1762
         }
1763
-        if (! $this->reg_code()) {
1763
+        if ( ! $this->reg_code()) {
1764 1764
             parent::set('REG_code', $REG_code, $use_default);
1765 1765
         } else {
1766 1766
             EE_Error::doing_it_wrong(
1767
-                __CLASS__ . '::' . __FUNCTION__,
1767
+                __CLASS__.'::'.__FUNCTION__,
1768 1768
                 esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1769 1769
                 '4.6.0'
1770 1770
             );
@@ -1915,7 +1915,7 @@  discard block
 block discarded – undo
1915 1915
                 break;
1916 1916
             }
1917 1917
         }
1918
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1918
+        if ( ! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1919 1919
             throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1920 1920
         }
1921 1921
         return $line_item;
Please login to merge, or discard this patch.
reg_steps/payment_options/EE_SPCO_Reg_Step_Payment_Options.class.php 3 patches
Doc Comments   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 
146 146
 
147 147
     /**
148
-     * @return null
148
+     * @return EE_Line_Item_Display
149 149
      */
150 150
     public function line_item_display()
151 151
     {
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 
155 155
 
156 156
     /**
157
-     * @param null $line_item_display
157
+     * @param EE_Line_Item_Display $line_item_display
158 158
      */
159 159
     public function set_line_item_display($line_item_display)
160 160
     {
@@ -882,7 +882,7 @@  discard block
 block discarded – undo
882 882
      *    _apply_registration_payments_to_amount_owing
883 883
      *
884 884
      * @access protected
885
-     * @param array $registrations
885
+     * @param EE_Base_Class[] $registrations
886 886
      * @throws EE_Error
887 887
      */
888 888
     protected function _apply_registration_payments_to_amount_owing(array $registrations)
@@ -1188,7 +1188,7 @@  discard block
 block discarded – undo
1188 1188
      * get_billing_form_html_for_payment_method
1189 1189
      *
1190 1190
      * @access public
1191
-     * @return string
1191
+     * @return boolean
1192 1192
      * @throws EE_Error
1193 1193
      * @throws InvalidArgumentException
1194 1194
      * @throws ReflectionException
@@ -1255,7 +1255,7 @@  discard block
 block discarded – undo
1255 1255
      *
1256 1256
      * @access private
1257 1257
      * @param EE_Payment_Method $payment_method
1258
-     * @return EE_Billing_Info_Form|EE_Form_Section_HTML
1258
+     * @return EE_Billing_Info_Form
1259 1259
      * @throws EE_Error
1260 1260
      * @throws InvalidArgumentException
1261 1261
      * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
@@ -1364,7 +1364,7 @@  discard block
 block discarded – undo
1364 1364
      * switch_payment_method
1365 1365
      *
1366 1366
      * @access public
1367
-     * @return string
1367
+     * @return boolean
1368 1368
      * @throws EE_Error
1369 1369
      * @throws InvalidArgumentException
1370 1370
      * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
@@ -1643,7 +1643,7 @@  discard block
 block discarded – undo
1643 1643
     /**
1644 1644
      * process_reg_step
1645 1645
      *
1646
-     * @return bool
1646
+     * @return null|boolean
1647 1647
      * @throws EE_Error
1648 1648
      * @throws InvalidArgumentException
1649 1649
      * @throws ReflectionException
@@ -1774,7 +1774,7 @@  discard block
 block discarded – undo
1774 1774
      *    update_reg_step
1775 1775
      *    this is the final step after a user  revisits the site to retry a payment
1776 1776
      *
1777
-     * @return bool
1777
+     * @return null|boolean
1778 1778
      * @throws EE_Error
1779 1779
      * @throws InvalidArgumentException
1780 1780
      * @throws ReflectionException
@@ -2221,7 +2221,7 @@  discard block
 block discarded – undo
2221 2221
      *
2222 2222
      * @access    private
2223 2223
      * @type    EE_Payment_Method $payment_method
2224
-     * @return mixed EE_Payment | boolean
2224
+     * @return EE_Payment|null EE_Payment | boolean
2225 2225
      * @throws EE_Error
2226 2226
      * @throws InvalidArgumentException
2227 2227
      * @throws ReflectionException
@@ -2546,7 +2546,7 @@  discard block
 block discarded – undo
2546 2546
      *        or present the payment options again
2547 2547
      *
2548 2548
      * @access private
2549
-     * @return EE_Payment|FALSE
2549
+     * @return boolean
2550 2550
      * @throws EE_Error
2551 2551
      * @throws InvalidArgumentException
2552 2552
      * @throws ReflectionException
@@ -2686,8 +2686,8 @@  discard block
 block discarded – undo
2686 2686
      * _redirect_wayward_request
2687 2687
      *
2688 2688
      * @access private
2689
-     * @param \EE_Registration|null $primary_registrant
2690
-     * @return bool
2689
+     * @param EE_Registration $primary_registrant
2690
+     * @return false|null
2691 2691
      * @throws EE_Error
2692 2692
      * @throws InvalidArgumentException
2693 2693
      * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
Please login to merge, or discard this patch.
Indentation   +2885 added lines, -2885 removed lines patch added patch discarded remove patch
@@ -12,2889 +12,2889 @@
 block discarded – undo
12 12
 class EE_SPCO_Reg_Step_Payment_Options extends EE_SPCO_Reg_Step
13 13
 {
14 14
 
15
-    /**
16
-     * @access protected
17
-     * @var EE_Line_Item_Display $Line_Item_Display
18
-     */
19
-    protected $line_item_display;
20
-
21
-    /**
22
-     * @access protected
23
-     * @var boolean $handle_IPN_in_this_request
24
-     */
25
-    protected $handle_IPN_in_this_request = false;
26
-
27
-
28
-    /**
29
-     *    set_hooks - for hooking into EE Core, other modules, etc
30
-     *
31
-     * @access    public
32
-     * @return    void
33
-     */
34
-    public static function set_hooks()
35
-    {
36
-        add_filter(
37
-            'FHEE__SPCO__EE_Line_Item_Filter_Collection',
38
-            array('EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters')
39
-        );
40
-        add_action(
41
-            'wp_ajax_switch_spco_billing_form',
42
-            array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
43
-        );
44
-        add_action(
45
-            'wp_ajax_nopriv_switch_spco_billing_form',
46
-            array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
47
-        );
48
-        add_action('wp_ajax_save_payer_details', array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details'));
49
-        add_action(
50
-            'wp_ajax_nopriv_save_payer_details',
51
-            array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details')
52
-        );
53
-        add_action(
54
-            'wp_ajax_get_transaction_details_for_gateways',
55
-            array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
56
-        );
57
-        add_action(
58
-            'wp_ajax_nopriv_get_transaction_details_for_gateways',
59
-            array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
60
-        );
61
-        add_filter(
62
-            'FHEE__EED_Recaptcha___bypass_recaptcha__bypass_request_params_array',
63
-            array('EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method'),
64
-            10,
65
-            1
66
-        );
67
-    }
68
-
69
-
70
-    /**
71
-     *    ajax switch_spco_billing_form
72
-     *
73
-     * @throws \EE_Error
74
-     */
75
-    public static function switch_spco_billing_form()
76
-    {
77
-        EED_Single_Page_Checkout::process_ajax_request('switch_payment_method');
78
-    }
79
-
80
-
81
-    /**
82
-     *    ajax save_payer_details
83
-     *
84
-     * @throws \EE_Error
85
-     */
86
-    public static function save_payer_details()
87
-    {
88
-        EED_Single_Page_Checkout::process_ajax_request('save_payer_details_via_ajax');
89
-    }
90
-
91
-
92
-    /**
93
-     *    ajax get_transaction_details
94
-     *
95
-     * @throws \EE_Error
96
-     */
97
-    public static function get_transaction_details()
98
-    {
99
-        EED_Single_Page_Checkout::process_ajax_request('get_transaction_details_for_gateways');
100
-    }
101
-
102
-
103
-    /**
104
-     * bypass_recaptcha_for_load_payment_method
105
-     *
106
-     * @access public
107
-     * @return array
108
-     * @throws InvalidArgumentException
109
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
110
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
111
-     */
112
-    public static function bypass_recaptcha_for_load_payment_method()
113
-    {
114
-        return array(
115
-            'EESID'  => EE_Registry::instance()->SSN->id(),
116
-            'step'   => 'payment_options',
117
-            'action' => 'spco_billing_form',
118
-        );
119
-    }
120
-
121
-
122
-    /**
123
-     *    class constructor
124
-     *
125
-     * @access    public
126
-     * @param    EE_Checkout $checkout
127
-     */
128
-    public function __construct(EE_Checkout $checkout)
129
-    {
130
-        $this->_slug = 'payment_options';
131
-        $this->_name = esc_html__('Payment Options', 'event_espresso');
132
-        $this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
133
-        $this->checkout = $checkout;
134
-        $this->_reset_success_message();
135
-        $this->set_instructions(
136
-            esc_html__(
137
-                'Please select a method of payment and provide any necessary billing information before proceeding.',
138
-                'event_espresso'
139
-            )
140
-        );
141
-    }
142
-
143
-
144
-    /**
145
-     * @return null
146
-     */
147
-    public function line_item_display()
148
-    {
149
-        return $this->line_item_display;
150
-    }
151
-
152
-
153
-    /**
154
-     * @param null $line_item_display
155
-     */
156
-    public function set_line_item_display($line_item_display)
157
-    {
158
-        $this->line_item_display = $line_item_display;
159
-    }
160
-
161
-
162
-    /**
163
-     * @return boolean
164
-     */
165
-    public function handle_IPN_in_this_request()
166
-    {
167
-        return $this->handle_IPN_in_this_request;
168
-    }
169
-
170
-
171
-    /**
172
-     * @param boolean $handle_IPN_in_this_request
173
-     */
174
-    public function set_handle_IPN_in_this_request($handle_IPN_in_this_request)
175
-    {
176
-        $this->handle_IPN_in_this_request = filter_var($handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN);
177
-    }
178
-
179
-
180
-    /**
181
-     * translate_js_strings
182
-     *
183
-     * @return void
184
-     */
185
-    public function translate_js_strings()
186
-    {
187
-        EE_Registry::$i18n_js_strings['no_payment_method'] = esc_html__(
188
-            'Please select a method of payment in order to continue.',
189
-            'event_espresso'
190
-        );
191
-        EE_Registry::$i18n_js_strings['invalid_payment_method'] = esc_html__(
192
-            'A valid method of payment could not be determined. Please refresh the page and try again.',
193
-            'event_espresso'
194
-        );
195
-        EE_Registry::$i18n_js_strings['forwarding_to_offsite'] = esc_html__(
196
-            'Forwarding to Secure Payment Provider.',
197
-            'event_espresso'
198
-        );
199
-    }
200
-
201
-
202
-    /**
203
-     * enqueue_styles_and_scripts
204
-     *
205
-     * @return void
206
-     * @throws EE_Error
207
-     * @throws InvalidArgumentException
208
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
209
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
210
-     */
211
-    public function enqueue_styles_and_scripts()
212
-    {
213
-        $transaction = $this->checkout->transaction;
214
-        // if the transaction isn't set or nothing is owed on it, don't enqueue any JS
215
-        if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
216
-            return;
217
-        }
218
-        foreach (EEM_Payment_Method::instance()->get_all_for_transaction(
219
-            $transaction,
220
-            EEM_Payment_Method::scope_cart
221
-        ) as $payment_method) {
222
-            $type_obj = $payment_method->type_obj();
223
-            if ($type_obj instanceof EE_PMT_Base) {
224
-                $billing_form = $type_obj->generate_new_billing_form($transaction);
225
-                if ($billing_form instanceof EE_Form_Section_Proper) {
226
-                    $billing_form->enqueue_js();
227
-                }
228
-            }
229
-        }
230
-    }
231
-
232
-
233
-    /**
234
-     * initialize_reg_step
235
-     *
236
-     * @return bool
237
-     * @throws EE_Error
238
-     * @throws InvalidArgumentException
239
-     * @throws ReflectionException
240
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
241
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
242
-     */
243
-    public function initialize_reg_step()
244
-    {
245
-        // TODO: if /when we implement donations, then this will need overriding
246
-        if (// don't need payment options for:
247
-            // registrations made via the admin
248
-            // completed transactions
249
-            // overpaid transactions
250
-            // $ 0.00 transactions(no payment required)
251
-            ! $this->checkout->payment_required()
252
-            // but do NOT remove if current action being called belongs to this reg step
253
-            && ! is_callable(array($this, $this->checkout->action))
254
-            && ! $this->completed()
255
-        ) {
256
-            // and if so, then we no longer need the Payment Options step
257
-            if ($this->is_current_step()) {
258
-                $this->checkout->generate_reg_form = false;
259
-            }
260
-            $this->checkout->remove_reg_step($this->_slug);
261
-            // DEBUG LOG
262
-            // $this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
263
-            return false;
264
-        }
265
-        // load EEM_Payment_Method
266
-        EE_Registry::instance()->load_model('Payment_Method');
267
-        // get all active payment methods
268
-        $this->checkout->available_payment_methods = EEM_Payment_Method::instance()->get_all_for_transaction(
269
-            $this->checkout->transaction,
270
-            EEM_Payment_Method::scope_cart
271
-        );
272
-        return true;
273
-    }
274
-
275
-
276
-    /**
277
-     * @return EE_Form_Section_Proper
278
-     * @throws EE_Error
279
-     * @throws InvalidArgumentException
280
-     * @throws ReflectionException
281
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
282
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
283
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
284
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
285
-     */
286
-    public function generate_reg_form()
287
-    {
288
-        // reset in case someone changes their mind
289
-        $this->_reset_selected_method_of_payment();
290
-        // set some defaults
291
-        $this->checkout->selected_method_of_payment = 'payments_closed';
292
-        $registrations_requiring_payment = array();
293
-        $registrations_for_free_events = array();
294
-        $registrations_requiring_pre_approval = array();
295
-        $sold_out_events = array();
296
-        $insufficient_spaces_available = array();
297
-        $no_payment_required = true;
298
-        // loop thru registrations to gather info
299
-        $registrations = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
300
-        $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
301
-            $registrations,
302
-            $this->checkout->revisit
303
-        );
304
-        foreach ($registrations as $REG_ID => $registration) {
305
-            /** @var $registration EE_Registration */
306
-            // has this registration lost it's space ?
307
-            if (isset($ejected_registrations[ $REG_ID ])) {
308
-                if ($registration->event()->is_sold_out() || $registration->event()->is_sold_out(true)) {
309
-                    $sold_out_events[ $registration->event()->ID() ] = $registration->event();
310
-                } else {
311
-                    $insufficient_spaces_available[ $registration->event()->ID() ] = $registration->event();
312
-                }
313
-                continue;
314
-            }
315
-            // event requires admin approval
316
-            if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
317
-                // add event to list of events with pre-approval reg status
318
-                $registrations_requiring_pre_approval[ $REG_ID ] = $registration;
319
-                do_action(
320
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
321
-                    $registration->event(),
322
-                    $this
323
-                );
324
-                continue;
325
-            }
326
-            if ($this->checkout->revisit
327
-                && $registration->status_ID() !== EEM_Registration::status_id_approved
328
-                && (
329
-                    $registration->event()->is_sold_out()
330
-                    || $registration->event()->is_sold_out(true)
331
-                )
332
-            ) {
333
-                // add event to list of events that are sold out
334
-                $sold_out_events[ $registration->event()->ID() ] = $registration->event();
335
-                do_action(
336
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
337
-                    $registration->event(),
338
-                    $this
339
-                );
340
-                continue;
341
-            }
342
-            // are they allowed to pay now and is there monies owing?
343
-            if ($registration->owes_monies_and_can_pay()) {
344
-                $registrations_requiring_payment[ $REG_ID ] = $registration;
345
-                do_action(
346
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
347
-                    $registration->event(),
348
-                    $this
349
-                );
350
-            } elseif (! $this->checkout->revisit
351
-                      && $registration->status_ID() !== EEM_Registration::status_id_not_approved
352
-                      && $registration->ticket()->is_free()
353
-            ) {
354
-                $registrations_for_free_events[ $registration->event()->ID() ] = $registration;
355
-            }
356
-        }
357
-        $subsections = array();
358
-        // now decide which template to load
359
-        if (! empty($sold_out_events)) {
360
-            $subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
361
-        }
362
-        if (! empty($insufficient_spaces_available)) {
363
-            $subsections['insufficient_space'] = $this->_insufficient_spaces_available(
364
-                $insufficient_spaces_available
365
-            );
366
-        }
367
-        if (! empty($registrations_requiring_pre_approval)) {
368
-            $subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
369
-                $registrations_requiring_pre_approval
370
-            );
371
-        }
372
-        if (! empty($registrations_for_free_events)) {
373
-            $subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
374
-        }
375
-        if (! empty($registrations_requiring_payment)) {
376
-            if ($this->checkout->amount_owing > 0) {
377
-                // autoload Line_Item_Display classes
378
-                EEH_Autoloader::register_line_item_filter_autoloaders();
379
-                $line_item_filter_processor = new EE_Line_Item_Filter_Processor(
380
-                    apply_filters(
381
-                        'FHEE__SPCO__EE_Line_Item_Filter_Collection',
382
-                        new EE_Line_Item_Filter_Collection()
383
-                    ),
384
-                    $this->checkout->cart->get_grand_total()
385
-                );
386
-                /** @var EE_Line_Item $filtered_line_item_tree */
387
-                $filtered_line_item_tree = $line_item_filter_processor->process();
388
-                EEH_Autoloader::register_line_item_display_autoloaders();
389
-                $this->set_line_item_display(new EE_Line_Item_Display('spco'));
390
-                $subsections['payment_options'] = $this->_display_payment_options(
391
-                    $this->line_item_display->display_line_item(
392
-                        $filtered_line_item_tree,
393
-                        array('registrations' => $registrations)
394
-                    )
395
-                );
396
-                $this->checkout->amount_owing = $filtered_line_item_tree->total();
397
-                $this->_apply_registration_payments_to_amount_owing($registrations);
398
-            }
399
-            $no_payment_required = false;
400
-        } else {
401
-            $this->_hide_reg_step_submit_button_if_revisit();
402
-        }
403
-        $this->_save_selected_method_of_payment();
404
-
405
-        $subsections['default_hidden_inputs'] = $this->reg_step_hidden_inputs();
406
-        $subsections['extra_hidden_inputs'] = $this->_extra_hidden_inputs($no_payment_required);
407
-
408
-        return new EE_Form_Section_Proper(
409
-            array(
410
-                'name'            => $this->reg_form_name(),
411
-                'html_id'         => $this->reg_form_name(),
412
-                'subsections'     => $subsections,
413
-                'layout_strategy' => new EE_No_Layout(),
414
-            )
415
-        );
416
-    }
417
-
418
-
419
-    /**
420
-     * add line item filters required for this reg step
421
-     * these filters are applied via this line in EE_SPCO_Reg_Step_Payment_Options::set_hooks():
422
-     *        add_filter( 'FHEE__SPCO__EE_Line_Item_Filter_Collection', array( 'EE_SPCO_Reg_Step_Payment_Options',
423
-     *        'add_spco_line_item_filters' ) ); so any code that wants to use the same set of filters during the
424
-     *        payment options reg step, can apply these filters via the following: apply_filters(
425
-     *        'FHEE__SPCO__EE_Line_Item_Filter_Collection', new EE_Line_Item_Filter_Collection() ) or to an existing
426
-     *        filter collection by passing that instead of instantiating a new collection
427
-     *
428
-     * @param \EE_Line_Item_Filter_Collection $line_item_filter_collection
429
-     * @return EE_Line_Item_Filter_Collection
430
-     * @throws EE_Error
431
-     * @throws InvalidArgumentException
432
-     * @throws ReflectionException
433
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
434
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
435
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
436
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
437
-     */
438
-    public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
439
-    {
440
-        if (! EE_Registry::instance()->SSN instanceof EE_Session) {
441
-            return $line_item_filter_collection;
442
-        }
443
-        if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
444
-            return $line_item_filter_collection;
445
-        }
446
-        if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
447
-            return $line_item_filter_collection;
448
-        }
449
-        $line_item_filter_collection->add(
450
-            new EE_Billable_Line_Item_Filter(
451
-                EE_SPCO_Reg_Step_Payment_Options::remove_ejected_registrations(
452
-                    EE_Registry::instance()->SSN->checkout()->transaction->registrations(
453
-                        EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
454
-                    )
455
-                )
456
-            )
457
-        );
458
-        $line_item_filter_collection->add(new EE_Non_Zero_Line_Item_Filter());
459
-        return $line_item_filter_collection;
460
-    }
461
-
462
-
463
-    /**
464
-     * remove_ejected_registrations
465
-     * if a registrant has lost their potential space at an event due to lack of payment,
466
-     * then this method removes them from the list of registrations being paid for during this request
467
-     *
468
-     * @param \EE_Registration[] $registrations
469
-     * @return EE_Registration[]
470
-     * @throws EE_Error
471
-     * @throws InvalidArgumentException
472
-     * @throws ReflectionException
473
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
474
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
475
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
476
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
477
-     */
478
-    public static function remove_ejected_registrations(array $registrations)
479
-    {
480
-        $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
481
-            $registrations,
482
-            EE_Registry::instance()->SSN->checkout()->revisit
483
-        );
484
-        foreach ($registrations as $REG_ID => $registration) {
485
-            // has this registration lost it's space ?
486
-            if (isset($ejected_registrations[ $REG_ID ])) {
487
-                unset($registrations[ $REG_ID ]);
488
-                continue;
489
-            }
490
-        }
491
-        return $registrations;
492
-    }
493
-
494
-
495
-    /**
496
-     * find_registrations_that_lost_their_space
497
-     * If a registrant chooses an offline payment method like Invoice,
498
-     * then no space is reserved for them at the event until they fully pay fo that site
499
-     * (unless the event's default reg status is set to APPROVED)
500
-     * if a registrant then later returns to pay, but the number of spaces available has been reduced due to sales,
501
-     * then this method will determine which registrations have lost the ability to complete the reg process.
502
-     *
503
-     * @param \EE_Registration[] $registrations
504
-     * @param bool               $revisit
505
-     * @return array
506
-     * @throws EE_Error
507
-     * @throws InvalidArgumentException
508
-     * @throws ReflectionException
509
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
510
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
511
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
512
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
513
-     */
514
-    public static function find_registrations_that_lost_their_space(array $registrations, $revisit = false)
515
-    {
516
-        // registrations per event
517
-        $event_reg_count = array();
518
-        // spaces left per event
519
-        $event_spaces_remaining = array();
520
-        // tickets left sorted by ID
521
-        $tickets_remaining = array();
522
-        // registrations that have lost their space
523
-        $ejected_registrations = array();
524
-        foreach ($registrations as $REG_ID => $registration) {
525
-            if ($registration->status_ID() === EEM_Registration::status_id_approved
526
-                || apply_filters(
527
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__find_registrations_that_lost_their_space__allow_reg_payment',
528
-                    false,
529
-                    $registration,
530
-                    $revisit
531
-                )
532
-            ) {
533
-                continue;
534
-            }
535
-            $EVT_ID = $registration->event_ID();
536
-            $ticket = $registration->ticket();
537
-            if (! isset($tickets_remaining[ $ticket->ID() ])) {
538
-                $tickets_remaining[ $ticket->ID() ] = $ticket->remaining();
539
-            }
540
-            if ($tickets_remaining[ $ticket->ID() ] > 0) {
541
-                if (! isset($event_reg_count[ $EVT_ID ])) {
542
-                    $event_reg_count[ $EVT_ID ] = 0;
543
-                }
544
-                $event_reg_count[ $EVT_ID ]++;
545
-                if (! isset($event_spaces_remaining[ $EVT_ID ])) {
546
-                    $event_spaces_remaining[ $EVT_ID ] = $registration->event()->spaces_remaining_for_sale();
547
-                }
548
-            }
549
-            if ($revisit
550
-                && ($tickets_remaining[ $ticket->ID() ] === 0
551
-                    || $event_reg_count[ $EVT_ID ] > $event_spaces_remaining[ $EVT_ID ]
552
-                )
553
-            ) {
554
-                $ejected_registrations[ $REG_ID ] = $registration->event();
555
-                if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
556
-                    /** @type EE_Registration_Processor $registration_processor */
557
-                    $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
558
-                    // at this point, we should have enough details about the registrant to consider the registration
559
-                    // NOT incomplete
560
-                    $registration_processor->manually_update_registration_status(
561
-                        $registration,
562
-                        EEM_Registration::status_id_wait_list
563
-                    );
564
-                }
565
-            }
566
-        }
567
-        return $ejected_registrations;
568
-    }
569
-
570
-
571
-    /**
572
-     * _hide_reg_step_submit_button
573
-     * removes the html for the reg step submit button
574
-     * by replacing it with an empty string via filter callback
575
-     *
576
-     * @return void
577
-     */
578
-    protected function _adjust_registration_status_if_event_old_sold()
579
-    {
580
-    }
581
-
582
-
583
-    /**
584
-     * _hide_reg_step_submit_button
585
-     * removes the html for the reg step submit button
586
-     * by replacing it with an empty string via filter callback
587
-     *
588
-     * @return void
589
-     */
590
-    protected function _hide_reg_step_submit_button_if_revisit()
591
-    {
592
-        if ($this->checkout->revisit) {
593
-            add_filter('FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string');
594
-        }
595
-    }
596
-
597
-
598
-    /**
599
-     * sold_out_events
600
-     * displays notices regarding events that have sold out since hte registrant first signed up
601
-     *
602
-     * @param \EE_Event[] $sold_out_events_array
603
-     * @return \EE_Form_Section_Proper
604
-     * @throws \EE_Error
605
-     */
606
-    private function _sold_out_events($sold_out_events_array = array())
607
-    {
608
-        // set some defaults
609
-        $this->checkout->selected_method_of_payment = 'events_sold_out';
610
-        $sold_out_events = '';
611
-        foreach ($sold_out_events_array as $sold_out_event) {
612
-            $sold_out_events .= EEH_HTML::li(
613
-                EEH_HTML::span(
614
-                    '  ' . $sold_out_event->name(),
615
-                    '',
616
-                    'dashicons dashicons-marker ee-icon-size-16 pink-text'
617
-                )
618
-            );
619
-        }
620
-        return new EE_Form_Section_Proper(
621
-            array(
622
-                'layout_strategy' => new EE_Template_Layout(
623
-                    array(
624
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
625
-                                                  . $this->_slug
626
-                                                  . DS
627
-                                                  . 'sold_out_events.template.php',
628
-                        'template_args'        => apply_filters(
629
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
630
-                            array(
631
-                                'sold_out_events'     => $sold_out_events,
632
-                                'sold_out_events_msg' => apply_filters(
633
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__sold_out_events_msg',
634
-                                    sprintf(
635
-                                        esc_html__(
636
-                                            'It appears that the event you were about to make a payment for has sold out since you first registered. If you have already made a partial payment towards this event, please contact the event administrator for a refund.%3$s%3$s%1$sPlease note that availability can change at any time due to cancellations, so please check back again later if registration for this event(s) is important to you.%2$s',
637
-                                            'event_espresso'
638
-                                        ),
639
-                                        '<strong>',
640
-                                        '</strong>',
641
-                                        '<br />'
642
-                                    )
643
-                                ),
644
-                            )
645
-                        ),
646
-                    )
647
-                ),
648
-            )
649
-        );
650
-    }
651
-
652
-
653
-    /**
654
-     * _insufficient_spaces_available
655
-     * displays notices regarding events that do not have enough remaining spaces
656
-     * to satisfy the current number of registrations looking to pay
657
-     *
658
-     * @param \EE_Event[] $insufficient_spaces_events_array
659
-     * @return \EE_Form_Section_Proper
660
-     * @throws \EE_Error
661
-     */
662
-    private function _insufficient_spaces_available($insufficient_spaces_events_array = array())
663
-    {
664
-        // set some defaults
665
-        $this->checkout->selected_method_of_payment = 'invoice';
666
-        $insufficient_space_events = '';
667
-        foreach ($insufficient_spaces_events_array as $event) {
668
-            if ($event instanceof EE_Event) {
669
-                $insufficient_space_events .= EEH_HTML::li(
670
-                    EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
671
-                );
672
-            }
673
-        }
674
-        return new EE_Form_Section_Proper(
675
-            array(
676
-                'subsections'     => array(
677
-                    'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
678
-                    'extra_hidden_inputs'   => $this->_extra_hidden_inputs(),
679
-                ),
680
-                'layout_strategy' => new EE_Template_Layout(
681
-                    array(
682
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
683
-                                                  . $this->_slug
684
-                                                  . DS
685
-                                                  . 'sold_out_events.template.php',
686
-                        'template_args'        => apply_filters(
687
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__template_args',
688
-                            array(
689
-                                'sold_out_events'     => $insufficient_space_events,
690
-                                'sold_out_events_msg' => apply_filters(
691
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__insufficient_space_msg',
692
-                                    esc_html__(
693
-                                        'It appears that the event you were about to make a payment for has sold additional tickets since you first registered, and there are no longer enough spaces left to accommodate your selections. You may continue to pay and secure the available space(s) remaining, or simply cancel if you no longer wish to purchase. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
694
-                                        'event_espresso'
695
-                                    )
696
-                                ),
697
-                            )
698
-                        ),
699
-                    )
700
-                ),
701
-            )
702
-        );
703
-    }
704
-
705
-
706
-    /**
707
-     * registrations_requiring_pre_approval
708
-     *
709
-     * @param array $registrations_requiring_pre_approval
710
-     * @return EE_Form_Section_Proper
711
-     * @throws EE_Error
712
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
713
-     */
714
-    private function _registrations_requiring_pre_approval($registrations_requiring_pre_approval = array())
715
-    {
716
-        $events_requiring_pre_approval = '';
717
-        foreach ($registrations_requiring_pre_approval as $registration) {
718
-            if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
719
-                $events_requiring_pre_approval[ $registration->event()->ID() ] = EEH_HTML::li(
720
-                    EEH_HTML::span(
721
-                        '',
722
-                        '',
723
-                        'dashicons dashicons-marker ee-icon-size-16 orange-text'
724
-                    )
725
-                    . EEH_HTML::span($registration->event()->name(), '', 'orange-text')
726
-                );
727
-            }
728
-        }
729
-        return new EE_Form_Section_Proper(
730
-            array(
731
-                'layout_strategy' => new EE_Template_Layout(
732
-                    array(
733
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
734
-                                                  . $this->_slug
735
-                                                  . DS
736
-                                                  . 'events_requiring_pre_approval.template.php', // layout_template
737
-                        'template_args'        => apply_filters(
738
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
739
-                            array(
740
-                                'events_requiring_pre_approval'     => implode('', $events_requiring_pre_approval),
741
-                                'events_requiring_pre_approval_msg' => apply_filters(
742
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___events_requiring_pre_approval__events_requiring_pre_approval_msg',
743
-                                    esc_html__(
744
-                                        'The following events do not require payment at this time and will not be billed during this transaction. Billing will only occur after the attendee has been approved by the event organizer. You will be notified when your registration has been processed. If this is a free event, then no billing will occur.',
745
-                                        'event_espresso'
746
-                                    )
747
-                                ),
748
-                            )
749
-                        ),
750
-                    )
751
-                ),
752
-            )
753
-        );
754
-    }
755
-
756
-
757
-    /**
758
-     * _no_payment_required
759
-     *
760
-     * @param \EE_Event[] $registrations_for_free_events
761
-     * @return \EE_Form_Section_Proper
762
-     * @throws \EE_Error
763
-     */
764
-    private function _no_payment_required($registrations_for_free_events = array())
765
-    {
766
-        // set some defaults
767
-        $this->checkout->selected_method_of_payment = 'no_payment_required';
768
-        // generate no_payment_required form
769
-        return new EE_Form_Section_Proper(
770
-            array(
771
-                'layout_strategy' => new EE_Template_Layout(
772
-                    array(
773
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
774
-                                                  . $this->_slug
775
-                                                  . DS
776
-                                                  . 'no_payment_required.template.php', // layout_template
777
-                        'template_args'        => apply_filters(
778
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___no_payment_required__template_args',
779
-                            array(
780
-                                'revisit'                       => $this->checkout->revisit,
781
-                                'registrations'                 => array(),
782
-                                'ticket_count'                  => array(),
783
-                                'registrations_for_free_events' => $registrations_for_free_events,
784
-                                'no_payment_required_msg'       => EEH_HTML::p(
785
-                                    esc_html__('This is a free event, so no billing will occur.', 'event_espresso')
786
-                                ),
787
-                            )
788
-                        ),
789
-                    )
790
-                ),
791
-            )
792
-        );
793
-    }
794
-
795
-
796
-    /**
797
-     * _display_payment_options
798
-     *
799
-     * @param string $transaction_details
800
-     * @return EE_Form_Section_Proper
801
-     * @throws EE_Error
802
-     * @throws InvalidArgumentException
803
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
804
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
805
-     */
806
-    private function _display_payment_options($transaction_details = '')
807
-    {
808
-        // has method_of_payment been set by no-js user?
809
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment();
810
-        // build payment options form
811
-        return apply_filters(
812
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__payment_options_form',
813
-            new EE_Form_Section_Proper(
814
-                array(
815
-                    'subsections'     => array(
816
-                        'before_payment_options' => apply_filters(
817
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__before_payment_options',
818
-                            new EE_Form_Section_Proper(
819
-                                array('layout_strategy' => new EE_Div_Per_Section_Layout())
820
-                            )
821
-                        ),
822
-                        'payment_options'        => $this->_setup_payment_options(),
823
-                        'after_payment_options'  => apply_filters(
824
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__after_payment_options',
825
-                            new EE_Form_Section_Proper(
826
-                                array('layout_strategy' => new EE_Div_Per_Section_Layout())
827
-                            )
828
-                        ),
829
-                    ),
830
-                    'layout_strategy' => new EE_Template_Layout(
831
-                        array(
832
-                            'layout_template_file' => $this->_template,
833
-                            'template_args'        => apply_filters(
834
-                                'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__template_args',
835
-                                array(
836
-                                    'reg_count'                 => $this->line_item_display->total_items(),
837
-                                    'transaction_details'       => $transaction_details,
838
-                                    'available_payment_methods' => array(),
839
-                                )
840
-                            ),
841
-                        )
842
-                    ),
843
-                )
844
-            )
845
-        );
846
-    }
847
-
848
-
849
-    /**
850
-     * _extra_hidden_inputs
851
-     *
852
-     * @param bool $no_payment_required
853
-     * @return \EE_Form_Section_Proper
854
-     * @throws \EE_Error
855
-     */
856
-    private function _extra_hidden_inputs($no_payment_required = true)
857
-    {
858
-        return new EE_Form_Section_Proper(
859
-            array(
860
-                'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
861
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
862
-                'subsections'     => array(
863
-                    'spco_no_payment_required' => new EE_Hidden_Input(
864
-                        array(
865
-                            'normalization_strategy' => new EE_Boolean_Normalization(),
866
-                            'html_name'              => 'spco_no_payment_required',
867
-                            'html_id'                => 'spco-no-payment-required-payment_options',
868
-                            'default'                => $no_payment_required,
869
-                        )
870
-                    ),
871
-                    'spco_transaction_id'      => new EE_Fixed_Hidden_Input(
872
-                        array(
873
-                            'normalization_strategy' => new EE_Int_Normalization(),
874
-                            'html_name'              => 'spco_transaction_id',
875
-                            'html_id'                => 'spco-transaction-id',
876
-                            'default'                => $this->checkout->transaction->ID(),
877
-                        )
878
-                    ),
879
-                ),
880
-            )
881
-        );
882
-    }
883
-
884
-
885
-    /**
886
-     *    _apply_registration_payments_to_amount_owing
887
-     *
888
-     * @access protected
889
-     * @param array $registrations
890
-     * @throws EE_Error
891
-     */
892
-    protected function _apply_registration_payments_to_amount_owing(array $registrations)
893
-    {
894
-        $payments = array();
895
-        foreach ($registrations as $registration) {
896
-            if ($registration instanceof EE_Registration && $registration->owes_monies_and_can_pay()) {
897
-                $payments += $registration->registration_payments();
898
-            }
899
-        }
900
-        if (! empty($payments)) {
901
-            foreach ($payments as $payment) {
902
-                if ($payment instanceof EE_Registration_Payment) {
903
-                    $this->checkout->amount_owing -= $payment->amount();
904
-                }
905
-            }
906
-        }
907
-    }
908
-
909
-
910
-    /**
911
-     *    _reset_selected_method_of_payment
912
-     *
913
-     * @access    private
914
-     * @param    bool $force_reset
915
-     * @return void
916
-     * @throws InvalidArgumentException
917
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
918
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
919
-     */
920
-    private function _reset_selected_method_of_payment($force_reset = false)
921
-    {
922
-        $reset_payment_method = $force_reset
923
-            ? true
924
-            : sanitize_text_field(EE_Registry::instance()->REQ->get('reset_payment_method', false));
925
-        if ($reset_payment_method) {
926
-            $this->checkout->selected_method_of_payment = null;
927
-            $this->checkout->payment_method = null;
928
-            $this->checkout->billing_form = null;
929
-            $this->_save_selected_method_of_payment();
930
-        }
931
-    }
932
-
933
-
934
-    /**
935
-     * _save_selected_method_of_payment
936
-     * stores the selected_method_of_payment in the session
937
-     * so that it's available for all subsequent requests including AJAX
938
-     *
939
-     * @access        private
940
-     * @param string $selected_method_of_payment
941
-     * @return void
942
-     * @throws InvalidArgumentException
943
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
944
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
945
-     */
946
-    private function _save_selected_method_of_payment($selected_method_of_payment = '')
947
-    {
948
-        $selected_method_of_payment = ! empty($selected_method_of_payment)
949
-            ? $selected_method_of_payment
950
-            : $this->checkout->selected_method_of_payment;
951
-        EE_Registry::instance()->SSN->set_session_data(
952
-            array('selected_method_of_payment' => $selected_method_of_payment)
953
-        );
954
-    }
955
-
956
-
957
-    /**
958
-     * _setup_payment_options
959
-     *
960
-     * @return EE_Form_Section_Proper
961
-     * @throws EE_Error
962
-     * @throws InvalidArgumentException
963
-     * @throws ReflectionException
964
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
965
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
966
-     */
967
-    public function _setup_payment_options()
968
-    {
969
-        // load payment method classes
970
-        $this->checkout->available_payment_methods = $this->_get_available_payment_methods();
971
-        if (empty($this->checkout->available_payment_methods)) {
972
-            EE_Error::add_error(
973
-                apply_filters(
974
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___setup_payment_options__error_message_no_payment_methods',
975
-                    sprintf(
976
-                        esc_html__(
977
-                            'Sorry, you cannot complete your purchase because a payment method is not active.%1$s Please contact %2$s for assistance and provide a description of the problem.',
978
-                            'event_espresso'
979
-                        ),
980
-                        '<br>',
981
-                        EE_Registry::instance()->CFG->organization->get_pretty('email')
982
-                    )
983
-                ),
984
-                __FILE__,
985
-                __FUNCTION__,
986
-                __LINE__
987
-            );
988
-        }
989
-        // switch up header depending on number of available payment methods
990
-        $payment_method_header = count($this->checkout->available_payment_methods) > 1
991
-            ? apply_filters(
992
-                'FHEE__registration_page_payment_options__method_of_payment_hdr',
993
-                esc_html__('Please Select Your Method of Payment', 'event_espresso')
994
-            )
995
-            : apply_filters(
996
-                'FHEE__registration_page_payment_options__method_of_payment_hdr',
997
-                esc_html__('Method of Payment', 'event_espresso')
998
-            );
999
-        $available_payment_methods = array(
1000
-            // display the "Payment Method" header
1001
-            'payment_method_header' => new EE_Form_Section_HTML(
1002
-                EEH_HTML::h4($payment_method_header, 'method-of-payment-hdr')
1003
-            ),
1004
-        );
1005
-        // the list of actual payment methods ( invoice, paypal, etc ) in a  ( slug => HTML )  format
1006
-        $available_payment_method_options = array();
1007
-        $default_payment_method_option = array();
1008
-        // additional instructions to be displayed and hidden below payment methods (adding a clearing div to start)
1009
-        $payment_methods_billing_info = array(
1010
-            new EE_Form_Section_HTML(
1011
-                EEH_HTML::div('<br />', '', '', 'clear:both;')
1012
-            ),
1013
-        );
1014
-        // loop through payment methods
1015
-        foreach ($this->checkout->available_payment_methods as $payment_method) {
1016
-            if ($payment_method instanceof EE_Payment_Method) {
1017
-                $payment_method_button = EEH_HTML::img(
1018
-                    $payment_method->button_url(),
1019
-                    $payment_method->name(),
1020
-                    'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1021
-                    'spco-payment-method-btn-img'
1022
-                );
1023
-                // check if any payment methods are set as default
1024
-                // if payment method is already selected OR nothing is selected and this payment method should be
1025
-                // open_by_default
1026
-                if (($this->checkout->selected_method_of_payment === $payment_method->slug())
1027
-                    || (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1028
-                ) {
1029
-                    $this->checkout->selected_method_of_payment = $payment_method->slug();
1030
-                    $this->_save_selected_method_of_payment();
1031
-                    $default_payment_method_option[ $payment_method->slug() ] = $payment_method_button;
1032
-                } else {
1033
-                    $available_payment_method_options[ $payment_method->slug() ] = $payment_method_button;
1034
-                }
1035
-                $payment_methods_billing_info[ $payment_method->slug(
1036
-                ) . '-info' ] = $this->_payment_method_billing_info(
1037
-                    $payment_method
1038
-                );
1039
-            }
1040
-        }
1041
-        // prepend available_payment_method_options with default_payment_method_option so that it appears first in list
1042
-        // of PMs
1043
-        $available_payment_method_options = $default_payment_method_option + $available_payment_method_options;
1044
-        // now generate the actual form  inputs
1045
-        $available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
1046
-            $available_payment_method_options
1047
-        );
1048
-        $available_payment_methods += $payment_methods_billing_info;
1049
-        // build the available payment methods form
1050
-        return new EE_Form_Section_Proper(
1051
-            array(
1052
-                'html_id'         => 'spco-available-methods-of-payment-dv',
1053
-                'subsections'     => $available_payment_methods,
1054
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1055
-            )
1056
-        );
1057
-    }
1058
-
1059
-
1060
-    /**
1061
-     * _get_available_payment_methods
1062
-     *
1063
-     * @return EE_Payment_Method[]
1064
-     * @throws EE_Error
1065
-     * @throws InvalidArgumentException
1066
-     * @throws ReflectionException
1067
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1068
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1069
-     */
1070
-    protected function _get_available_payment_methods()
1071
-    {
1072
-        if (! empty($this->checkout->available_payment_methods)) {
1073
-            return $this->checkout->available_payment_methods;
1074
-        }
1075
-        $available_payment_methods = array();
1076
-        // load EEM_Payment_Method
1077
-        EE_Registry::instance()->load_model('Payment_Method');
1078
-        /** @type EEM_Payment_Method $EEM_Payment_Method */
1079
-        $EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
1080
-        // get all active payment methods
1081
-        $payment_methods = $EEM_Payment_Method->get_all_for_transaction(
1082
-            $this->checkout->transaction,
1083
-            EEM_Payment_Method::scope_cart
1084
-        );
1085
-        foreach ($payment_methods as $payment_method) {
1086
-            if ($payment_method instanceof EE_Payment_Method) {
1087
-                $available_payment_methods[ $payment_method->slug() ] = $payment_method;
1088
-            }
1089
-        }
1090
-        return $available_payment_methods;
1091
-    }
1092
-
1093
-
1094
-    /**
1095
-     *    _available_payment_method_inputs
1096
-     *
1097
-     * @access    private
1098
-     * @param    array $available_payment_method_options
1099
-     * @return    \EE_Form_Section_Proper
1100
-     */
1101
-    private function _available_payment_method_inputs($available_payment_method_options = array())
1102
-    {
1103
-        // generate inputs
1104
-        return new EE_Form_Section_Proper(
1105
-            array(
1106
-                'html_id'         => 'ee-available-payment-method-inputs',
1107
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1108
-                'subsections'     => array(
1109
-                    '' => new EE_Radio_Button_Input(
1110
-                        $available_payment_method_options,
1111
-                        array(
1112
-                            'html_name'          => 'selected_method_of_payment',
1113
-                            'html_class'         => 'spco-payment-method',
1114
-                            'default'            => $this->checkout->selected_method_of_payment,
1115
-                            'label_size'         => 11,
1116
-                            'enforce_label_size' => true,
1117
-                        )
1118
-                    ),
1119
-                ),
1120
-            )
1121
-        );
1122
-    }
1123
-
1124
-
1125
-    /**
1126
-     *    _payment_method_billing_info
1127
-     *
1128
-     * @access    private
1129
-     * @param    EE_Payment_Method $payment_method
1130
-     * @return EE_Form_Section_Proper
1131
-     * @throws EE_Error
1132
-     * @throws InvalidArgumentException
1133
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1134
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1135
-     */
1136
-    private function _payment_method_billing_info(EE_Payment_Method $payment_method)
1137
-    {
1138
-        $currently_selected = $this->checkout->selected_method_of_payment === $payment_method->slug()
1139
-            ? true
1140
-            : false;
1141
-        // generate the billing form for payment method
1142
-        $billing_form = $currently_selected
1143
-            ? $this->_get_billing_form_for_payment_method($payment_method)
1144
-            : new EE_Form_Section_HTML();
1145
-        $this->checkout->billing_form = $currently_selected
1146
-            ? $billing_form
1147
-            : $this->checkout->billing_form;
1148
-        // it's all in the details
1149
-        $info_html = EEH_HTML::h3(
1150
-            esc_html__('Important information regarding your payment', 'event_espresso'),
1151
-            '',
1152
-            'spco-payment-method-hdr'
1153
-        );
1154
-        // add some info regarding the step, either from what's saved in the admin,
1155
-        // or a default string depending on whether the PM has a billing form or not
1156
-        if ($payment_method->description()) {
1157
-            $payment_method_info = $payment_method->description();
1158
-        } elseif ($billing_form instanceof EE_Billing_Info_Form) {
1159
-            $payment_method_info = sprintf(
1160
-                esc_html__(
1161
-                    'Please provide the following billing information, then click the "%1$s" button below in order to proceed.',
1162
-                    'event_espresso'
1163
-                ),
1164
-                $this->submit_button_text()
1165
-            );
1166
-        } else {
1167
-            $payment_method_info = sprintf(
1168
-                esc_html__('Please click the "%1$s" button below in order to proceed.', 'event_espresso'),
1169
-                $this->submit_button_text()
1170
-            );
1171
-        }
1172
-        $info_html .= EEH_HTML::p(
1173
-            apply_filters(
1174
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options___payment_method_billing_info__payment_method_info',
1175
-                $payment_method_info
1176
-            ),
1177
-            '',
1178
-            'spco-payment-method-desc ee-attention'
1179
-        );
1180
-        return new EE_Form_Section_Proper(
1181
-            array(
1182
-                'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1183
-                'html_class'      => 'spco-payment-method-info-dv',
1184
-                // only display the selected or default PM
1185
-                'html_style'      => $currently_selected ? '' : 'display:none;',
1186
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1187
-                'subsections'     => array(
1188
-                    'info'         => new EE_Form_Section_HTML($info_html),
1189
-                    'billing_form' => $currently_selected ? $billing_form : new EE_Form_Section_HTML(),
1190
-                ),
1191
-            )
1192
-        );
1193
-    }
1194
-
1195
-
1196
-    /**
1197
-     * get_billing_form_html_for_payment_method
1198
-     *
1199
-     * @access public
1200
-     * @return string
1201
-     * @throws EE_Error
1202
-     * @throws InvalidArgumentException
1203
-     * @throws ReflectionException
1204
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1205
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1206
-     */
1207
-    public function get_billing_form_html_for_payment_method()
1208
-    {
1209
-        // how have they chosen to pay?
1210
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1211
-        $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1212
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1213
-            return false;
1214
-        }
1215
-        if (apply_filters(
1216
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1217
-            false
1218
-        )) {
1219
-            EE_Error::add_success(
1220
-                apply_filters(
1221
-                    'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1222
-                    sprintf(
1223
-                        esc_html__(
1224
-                            'You have selected "%s" as your method of payment. Please note the important payment information below.',
1225
-                            'event_espresso'
1226
-                        ),
1227
-                        $this->checkout->payment_method->name()
1228
-                    )
1229
-                )
1230
-            );
1231
-        }
1232
-        // now generate billing form for selected method of payment
1233
-        $payment_method_billing_form = $this->_get_billing_form_for_payment_method($this->checkout->payment_method);
1234
-        // fill form with attendee info if applicable
1235
-        if ($payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
1236
-            && $this->checkout->transaction_has_primary_registrant()
1237
-        ) {
1238
-            $payment_method_billing_form->populate_from_attendee(
1239
-                $this->checkout->transaction->primary_registration()->attendee()
1240
-            );
1241
-        }
1242
-        // and debug content
1243
-        if ($payment_method_billing_form instanceof EE_Billing_Info_Form
1244
-            && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1245
-        ) {
1246
-            $payment_method_billing_form =
1247
-                $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1248
-                    $payment_method_billing_form
1249
-                );
1250
-        }
1251
-        $billing_info = $payment_method_billing_form instanceof EE_Form_Section_Proper
1252
-            ? $payment_method_billing_form->get_html()
1253
-            : '';
1254
-        $this->checkout->json_response->set_return_data(array('payment_method_info' => $billing_info));
1255
-        // localize validation rules for main form
1256
-        $this->checkout->current_step->reg_form->localize_validation_rules();
1257
-        $this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1258
-        return true;
1259
-    }
1260
-
1261
-
1262
-    /**
1263
-     * _get_billing_form_for_payment_method
1264
-     *
1265
-     * @access private
1266
-     * @param EE_Payment_Method $payment_method
1267
-     * @return EE_Billing_Info_Form|EE_Form_Section_HTML
1268
-     * @throws EE_Error
1269
-     * @throws InvalidArgumentException
1270
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1271
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1272
-     */
1273
-    private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method)
1274
-    {
1275
-        $billing_form = $payment_method->type_obj()->billing_form(
1276
-            $this->checkout->transaction,
1277
-            array('amount_owing' => $this->checkout->amount_owing)
1278
-        );
1279
-        if ($billing_form instanceof EE_Billing_Info_Form) {
1280
-            if (apply_filters(
1281
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1282
-                false
1283
-            )
1284
-                && EE_Registry::instance()->REQ->is_set('payment_method')
1285
-            ) {
1286
-                EE_Error::add_success(
1287
-                    apply_filters(
1288
-                        'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1289
-                        sprintf(
1290
-                            esc_html__(
1291
-                                'You have selected "%s" as your method of payment. Please note the important payment information below.',
1292
-                                'event_espresso'
1293
-                            ),
1294
-                            $payment_method->name()
1295
-                        )
1296
-                    )
1297
-                );
1298
-            }
1299
-            return apply_filters(
1300
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
1301
-                $billing_form,
1302
-                $payment_method
1303
-            );
1304
-        }
1305
-        // no actual billing form, so return empty HTML form section
1306
-        return new EE_Form_Section_HTML();
1307
-    }
1308
-
1309
-
1310
-    /**
1311
-     * _get_selected_method_of_payment
1312
-     *
1313
-     * @access private
1314
-     * @param boolean $required whether to throw an error if the "selected_method_of_payment"
1315
-     *                          is not found in the incoming request
1316
-     * @param string  $request_param
1317
-     * @return NULL|string
1318
-     * @throws EE_Error
1319
-     * @throws InvalidArgumentException
1320
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1321
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1322
-     */
1323
-    private function _get_selected_method_of_payment(
1324
-        $required = false,
1325
-        $request_param = 'selected_method_of_payment'
1326
-    ) {
1327
-        // is selected_method_of_payment set in the request ?
1328
-        $selected_method_of_payment = EE_Registry::instance()->REQ->get($request_param, false);
1329
-        if ($selected_method_of_payment) {
1330
-            // sanitize it
1331
-            $selected_method_of_payment = is_array($selected_method_of_payment)
1332
-                ? array_shift($selected_method_of_payment)
1333
-                : $selected_method_of_payment;
1334
-            $selected_method_of_payment = sanitize_text_field($selected_method_of_payment);
1335
-            // store it in the session so that it's available for all subsequent requests including AJAX
1336
-            $this->_save_selected_method_of_payment($selected_method_of_payment);
1337
-        } else {
1338
-            // or is is set in the session ?
1339
-            $selected_method_of_payment = EE_Registry::instance()->SSN->get_session_data(
1340
-                'selected_method_of_payment'
1341
-            );
1342
-        }
1343
-        // do ya really really gotta have it?
1344
-        if (empty($selected_method_of_payment) && $required) {
1345
-            EE_Error::add_error(
1346
-                sprintf(
1347
-                    esc_html__(
1348
-                        'The selected method of payment could not be determined.%sPlease ensure that you have selected one before proceeding.%sIf you continue to experience difficulties, then refresh your browser and try again, or contact %s for assistance.',
1349
-                        'event_espresso'
1350
-                    ),
1351
-                    '<br/>',
1352
-                    '<br/>',
1353
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
1354
-                ),
1355
-                __FILE__,
1356
-                __FUNCTION__,
1357
-                __LINE__
1358
-            );
1359
-            return null;
1360
-        }
1361
-        return $selected_method_of_payment;
1362
-    }
1363
-
1364
-
1365
-
1366
-
1367
-
1368
-
1369
-    /********************************************************************************************************/
1370
-    /***********************************  SWITCH PAYMENT METHOD  ************************************/
1371
-    /********************************************************************************************************/
1372
-    /**
1373
-     * switch_payment_method
1374
-     *
1375
-     * @access public
1376
-     * @return string
1377
-     * @throws EE_Error
1378
-     * @throws InvalidArgumentException
1379
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1380
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1381
-     */
1382
-    public function switch_payment_method()
1383
-    {
1384
-        if (! $this->_verify_payment_method_is_set()) {
1385
-            return false;
1386
-        }
1387
-        if (apply_filters(
1388
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1389
-            false
1390
-        )) {
1391
-            EE_Error::add_success(
1392
-                apply_filters(
1393
-                    'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1394
-                    sprintf(
1395
-                        esc_html__(
1396
-                            'You have selected "%s" as your method of payment. Please note the important payment information below.',
1397
-                            'event_espresso'
1398
-                        ),
1399
-                        $this->checkout->payment_method->name()
1400
-                    )
1401
-                )
1402
-            );
1403
-        }
1404
-        // generate billing form for selected method of payment if it hasn't been done already
1405
-        if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1406
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1407
-                $this->checkout->payment_method
1408
-            );
1409
-        }
1410
-        // fill form with attendee info if applicable
1411
-        if (apply_filters(
1412
-            'FHEE__populate_billing_form_fields_from_attendee',
1413
-            (
1414
-                $this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1415
-                && $this->checkout->transaction_has_primary_registrant()
1416
-            ),
1417
-            $this->checkout->billing_form,
1418
-            $this->checkout->transaction
1419
-        )
1420
-        ) {
1421
-            $this->checkout->billing_form->populate_from_attendee(
1422
-                $this->checkout->transaction->primary_registration()->attendee()
1423
-            );
1424
-        }
1425
-        // and debug content
1426
-        if ($this->checkout->billing_form instanceof EE_Billing_Info_Form
1427
-            && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1428
-        ) {
1429
-            $this->checkout->billing_form =
1430
-                $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1431
-                    $this->checkout->billing_form
1432
-                );
1433
-        }
1434
-        // get html and validation rules for form
1435
-        if ($this->checkout->billing_form instanceof EE_Form_Section_Proper) {
1436
-            $this->checkout->json_response->set_return_data(
1437
-                array('payment_method_info' => $this->checkout->billing_form->get_html())
1438
-            );
1439
-            // localize validation rules for main form
1440
-            $this->checkout->billing_form->localize_validation_rules(true);
1441
-            $this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1442
-        } else {
1443
-            $this->checkout->json_response->set_return_data(array('payment_method_info' => ''));
1444
-        }
1445
-        // prevents advancement to next step
1446
-        $this->checkout->continue_reg = false;
1447
-        return true;
1448
-    }
1449
-
1450
-
1451
-    /**
1452
-     * _verify_payment_method_is_set
1453
-     *
1454
-     * @return bool
1455
-     * @throws EE_Error
1456
-     * @throws InvalidArgumentException
1457
-     * @throws ReflectionException
1458
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1459
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1460
-     */
1461
-    protected function _verify_payment_method_is_set()
1462
-    {
1463
-        // generate billing form for selected method of payment if it hasn't been done already
1464
-        if (empty($this->checkout->selected_method_of_payment)) {
1465
-            // how have they chosen to pay?
1466
-            $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1467
-        } else {
1468
-            // choose your own adventure based on method_of_payment
1469
-            switch ($this->checkout->selected_method_of_payment) {
1470
-                case 'events_sold_out':
1471
-                    EE_Error::add_attention(
1472
-                        apply_filters(
1473
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__sold_out_events_msg',
1474
-                            esc_html__(
1475
-                                'It appears that the event you were about to make a payment for has sold out since this form first loaded. Please contact the event administrator if you believe this is an error.',
1476
-                                'event_espresso'
1477
-                            )
1478
-                        ),
1479
-                        __FILE__,
1480
-                        __FUNCTION__,
1481
-                        __LINE__
1482
-                    );
1483
-                    return false;
1484
-                    break;
1485
-                case 'payments_closed':
1486
-                    EE_Error::add_attention(
1487
-                        apply_filters(
1488
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__payments_closed_msg',
1489
-                            esc_html__(
1490
-                                'It appears that the event you were about to make a payment for is not accepting payments at this time. Please contact the event administrator if you believe this is an error.',
1491
-                                'event_espresso'
1492
-                            )
1493
-                        ),
1494
-                        __FILE__,
1495
-                        __FUNCTION__,
1496
-                        __LINE__
1497
-                    );
1498
-                    return false;
1499
-                    break;
1500
-                case 'no_payment_required':
1501
-                    EE_Error::add_attention(
1502
-                        apply_filters(
1503
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__no_payment_required_msg',
1504
-                            esc_html__(
1505
-                                'It appears that the event you were about to make a payment for does not require payment. Please contact the event administrator if you believe this is an error.',
1506
-                                'event_espresso'
1507
-                            )
1508
-                        ),
1509
-                        __FILE__,
1510
-                        __FUNCTION__,
1511
-                        __LINE__
1512
-                    );
1513
-                    return false;
1514
-                    break;
1515
-                default:
1516
-            }
1517
-        }
1518
-        // verify payment method
1519
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1520
-            // get payment method for selected method of payment
1521
-            $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1522
-        }
1523
-        return $this->checkout->payment_method instanceof EE_Payment_Method ? true : false;
1524
-    }
1525
-
1526
-
1527
-
1528
-    /********************************************************************************************************/
1529
-    /***************************************  SAVE PAYER DETAILS  ****************************************/
1530
-    /********************************************************************************************************/
1531
-    /**
1532
-     * save_payer_details_via_ajax
1533
-     *
1534
-     * @return void
1535
-     * @throws EE_Error
1536
-     * @throws InvalidArgumentException
1537
-     * @throws ReflectionException
1538
-     * @throws RuntimeException
1539
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1540
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1541
-     */
1542
-    public function save_payer_details_via_ajax()
1543
-    {
1544
-        if (! $this->_verify_payment_method_is_set()) {
1545
-            return;
1546
-        }
1547
-        // generate billing form for selected method of payment if it hasn't been done already
1548
-        if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1549
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1550
-                $this->checkout->payment_method
1551
-            );
1552
-        }
1553
-        // generate primary attendee from payer info if applicable
1554
-        if (! $this->checkout->transaction_has_primary_registrant()) {
1555
-            $attendee = $this->_create_attendee_from_request_data();
1556
-            if ($attendee instanceof EE_Attendee) {
1557
-                foreach ($this->checkout->transaction->registrations() as $registration) {
1558
-                    if ($registration->is_primary_registrant()) {
1559
-                        $this->checkout->primary_attendee_obj = $attendee;
1560
-                        $registration->_add_relation_to($attendee, 'Attendee');
1561
-                        $registration->set_attendee_id($attendee->ID());
1562
-                        $registration->update_cache_after_object_save('Attendee', $attendee);
1563
-                    }
1564
-                }
1565
-            }
1566
-        }
1567
-    }
1568
-
1569
-
1570
-    /**
1571
-     * create_attendee_from_request_data
1572
-     * uses info from alternate GET or POST data (such as AJAX) to create a new attendee
1573
-     *
1574
-     * @return EE_Attendee
1575
-     * @throws EE_Error
1576
-     * @throws InvalidArgumentException
1577
-     * @throws ReflectionException
1578
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1579
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1580
-     */
1581
-    protected function _create_attendee_from_request_data()
1582
-    {
1583
-        // get State ID
1584
-        $STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1585
-        if (! empty($STA_ID)) {
1586
-            // can we get state object from name ?
1587
-            EE_Registry::instance()->load_model('State');
1588
-            $state = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
1589
-            $STA_ID = is_array($state) && ! empty($state) ? reset($state) : $STA_ID;
1590
-        }
1591
-        // get Country ISO
1592
-        $CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1593
-        if (! empty($CNT_ISO)) {
1594
-            // can we get country object from name ?
1595
-            EE_Registry::instance()->load_model('Country');
1596
-            $country = EEM_Country::instance()->get_col(
1597
-                array(array('CNT_name' => $CNT_ISO), 'limit' => 1),
1598
-                'CNT_ISO'
1599
-            );
1600
-            $CNT_ISO = is_array($country) && ! empty($country) ? reset($country) : $CNT_ISO;
1601
-        }
1602
-        // grab attendee data
1603
-        $attendee_data = array(
1604
-            'ATT_fname'    => ! empty($_REQUEST['first_name']) ? sanitize_text_field($_REQUEST['first_name']) : '',
1605
-            'ATT_lname'    => ! empty($_REQUEST['last_name']) ? sanitize_text_field($_REQUEST['last_name']) : '',
1606
-            'ATT_email'    => ! empty($_REQUEST['email']) ? sanitize_email($_REQUEST['email']) : '',
1607
-            'ATT_address'  => ! empty($_REQUEST['address']) ? sanitize_text_field($_REQUEST['address']) : '',
1608
-            'ATT_address2' => ! empty($_REQUEST['address2']) ? sanitize_text_field($_REQUEST['address2']) : '',
1609
-            'ATT_city'     => ! empty($_REQUEST['city']) ? sanitize_text_field($_REQUEST['city']) : '',
1610
-            'STA_ID'       => $STA_ID,
1611
-            'CNT_ISO'      => $CNT_ISO,
1612
-            'ATT_zip'      => ! empty($_REQUEST['zip']) ? sanitize_text_field($_REQUEST['zip']) : '',
1613
-            'ATT_phone'    => ! empty($_REQUEST['phone']) ? sanitize_text_field($_REQUEST['phone']) : '',
1614
-        );
1615
-        // validate the email address since it is the most important piece of info
1616
-        if (empty($attendee_data['ATT_email']) || $attendee_data['ATT_email'] !== $_REQUEST['email']) {
1617
-            EE_Error::add_error(
1618
-                esc_html__('An invalid email address was submitted.', 'event_espresso'),
1619
-                __FILE__,
1620
-                __FUNCTION__,
1621
-                __LINE__
1622
-            );
1623
-        }
1624
-        // does this attendee already exist in the db ? we're searching using a combination of first name, last name,
1625
-        // AND email address
1626
-        if (! empty($attendee_data['ATT_fname'])
1627
-            && ! empty($attendee_data['ATT_lname'])
1628
-            && ! empty($attendee_data['ATT_email'])
1629
-        ) {
1630
-            $existing_attendee = EE_Registry::instance()->LIB->EEM_Attendee->find_existing_attendee(
1631
-                array(
1632
-                    'ATT_fname' => $attendee_data['ATT_fname'],
1633
-                    'ATT_lname' => $attendee_data['ATT_lname'],
1634
-                    'ATT_email' => $attendee_data['ATT_email'],
1635
-                )
1636
-            );
1637
-            if ($existing_attendee instanceof EE_Attendee) {
1638
-                return $existing_attendee;
1639
-            }
1640
-        }
1641
-        // no existing attendee? kk let's create a new one
1642
-        // kinda lame, but we need a first and last name to create an attendee, so use the email address if those
1643
-        // don't exist
1644
-        $attendee_data['ATT_fname'] = ! empty($attendee_data['ATT_fname'])
1645
-            ? $attendee_data['ATT_fname']
1646
-            : $attendee_data['ATT_email'];
1647
-        $attendee_data['ATT_lname'] = ! empty($attendee_data['ATT_lname'])
1648
-            ? $attendee_data['ATT_lname']
1649
-            : $attendee_data['ATT_email'];
1650
-        return EE_Attendee::new_instance($attendee_data);
1651
-    }
1652
-
1653
-
1654
-
1655
-    /********************************************************************************************************/
1656
-    /****************************************  PROCESS REG STEP  *****************************************/
1657
-    /********************************************************************************************************/
1658
-    /**
1659
-     * process_reg_step
1660
-     *
1661
-     * @return bool
1662
-     * @throws EE_Error
1663
-     * @throws InvalidArgumentException
1664
-     * @throws ReflectionException
1665
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1666
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1667
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1668
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
1669
-     */
1670
-    public function process_reg_step()
1671
-    {
1672
-        // how have they chosen to pay?
1673
-        $this->checkout->selected_method_of_payment = $this->checkout->transaction->is_free()
1674
-            ? 'no_payment_required'
1675
-            : $this->_get_selected_method_of_payment(true);
1676
-        // choose your own adventure based on method_of_payment
1677
-        switch ($this->checkout->selected_method_of_payment) {
1678
-            case 'events_sold_out':
1679
-                $this->checkout->redirect = true;
1680
-                $this->checkout->redirect_url = $this->checkout->cancel_page_url;
1681
-                $this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1682
-                // mark this reg step as completed
1683
-                $this->set_completed();
1684
-                return false;
1685
-                break;
1686
-
1687
-            case 'payments_closed':
1688
-                if (apply_filters(
1689
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__payments_closed__display_success',
1690
-                    false
1691
-                )) {
1692
-                    EE_Error::add_success(
1693
-                        esc_html__('no payment required at this time.', 'event_espresso'),
1694
-                        __FILE__,
1695
-                        __FUNCTION__,
1696
-                        __LINE__
1697
-                    );
1698
-                }
1699
-                // mark this reg step as completed
1700
-                $this->set_completed();
1701
-                return true;
1702
-                break;
1703
-
1704
-            case 'no_payment_required':
1705
-                if (apply_filters(
1706
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__no_payment_required__display_success',
1707
-                    false
1708
-                )) {
1709
-                    EE_Error::add_success(
1710
-                        esc_html__('no payment required.', 'event_espresso'),
1711
-                        __FILE__,
1712
-                        __FUNCTION__,
1713
-                        __LINE__
1714
-                    );
1715
-                }
1716
-                // mark this reg step as completed
1717
-                $this->set_completed();
1718
-                return true;
1719
-                break;
1720
-
1721
-            default:
1722
-                $registrations = EE_Registry::instance()->SSN->checkout()->transaction->registrations(
1723
-                    EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
1724
-                );
1725
-                $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
1726
-                    $registrations,
1727
-                    EE_Registry::instance()->SSN->checkout()->revisit
1728
-                );
1729
-                // calculate difference between the two arrays
1730
-                $registrations = array_diff($registrations, $ejected_registrations);
1731
-                if (empty($registrations)) {
1732
-                    $this->_redirect_because_event_sold_out();
1733
-                    return false;
1734
-                }
1735
-                $payment_successful = $this->_process_payment();
1736
-                if ($payment_successful) {
1737
-                    $this->checkout->continue_reg = true;
1738
-                    $this->_maybe_set_completed($this->checkout->payment_method);
1739
-                } else {
1740
-                    $this->checkout->continue_reg = false;
1741
-                }
1742
-                return $payment_successful;
1743
-        }
1744
-    }
1745
-
1746
-
1747
-    /**
1748
-     * _redirect_because_event_sold_out
1749
-     *
1750
-     * @access protected
1751
-     * @return void
1752
-     */
1753
-    protected function _redirect_because_event_sold_out()
1754
-    {
1755
-        $this->checkout->continue_reg = false;
1756
-        // set redirect URL
1757
-        $this->checkout->redirect_url = add_query_arg(
1758
-            array('e_reg_url_link' => $this->checkout->reg_url_link),
1759
-            $this->checkout->current_step->reg_step_url()
1760
-        );
1761
-        $this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1762
-    }
1763
-
1764
-
1765
-    /**
1766
-     * _maybe_set_completed
1767
-     *
1768
-     * @access protected
1769
-     * @param \EE_Payment_Method $payment_method
1770
-     * @return void
1771
-     * @throws \EE_Error
1772
-     */
1773
-    protected function _maybe_set_completed(EE_Payment_Method $payment_method)
1774
-    {
1775
-        switch ($payment_method->type_obj()->payment_occurs()) {
1776
-            case EE_PMT_Base::offsite:
1777
-                break;
1778
-            case EE_PMT_Base::onsite:
1779
-            case EE_PMT_Base::offline:
1780
-                // mark this reg step as completed
1781
-                $this->set_completed();
1782
-                break;
1783
-        }
1784
-    }
1785
-
1786
-
1787
-    /**
1788
-     *    update_reg_step
1789
-     *    this is the final step after a user  revisits the site to retry a payment
1790
-     *
1791
-     * @return bool
1792
-     * @throws EE_Error
1793
-     * @throws InvalidArgumentException
1794
-     * @throws ReflectionException
1795
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1796
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1797
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1798
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
1799
-     */
1800
-    public function update_reg_step()
1801
-    {
1802
-        $success = true;
1803
-        // if payment required
1804
-        if ($this->checkout->transaction->total() > 0) {
1805
-            do_action(
1806
-                'AHEE__EE_Single_Page_Checkout__process_finalize_registration__before_gateway',
1807
-                $this->checkout->transaction
1808
-            );
1809
-            // attempt payment via payment method
1810
-            $success = $this->process_reg_step();
1811
-        }
1812
-        if ($success && ! $this->checkout->redirect) {
1813
-            $this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn(
1814
-                $this->checkout->transaction->ID()
1815
-            );
1816
-            // set return URL
1817
-            $this->checkout->redirect_url = add_query_arg(
1818
-                array('e_reg_url_link' => $this->checkout->reg_url_link),
1819
-                $this->checkout->thank_you_page_url
1820
-            );
1821
-        }
1822
-        return $success;
1823
-    }
1824
-
1825
-
1826
-    /**
1827
-     *    _process_payment
1828
-     *
1829
-     * @access private
1830
-     * @return bool
1831
-     * @throws EE_Error
1832
-     * @throws InvalidArgumentException
1833
-     * @throws ReflectionException
1834
-     * @throws RuntimeException
1835
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1836
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1837
-     */
1838
-    private function _process_payment()
1839
-    {
1840
-        // basically confirm that the event hasn't sold out since they hit the page
1841
-        if (! $this->_last_second_ticket_verifications()) {
1842
-            return false;
1843
-        }
1844
-        // ya gotta make a choice man
1845
-        if (empty($this->checkout->selected_method_of_payment)) {
1846
-            $this->checkout->json_response->set_plz_select_method_of_payment(
1847
-                esc_html__('Please select a method of payment before proceeding.', 'event_espresso')
1848
-            );
1849
-            return false;
1850
-        }
1851
-        // get EE_Payment_Method object
1852
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1853
-            return false;
1854
-        }
1855
-        // setup billing form
1856
-        if ($this->checkout->payment_method->is_on_site()) {
1857
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1858
-                $this->checkout->payment_method
1859
-            );
1860
-            // bad billing form ?
1861
-            if (! $this->_billing_form_is_valid()) {
1862
-                return false;
1863
-            }
1864
-        }
1865
-        // ensure primary registrant has been fully processed
1866
-        if (! $this->_setup_primary_registrant_prior_to_payment()) {
1867
-            return false;
1868
-        }
1869
-        // if session is close to expiring (under 10 minutes by default)
1870
-        if ((time() - EE_Registry::instance()->SSN->expiration()) < EE_Registry::instance()->SSN->extension()) {
1871
-            // add some time to session expiration so that payment can be completed
1872
-            EE_Registry::instance()->SSN->extend_expiration();
1873
-        }
1874
-        /** @type EE_Transaction_Processor $transaction_processor */
1875
-        // $transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
1876
-        // in case a registrant leaves to an Off-Site Gateway and never returns, we want to approve any registrations
1877
-        // for events with a default reg status of Approved
1878
-        // $transaction_processor->toggle_registration_statuses_for_default_approved_events(
1879
-        //      $this->checkout->transaction, $this->checkout->reg_cache_where_params
1880
-        // );
1881
-        // attempt payment
1882
-        $payment = $this->_attempt_payment($this->checkout->payment_method);
1883
-        // process results
1884
-        $payment = $this->_validate_payment($payment);
1885
-        $payment = $this->_post_payment_processing($payment);
1886
-        // verify payment
1887
-        if ($payment instanceof EE_Payment) {
1888
-            // store that for later
1889
-            $this->checkout->payment = $payment;
1890
-            // we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1891
-            $this->checkout->transaction->toggle_failed_transaction_status();
1892
-            $payment_status = $payment->status();
1893
-            if ($payment_status === EEM_Payment::status_id_approved
1894
-                || $payment_status === EEM_Payment::status_id_pending
1895
-            ) {
1896
-                return true;
1897
-            } else {
1898
-                return false;
1899
-            }
1900
-        } elseif ($payment === true) {
1901
-            // please note that offline payment methods will NOT make a payment,
1902
-            // but instead just mark themselves as the PMD_ID on the transaction, and return true
1903
-            $this->checkout->payment = $payment;
1904
-            return true;
1905
-        }
1906
-        // where's my money?
1907
-        return false;
1908
-    }
1909
-
1910
-
1911
-    /**
1912
-     * _last_second_ticket_verifications
1913
-     *
1914
-     * @access public
1915
-     * @return bool
1916
-     * @throws EE_Error
1917
-     */
1918
-    protected function _last_second_ticket_verifications()
1919
-    {
1920
-        // don't bother re-validating if not a return visit
1921
-        if (! $this->checkout->revisit) {
1922
-            return true;
1923
-        }
1924
-        $registrations = $this->checkout->transaction->registrations();
1925
-        if (empty($registrations)) {
1926
-            return false;
1927
-        }
1928
-        foreach ($registrations as $registration) {
1929
-            if ($registration instanceof EE_Registration && ! $registration->is_approved()) {
1930
-                $event = $registration->event_obj();
1931
-                if ($event instanceof EE_Event && $event->is_sold_out(true)) {
1932
-                    EE_Error::add_error(
1933
-                        apply_filters(
1934
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___last_second_ticket_verifications__sold_out_events_msg',
1935
-                            sprintf(
1936
-                                esc_html__(
1937
-                                    'It appears that the %1$s event that you were about to make a payment for has sold out since you first registered and/or arrived at this page. Please refresh the page and try again. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
1938
-                                    'event_espresso'
1939
-                                ),
1940
-                                $event->name()
1941
-                            )
1942
-                        ),
1943
-                        __FILE__,
1944
-                        __FUNCTION__,
1945
-                        __LINE__
1946
-                    );
1947
-                    return false;
1948
-                }
1949
-            }
1950
-        }
1951
-        return true;
1952
-    }
1953
-
1954
-
1955
-    /**
1956
-     * redirect_form
1957
-     *
1958
-     * @access public
1959
-     * @return bool
1960
-     * @throws EE_Error
1961
-     * @throws InvalidArgumentException
1962
-     * @throws ReflectionException
1963
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1964
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1965
-     */
1966
-    public function redirect_form()
1967
-    {
1968
-        $payment_method_billing_info = $this->_payment_method_billing_info(
1969
-            $this->_get_payment_method_for_selected_method_of_payment()
1970
-        );
1971
-        $html = $payment_method_billing_info->get_html();
1972
-        $html .= $this->checkout->redirect_form;
1973
-        EE_Registry::instance()->REQ->add_output($html);
1974
-        return true;
1975
-    }
1976
-
1977
-
1978
-    /**
1979
-     * _billing_form_is_valid
1980
-     *
1981
-     * @access private
1982
-     * @return bool
1983
-     * @throws \EE_Error
1984
-     */
1985
-    private function _billing_form_is_valid()
1986
-    {
1987
-        if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1988
-            return true;
1989
-        }
1990
-        if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
1991
-            if ($this->checkout->billing_form->was_submitted()) {
1992
-                $this->checkout->billing_form->receive_form_submission();
1993
-                if ($this->checkout->billing_form->is_valid()) {
1994
-                    return true;
1995
-                }
1996
-                $validation_errors = $this->checkout->billing_form->get_validation_errors_accumulated();
1997
-                $error_strings = array();
1998
-                foreach ($validation_errors as $validation_error) {
1999
-                    if ($validation_error instanceof EE_Validation_Error) {
2000
-                        $form_section = $validation_error->get_form_section();
2001
-                        if ($form_section instanceof EE_Form_Input_Base) {
2002
-                            $label = $form_section->html_label_text();
2003
-                        } elseif ($form_section instanceof EE_Form_Section_Base) {
2004
-                            $label = $form_section->name();
2005
-                        } else {
2006
-                            $label = esc_html__('Validation Error', 'event_espresso');
2007
-                        }
2008
-                        $error_strings[] = sprintf('%1$s: %2$s', $label, $validation_error->getMessage());
2009
-                    }
2010
-                }
2011
-                EE_Error::add_error(
2012
-                    sprintf(
2013
-                        esc_html__(
2014
-                            'One or more billing form inputs are invalid and require correction before proceeding. %1$s %2$s',
2015
-                            'event_espresso'
2016
-                        ),
2017
-                        '<br/>',
2018
-                        implode('<br/>', $error_strings)
2019
-                    ),
2020
-                    __FILE__,
2021
-                    __FUNCTION__,
2022
-                    __LINE__
2023
-                );
2024
-            } else {
2025
-                EE_Error::add_error(
2026
-                    esc_html__(
2027
-                        'The billing form was not submitted or something prevented it\'s submission.',
2028
-                        'event_espresso'
2029
-                    ),
2030
-                    __FILE__,
2031
-                    __FUNCTION__,
2032
-                    __LINE__
2033
-                );
2034
-            }
2035
-        } else {
2036
-            EE_Error::add_error(
2037
-                esc_html__(
2038
-                    'The submitted billing form is invalid possibly due to a technical reason.',
2039
-                    'event_espresso'
2040
-                ),
2041
-                __FILE__,
2042
-                __FUNCTION__,
2043
-                __LINE__
2044
-            );
2045
-        }
2046
-        return false;
2047
-    }
2048
-
2049
-
2050
-    /**
2051
-     * _setup_primary_registrant_prior_to_payment
2052
-     * ensures that the primary registrant has a valid attendee object created with the critical details populated
2053
-     * (first & last name & email) and that both the transaction object and primary registration object have been saved
2054
-     * plz note that any other registrations will NOT be saved at this point (because they may not have any details
2055
-     * yet)
2056
-     *
2057
-     * @access private
2058
-     * @return bool
2059
-     * @throws EE_Error
2060
-     * @throws InvalidArgumentException
2061
-     * @throws ReflectionException
2062
-     * @throws RuntimeException
2063
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2064
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2065
-     */
2066
-    private function _setup_primary_registrant_prior_to_payment()
2067
-    {
2068
-        // check if transaction has a primary registrant and that it has a related Attendee object
2069
-        // if not, then we need to at least gather some primary registrant data before attempting payment
2070
-        if ($this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
2071
-            && ! $this->checkout->transaction_has_primary_registrant()
2072
-            && ! $this->_capture_primary_registration_data_from_billing_form()
2073
-        ) {
2074
-            return false;
2075
-        }
2076
-        // because saving an object clears it's cache, we need to do the chevy shuffle
2077
-        // grab the primary_registration object
2078
-        $primary_registration = $this->checkout->transaction->primary_registration();
2079
-        // at this point we'll consider a TXN to not have been failed
2080
-        $this->checkout->transaction->toggle_failed_transaction_status();
2081
-        // save the TXN ( which clears cached copy of primary_registration)
2082
-        $this->checkout->transaction->save();
2083
-        // grab TXN ID and save it to the primary_registration
2084
-        $primary_registration->set_transaction_id($this->checkout->transaction->ID());
2085
-        // save what we have so far
2086
-        $primary_registration->save();
2087
-        return true;
2088
-    }
2089
-
2090
-
2091
-    /**
2092
-     * _capture_primary_registration_data_from_billing_form
2093
-     *
2094
-     * @access private
2095
-     * @return bool
2096
-     * @throws EE_Error
2097
-     * @throws InvalidArgumentException
2098
-     * @throws ReflectionException
2099
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2100
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2101
-     */
2102
-    private function _capture_primary_registration_data_from_billing_form()
2103
-    {
2104
-        // convert billing form data into an attendee
2105
-        $this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2106
-        if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2107
-            EE_Error::add_error(
2108
-                sprintf(
2109
-                    esc_html__(
2110
-                        'The billing form details could not be used for attendee details due to a technical issue.%sPlease try again or contact %s for assistance.',
2111
-                        'event_espresso'
2112
-                    ),
2113
-                    '<br/>',
2114
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2115
-                ),
2116
-                __FILE__,
2117
-                __FUNCTION__,
2118
-                __LINE__
2119
-            );
2120
-            return false;
2121
-        }
2122
-        $primary_registration = $this->checkout->transaction->primary_registration();
2123
-        if (! $primary_registration instanceof EE_Registration) {
2124
-            EE_Error::add_error(
2125
-                sprintf(
2126
-                    esc_html__(
2127
-                        'The primary registrant for this transaction could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2128
-                        'event_espresso'
2129
-                    ),
2130
-                    '<br/>',
2131
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2132
-                ),
2133
-                __FILE__,
2134
-                __FUNCTION__,
2135
-                __LINE__
2136
-            );
2137
-            return false;
2138
-        }
2139
-        if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2140
-              instanceof
2141
-              EE_Attendee
2142
-        ) {
2143
-            EE_Error::add_error(
2144
-                sprintf(
2145
-                    esc_html__(
2146
-                        'The primary registrant could not be associated with this transaction due to a technical issue.%sPlease try again or contact %s for assistance.',
2147
-                        'event_espresso'
2148
-                    ),
2149
-                    '<br/>',
2150
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2151
-                ),
2152
-                __FILE__,
2153
-                __FUNCTION__,
2154
-                __LINE__
2155
-            );
2156
-            return false;
2157
-        }
2158
-        /** @type EE_Registration_Processor $registration_processor */
2159
-        $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
2160
-        // at this point, we should have enough details about the registrant to consider the registration NOT incomplete
2161
-        $registration_processor->toggle_incomplete_registration_status_to_default($primary_registration);
2162
-        return true;
2163
-    }
2164
-
2165
-
2166
-    /**
2167
-     * _get_payment_method_for_selected_method_of_payment
2168
-     * retrieves a valid payment method
2169
-     *
2170
-     * @access public
2171
-     * @return EE_Payment_Method
2172
-     * @throws EE_Error
2173
-     * @throws InvalidArgumentException
2174
-     * @throws ReflectionException
2175
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2176
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2177
-     */
2178
-    private function _get_payment_method_for_selected_method_of_payment()
2179
-    {
2180
-        if ($this->checkout->selected_method_of_payment === 'events_sold_out') {
2181
-            $this->_redirect_because_event_sold_out();
2182
-            return null;
2183
-        }
2184
-        // get EE_Payment_Method object
2185
-        if (isset($this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ])) {
2186
-            $payment_method = $this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ];
2187
-        } else {
2188
-            // load EEM_Payment_Method
2189
-            EE_Registry::instance()->load_model('Payment_Method');
2190
-            /** @type EEM_Payment_Method $EEM_Payment_Method */
2191
-            $EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
2192
-            $payment_method = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2193
-        }
2194
-        // verify $payment_method
2195
-        if (! $payment_method instanceof EE_Payment_Method) {
2196
-            // not a payment
2197
-            EE_Error::add_error(
2198
-                sprintf(
2199
-                    esc_html__(
2200
-                        'The selected method of payment could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2201
-                        'event_espresso'
2202
-                    ),
2203
-                    '<br/>',
2204
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2205
-                ),
2206
-                __FILE__,
2207
-                __FUNCTION__,
2208
-                __LINE__
2209
-            );
2210
-            return null;
2211
-        }
2212
-        // and verify it has a valid Payment_Method Type object
2213
-        if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2214
-            // not a payment
2215
-            EE_Error::add_error(
2216
-                sprintf(
2217
-                    esc_html__(
2218
-                        'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2219
-                        'event_espresso'
2220
-                    ),
2221
-                    '<br/>',
2222
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2223
-                ),
2224
-                __FILE__,
2225
-                __FUNCTION__,
2226
-                __LINE__
2227
-            );
2228
-            return null;
2229
-        }
2230
-        return $payment_method;
2231
-    }
2232
-
2233
-
2234
-    /**
2235
-     *    _attempt_payment
2236
-     *
2237
-     * @access    private
2238
-     * @type    EE_Payment_Method $payment_method
2239
-     * @return mixed EE_Payment | boolean
2240
-     * @throws EE_Error
2241
-     * @throws InvalidArgumentException
2242
-     * @throws ReflectionException
2243
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2244
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2245
-     */
2246
-    private function _attempt_payment(EE_Payment_Method $payment_method)
2247
-    {
2248
-        $payment = null;
2249
-        $this->checkout->transaction->save();
2250
-        $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2251
-        if (! $payment_processor instanceof EE_Payment_Processor) {
2252
-            return false;
2253
-        }
2254
-        try {
2255
-            $payment_processor->set_revisit($this->checkout->revisit);
2256
-            // generate payment object
2257
-            $payment = $payment_processor->process_payment(
2258
-                $payment_method,
2259
-                $this->checkout->transaction,
2260
-                $this->checkout->amount_owing,
2261
-                $this->checkout->billing_form,
2262
-                $this->_get_return_url($payment_method),
2263
-                'CART',
2264
-                $this->checkout->admin_request,
2265
-                true,
2266
-                $this->reg_step_url()
2267
-            );
2268
-        } catch (Exception $e) {
2269
-            $this->_handle_payment_processor_exception($e);
2270
-        }
2271
-        return $payment;
2272
-    }
2273
-
2274
-
2275
-    /**
2276
-     * _handle_payment_processor_exception
2277
-     *
2278
-     * @access protected
2279
-     * @param \Exception $e
2280
-     * @return void
2281
-     * @throws EE_Error
2282
-     * @throws InvalidArgumentException
2283
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2284
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2285
-     */
2286
-    protected function _handle_payment_processor_exception(Exception $e)
2287
-    {
2288
-        EE_Error::add_error(
2289
-            sprintf(
2290
-                esc_html__(
2291
-                    'The payment could not br processed due to a technical issue.%1$sPlease try again or contact %2$s for assistance.||The following Exception was thrown in %4$s on line %5$s:%1$s%3$s',
2292
-                    'event_espresso'
2293
-                ),
2294
-                '<br/>',
2295
-                EE_Registry::instance()->CFG->organization->get_pretty('email'),
2296
-                $e->getMessage(),
2297
-                $e->getFile(),
2298
-                $e->getLine()
2299
-            ),
2300
-            __FILE__,
2301
-            __FUNCTION__,
2302
-            __LINE__
2303
-        );
2304
-    }
2305
-
2306
-
2307
-    /**
2308
-     * _get_return_url
2309
-     *
2310
-     * @access protected
2311
-     * @param \EE_Payment_Method $payment_method
2312
-     * @return string
2313
-     * @throws \EE_Error
2314
-     */
2315
-    protected function _get_return_url(EE_Payment_Method $payment_method)
2316
-    {
2317
-        $return_url = '';
2318
-        switch ($payment_method->type_obj()->payment_occurs()) {
2319
-            case EE_PMT_Base::offsite:
2320
-                $return_url = add_query_arg(
2321
-                    array(
2322
-                        'action'                     => 'process_gateway_response',
2323
-                        'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2324
-                        'spco_txn'                   => $this->checkout->transaction->ID(),
2325
-                    ),
2326
-                    $this->reg_step_url()
2327
-                );
2328
-                break;
2329
-            case EE_PMT_Base::onsite:
2330
-            case EE_PMT_Base::offline:
2331
-                $return_url = $this->checkout->next_step->reg_step_url();
2332
-                break;
2333
-        }
2334
-        return $return_url;
2335
-    }
2336
-
2337
-
2338
-    /**
2339
-     * _validate_payment
2340
-     *
2341
-     * @access private
2342
-     * @param EE_Payment $payment
2343
-     * @return EE_Payment|FALSE
2344
-     * @throws EE_Error
2345
-     * @throws InvalidArgumentException
2346
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2347
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2348
-     */
2349
-    private function _validate_payment($payment = null)
2350
-    {
2351
-        if ($this->checkout->payment_method->is_off_line()) {
2352
-            return true;
2353
-        }
2354
-        // verify payment object
2355
-        if (! $payment instanceof EE_Payment) {
2356
-            // not a payment
2357
-            EE_Error::add_error(
2358
-                sprintf(
2359
-                    esc_html__(
2360
-                        'A valid payment was not generated due to a technical issue.%1$sPlease try again or contact %2$s for assistance.',
2361
-                        'event_espresso'
2362
-                    ),
2363
-                    '<br/>',
2364
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2365
-                ),
2366
-                __FILE__,
2367
-                __FUNCTION__,
2368
-                __LINE__
2369
-            );
2370
-            return false;
2371
-        }
2372
-        return $payment;
2373
-    }
2374
-
2375
-
2376
-    /**
2377
-     * _post_payment_processing
2378
-     *
2379
-     * @access private
2380
-     * @param EE_Payment|bool $payment
2381
-     * @return bool
2382
-     * @throws EE_Error
2383
-     * @throws InvalidArgumentException
2384
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2385
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2386
-     */
2387
-    private function _post_payment_processing($payment = null)
2388
-    {
2389
-        // Off-Line payment?
2390
-        if ($payment === true) {
2391
-            // $this->_setup_redirect_for_next_step();
2392
-            return true;
2393
-            // On-Site payment?
2394
-        } elseif ($this->checkout->payment_method->is_on_site()) {
2395
-            if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2396
-                // $this->_setup_redirect_for_next_step();
2397
-                $this->checkout->continue_reg = false;
2398
-            }
2399
-            // Off-Site payment?
2400
-        } elseif ($this->checkout->payment_method->is_off_site()) {
2401
-            // if a payment object was made and it specifies a redirect url, then we'll setup that redirect info
2402
-            if ($payment instanceof EE_Payment && $payment->redirect_url()) {
2403
-                do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()');
2404
-                $this->checkout->redirect = true;
2405
-                $this->checkout->redirect_form = $payment->redirect_form();
2406
-                $this->checkout->redirect_url = $this->reg_step_url('redirect_form');
2407
-                // set JSON response
2408
-                $this->checkout->json_response->set_redirect_form($this->checkout->redirect_form);
2409
-                // and lastly, let's bump the payment status to pending
2410
-                $payment->set_status(EEM_Payment::status_id_pending);
2411
-                $payment->save();
2412
-            } else {
2413
-                // not a payment
2414
-                $this->checkout->continue_reg = false;
2415
-                EE_Error::add_error(
2416
-                    sprintf(
2417
-                        esc_html__(
2418
-                            'It appears the Off Site Payment Method was not configured properly.%sPlease try again or contact %s for assistance.',
2419
-                            'event_espresso'
2420
-                        ),
2421
-                        '<br/>',
2422
-                        EE_Registry::instance()->CFG->organization->get_pretty('email')
2423
-                    ),
2424
-                    __FILE__,
2425
-                    __FUNCTION__,
2426
-                    __LINE__
2427
-                );
2428
-            }
2429
-        } else {
2430
-            // ummm ya... not Off-Line, not On-Site, not off-Site ????
2431
-            $this->checkout->continue_reg = false;
2432
-            return false;
2433
-        }
2434
-        return $payment;
2435
-    }
2436
-
2437
-
2438
-    /**
2439
-     *    _process_payment_status
2440
-     *
2441
-     * @access private
2442
-     * @type    EE_Payment $payment
2443
-     * @param string       $payment_occurs
2444
-     * @return bool
2445
-     * @throws EE_Error
2446
-     * @throws InvalidArgumentException
2447
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2448
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2449
-     */
2450
-    private function _process_payment_status($payment, $payment_occurs = EE_PMT_Base::offline)
2451
-    {
2452
-        // off-line payment? carry on
2453
-        if ($payment_occurs === EE_PMT_Base::offline) {
2454
-            return true;
2455
-        }
2456
-        // verify payment validity
2457
-        if ($payment instanceof EE_Payment) {
2458
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()');
2459
-            $msg = $payment->gateway_response();
2460
-            // check results
2461
-            switch ($payment->status()) {
2462
-                // good payment
2463
-                case EEM_Payment::status_id_approved:
2464
-                    EE_Error::add_success(
2465
-                        esc_html__('Your payment was processed successfully.', 'event_espresso'),
2466
-                        __FILE__,
2467
-                        __FUNCTION__,
2468
-                        __LINE__
2469
-                    );
2470
-                    return true;
2471
-                    break;
2472
-                // slow payment
2473
-                case EEM_Payment::status_id_pending:
2474
-                    if (empty($msg)) {
2475
-                        $msg = esc_html__(
2476
-                            'Your payment appears to have been processed successfully, but the Instant Payment Notification has not yet been received. It should arrive shortly.',
2477
-                            'event_espresso'
2478
-                        );
2479
-                    }
2480
-                    EE_Error::add_success($msg, __FILE__, __FUNCTION__, __LINE__);
2481
-                    return true;
2482
-                    break;
2483
-                // don't wanna payment
2484
-                case EEM_Payment::status_id_cancelled:
2485
-                    if (empty($msg)) {
2486
-                        $msg = _n(
2487
-                            'Payment cancelled. Please try again.',
2488
-                            'Payment cancelled. Please try again or select another method of payment.',
2489
-                            count($this->checkout->available_payment_methods),
2490
-                            'event_espresso'
2491
-                        );
2492
-                    }
2493
-                    EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2494
-                    return false;
2495
-                    break;
2496
-                // not enough payment
2497
-                case EEM_Payment::status_id_declined:
2498
-                    if (empty($msg)) {
2499
-                        $msg = _n(
2500
-                            'We\'re sorry but your payment was declined. Please try again.',
2501
-                            'We\'re sorry but your payment was declined. Please try again or select another method of payment.',
2502
-                            count($this->checkout->available_payment_methods),
2503
-                            'event_espresso'
2504
-                        );
2505
-                    }
2506
-                    EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2507
-                    return false;
2508
-                    break;
2509
-                // bad payment
2510
-                case EEM_Payment::status_id_failed:
2511
-                    if (! empty($msg)) {
2512
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2513
-                        return false;
2514
-                    }
2515
-                    // default to error below
2516
-                    break;
2517
-            }
2518
-        }
2519
-        // off-site payment gateway responses are too unreliable, so let's just assume that
2520
-        // the payment processing is just running slower than the registrant's request
2521
-        if ($payment_occurs === EE_PMT_Base::offsite) {
2522
-            return true;
2523
-        }
2524
-        EE_Error::add_error(
2525
-            sprintf(
2526
-                esc_html__(
2527
-                    'Your payment could not be processed successfully due to a technical issue.%sPlease try again or contact %s for assistance.',
2528
-                    'event_espresso'
2529
-                ),
2530
-                '<br/>',
2531
-                EE_Registry::instance()->CFG->organization->get_pretty('email')
2532
-            ),
2533
-            __FILE__,
2534
-            __FUNCTION__,
2535
-            __LINE__
2536
-        );
2537
-        return false;
2538
-    }
2539
-
2540
-
2541
-
2542
-
2543
-
2544
-
2545
-    /********************************************************************************************************/
2546
-    /**********************************  PROCESS GATEWAY RESPONSE  **********************************/
2547
-    /********************************************************************************************************/
2548
-    /**
2549
-     * process_gateway_response
2550
-     * this is the return point for Off-Site Payment Methods
2551
-     * It will attempt to "handle the IPN" if it appears that this has not already occurred,
2552
-     * otherwise, it will load up the last payment made for the TXN.
2553
-     * If the payment retrieved looks good, it will then either:
2554
-     *    complete the current step and allow advancement to the next reg step
2555
-     *        or present the payment options again
2556
-     *
2557
-     * @access private
2558
-     * @return EE_Payment|FALSE
2559
-     * @throws EE_Error
2560
-     * @throws InvalidArgumentException
2561
-     * @throws ReflectionException
2562
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2563
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2564
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2565
-     */
2566
-    public function process_gateway_response()
2567
-    {
2568
-        $payment = null;
2569
-        // how have they chosen to pay?
2570
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2571
-        // get EE_Payment_Method object
2572
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2573
-            $this->checkout->continue_reg = false;
2574
-            return false;
2575
-        }
2576
-        if (! $this->checkout->payment_method->is_off_site()) {
2577
-            return false;
2578
-        }
2579
-        $this->_validate_offsite_return();
2580
-        // DEBUG LOG
2581
-        // $this->checkout->log(
2582
-        //     __CLASS__,
2583
-        //     __FUNCTION__,
2584
-        //     __LINE__,
2585
-        //     array(
2586
-        //         'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2587
-        //         'payment_method'             => $this->checkout->payment_method,
2588
-        //     ),
2589
-        //     true
2590
-        // );
2591
-        // verify TXN
2592
-        if ($this->checkout->transaction instanceof EE_Transaction) {
2593
-            $gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2594
-            if (! $gateway instanceof EE_Offsite_Gateway) {
2595
-                $this->checkout->continue_reg = false;
2596
-                return false;
2597
-            }
2598
-            $payment = $this->_process_off_site_payment($gateway);
2599
-            $payment = $this->_process_cancelled_payments($payment);
2600
-            $payment = $this->_validate_payment($payment);
2601
-            // if payment was not declined by the payment gateway or cancelled by the registrant
2602
-            if ($this->_process_payment_status($payment, EE_PMT_Base::offsite)) {
2603
-                // $this->_setup_redirect_for_next_step();
2604
-                // store that for later
2605
-                $this->checkout->payment = $payment;
2606
-                // mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2607
-                // because we will complete this step during the IPN processing then
2608
-                if ($gateway instanceof EE_Offsite_Gateway && ! $this->handle_IPN_in_this_request()) {
2609
-                    $this->set_completed();
2610
-                }
2611
-                return true;
2612
-            }
2613
-        }
2614
-        // DEBUG LOG
2615
-        // $this->checkout->log(
2616
-        //     __CLASS__,
2617
-        //     __FUNCTION__,
2618
-        //     __LINE__,
2619
-        //     array('payment' => $payment)
2620
-        // );
2621
-        $this->checkout->continue_reg = false;
2622
-        return false;
2623
-    }
2624
-
2625
-
2626
-    /**
2627
-     * _validate_return
2628
-     *
2629
-     * @access private
2630
-     * @return void
2631
-     * @throws EE_Error
2632
-     * @throws InvalidArgumentException
2633
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2634
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2635
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2636
-     */
2637
-    private function _validate_offsite_return()
2638
-    {
2639
-        $TXN_ID = (int) EE_Registry::instance()->REQ->get('spco_txn', 0);
2640
-        if ($TXN_ID !== $this->checkout->transaction->ID()) {
2641
-            // Houston... we might have a problem
2642
-            $invalid_TXN = false;
2643
-            // first gather some info
2644
-            $valid_TXN = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2645
-            $primary_registrant = $valid_TXN instanceof EE_Transaction
2646
-                ? $valid_TXN->primary_registration()
2647
-                : null;
2648
-            // let's start by retrieving the cart for this TXN
2649
-            $cart = $this->checkout->get_cart_for_transaction($this->checkout->transaction);
2650
-            if ($cart instanceof EE_Cart) {
2651
-                // verify that the current cart has tickets
2652
-                $tickets = $cart->get_tickets();
2653
-                if (empty($tickets)) {
2654
-                    $invalid_TXN = true;
2655
-                }
2656
-            } else {
2657
-                $invalid_TXN = true;
2658
-            }
2659
-            $valid_TXN_SID = $primary_registrant instanceof EE_Registration
2660
-                ? $primary_registrant->session_ID()
2661
-                : null;
2662
-            // validate current Session ID and compare against valid TXN session ID
2663
-            if ($invalid_TXN // if this is already true, then skip other checks
2664
-                || EE_Session::instance()->id() === null
2665
-                || (
2666
-                    // WARNING !!!
2667
-                    // this could be PayPal sending back duplicate requests (ya they do that)
2668
-                    // or it **could** mean someone is simply registering AGAIN after having just done so
2669
-                    // so now we need to determine if this current TXN looks valid or not
2670
-                    // and whether this reg step has even been started ?
2671
-                    EE_Session::instance()->id() === $valid_TXN_SID
2672
-                    // really? you're half way through this reg step, but you never started it ?
2673
-                    && $this->checkout->transaction->reg_step_completed($this->slug()) === false
2674
-                )
2675
-            ) {
2676
-                $invalid_TXN = true;
2677
-            }
2678
-            if ($invalid_TXN) {
2679
-                // is the valid TXN completed ?
2680
-                if ($valid_TXN instanceof EE_Transaction) {
2681
-                    // has this step even been started ?
2682
-                    $reg_step_completed = $valid_TXN->reg_step_completed($this->slug());
2683
-                    if ($reg_step_completed !== false && $reg_step_completed !== true) {
2684
-                        // so it **looks** like this is a double request from PayPal
2685
-                        // so let's try to pick up where we left off
2686
-                        $this->checkout->transaction = $valid_TXN;
2687
-                        $this->checkout->refresh_all_entities(true);
2688
-                        return;
2689
-                    }
2690
-                }
2691
-                // you appear to be lost?
2692
-                $this->_redirect_wayward_request($primary_registrant);
2693
-            }
2694
-        }
2695
-    }
2696
-
2697
-
2698
-    /**
2699
-     * _redirect_wayward_request
2700
-     *
2701
-     * @access private
2702
-     * @param \EE_Registration|null $primary_registrant
2703
-     * @return bool
2704
-     * @throws EE_Error
2705
-     * @throws InvalidArgumentException
2706
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2707
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2708
-     */
2709
-    private function _redirect_wayward_request(EE_Registration $primary_registrant)
2710
-    {
2711
-        if (! $primary_registrant instanceof EE_Registration) {
2712
-            // try redirecting based on the current TXN
2713
-            $primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2714
-                ? $this->checkout->transaction->primary_registration()
2715
-                : null;
2716
-        }
2717
-        if (! $primary_registrant instanceof EE_Registration) {
2718
-            EE_Error::add_error(
2719
-                sprintf(
2720
-                    esc_html__(
2721
-                        'Invalid information was received from the Off-Site Payment Processor and your Transaction details could not be retrieved from the database.%1$sPlease try again or contact %2$s for assistance.',
2722
-                        'event_espresso'
2723
-                    ),
2724
-                    '<br/>',
2725
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2726
-                ),
2727
-                __FILE__,
2728
-                __FUNCTION__,
2729
-                __LINE__
2730
-            );
2731
-            return false;
2732
-        }
2733
-        // make sure transaction is not locked
2734
-        $this->checkout->transaction->unlock();
2735
-        wp_safe_redirect(
2736
-            add_query_arg(
2737
-                array(
2738
-                    'e_reg_url_link' => $primary_registrant->reg_url_link(),
2739
-                ),
2740
-                $this->checkout->thank_you_page_url
2741
-            )
2742
-        );
2743
-        exit();
2744
-    }
2745
-
2746
-
2747
-    /**
2748
-     * _process_off_site_payment
2749
-     *
2750
-     * @access private
2751
-     * @param \EE_Offsite_Gateway $gateway
2752
-     * @return EE_Payment
2753
-     * @throws EE_Error
2754
-     * @throws InvalidArgumentException
2755
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2756
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2757
-     */
2758
-    private function _process_off_site_payment(EE_Offsite_Gateway $gateway)
2759
-    {
2760
-        try {
2761
-            $request_data = \EE_Registry::instance()->REQ->params();
2762
-            // if gateway uses_separate_IPN_request, then we don't have to process the IPN manually
2763
-            $this->set_handle_IPN_in_this_request(
2764
-                $gateway->handle_IPN_in_this_request($request_data, false)
2765
-            );
2766
-            if ($this->handle_IPN_in_this_request()) {
2767
-                // get payment details and process results
2768
-                /** @type EE_Payment_Processor $payment_processor */
2769
-                $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2770
-                $payment = $payment_processor->process_ipn(
2771
-                    $request_data,
2772
-                    $this->checkout->transaction,
2773
-                    $this->checkout->payment_method,
2774
-                    true,
2775
-                    false
2776
-                );
2777
-                // $payment_source = 'process_ipn';
2778
-            } else {
2779
-                $payment = $this->checkout->transaction->last_payment();
2780
-                // $payment_source = 'last_payment';
2781
-            }
2782
-        } catch (Exception $e) {
2783
-            // let's just eat the exception and try to move on using any previously set payment info
2784
-            $payment = $this->checkout->transaction->last_payment();
2785
-            // $payment_source = 'last_payment after Exception';
2786
-            // but if we STILL don't have a payment object
2787
-            if (! $payment instanceof EE_Payment) {
2788
-                // then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2789
-                $this->_handle_payment_processor_exception($e);
2790
-            }
2791
-        }
2792
-        // DEBUG LOG
2793
-        // $this->checkout->log(
2794
-        //     __CLASS__,
2795
-        //     __FUNCTION__,
2796
-        //     __LINE__,
2797
-        //     array(
2798
-        //         'process_ipn_payment' => $payment,
2799
-        //         'payment_source'      => $payment_source,
2800
-        //     )
2801
-        // );
2802
-        return $payment;
2803
-    }
2804
-
2805
-
2806
-    /**
2807
-     * _process_cancelled_payments
2808
-     * just makes sure that the payment status gets updated correctly
2809
-     * so tha tan error isn't generated during payment validation
2810
-     *
2811
-     * @access private
2812
-     * @param EE_Payment $payment
2813
-     * @return EE_Payment | FALSE
2814
-     * @throws \EE_Error
2815
-     */
2816
-    private function _process_cancelled_payments($payment = null)
2817
-    {
2818
-        if ($payment instanceof EE_Payment
2819
-            && isset($_REQUEST['ee_cancel_payment'])
2820
-            && $payment->status() === EEM_Payment::status_id_failed
2821
-        ) {
2822
-            $payment->set_status(EEM_Payment::status_id_cancelled);
2823
-        }
2824
-        return $payment;
2825
-    }
2826
-
2827
-
2828
-    /**
2829
-     *    get_transaction_details_for_gateways
2830
-     *
2831
-     * @access    public
2832
-     * @return int
2833
-     * @throws EE_Error
2834
-     * @throws InvalidArgumentException
2835
-     * @throws ReflectionException
2836
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2837
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2838
-     */
2839
-    public function get_transaction_details_for_gateways()
2840
-    {
2841
-        $txn_details = array();
2842
-        // ya gotta make a choice man
2843
-        if (empty($this->checkout->selected_method_of_payment)) {
2844
-            $txn_details = array(
2845
-                'error' => esc_html__('Please select a method of payment before proceeding.', 'event_espresso'),
2846
-            );
2847
-        }
2848
-        // get EE_Payment_Method object
2849
-        if (empty($txn_details)
2850
-            &&
2851
-            ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()
2852
-        ) {
2853
-            $txn_details = array(
2854
-                'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2855
-                'error'                      => esc_html__(
2856
-                    'A valid Payment Method could not be determined.',
2857
-                    'event_espresso'
2858
-                ),
2859
-            );
2860
-        }
2861
-        if (empty($txn_details) && $this->checkout->transaction instanceof EE_Transaction) {
2862
-            $return_url = $this->_get_return_url($this->checkout->payment_method);
2863
-            $txn_details = array(
2864
-                'TXN_ID'         => $this->checkout->transaction->ID(),
2865
-                'TXN_timestamp'  => $this->checkout->transaction->datetime(),
2866
-                'TXN_total'      => $this->checkout->transaction->total(),
2867
-                'TXN_paid'       => $this->checkout->transaction->paid(),
2868
-                'TXN_reg_steps'  => $this->checkout->transaction->reg_steps(),
2869
-                'STS_ID'         => $this->checkout->transaction->status_ID(),
2870
-                'PMD_ID'         => $this->checkout->transaction->payment_method_ID(),
2871
-                'payment_amount' => $this->checkout->amount_owing,
2872
-                'return_url'     => $return_url,
2873
-                'cancel_url'     => add_query_arg(array('ee_cancel_payment' => true), $return_url),
2874
-                'notify_url'     => EE_Config::instance()->core->txn_page_url(
2875
-                    array(
2876
-                        'e_reg_url_link'    => $this->checkout->transaction->primary_registration()->reg_url_link(),
2877
-                        'ee_payment_method' => $this->checkout->payment_method->slug(),
2878
-                    )
2879
-                ),
2880
-            );
2881
-        }
2882
-        echo wp_json_encode($txn_details);
2883
-        exit();
2884
-    }
2885
-
2886
-
2887
-    /**
2888
-     *    __sleep
2889
-     * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon
2890
-     * serialization EE_Checkout will handle the reimplementation of itself upon waking, but we won't bother with the
2891
-     * reg form, because if needed, it will be regenerated anyways
2892
-     *
2893
-     * @return array
2894
-     */
2895
-    public function __sleep()
2896
-    {
2897
-        // remove the reg form and the checkout
2898
-        return array_diff(array_keys(get_object_vars($this)), array('reg_form', 'checkout', 'line_item_display'));
2899
-    }
15
+	/**
16
+	 * @access protected
17
+	 * @var EE_Line_Item_Display $Line_Item_Display
18
+	 */
19
+	protected $line_item_display;
20
+
21
+	/**
22
+	 * @access protected
23
+	 * @var boolean $handle_IPN_in_this_request
24
+	 */
25
+	protected $handle_IPN_in_this_request = false;
26
+
27
+
28
+	/**
29
+	 *    set_hooks - for hooking into EE Core, other modules, etc
30
+	 *
31
+	 * @access    public
32
+	 * @return    void
33
+	 */
34
+	public static function set_hooks()
35
+	{
36
+		add_filter(
37
+			'FHEE__SPCO__EE_Line_Item_Filter_Collection',
38
+			array('EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters')
39
+		);
40
+		add_action(
41
+			'wp_ajax_switch_spco_billing_form',
42
+			array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
43
+		);
44
+		add_action(
45
+			'wp_ajax_nopriv_switch_spco_billing_form',
46
+			array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
47
+		);
48
+		add_action('wp_ajax_save_payer_details', array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details'));
49
+		add_action(
50
+			'wp_ajax_nopriv_save_payer_details',
51
+			array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details')
52
+		);
53
+		add_action(
54
+			'wp_ajax_get_transaction_details_for_gateways',
55
+			array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
56
+		);
57
+		add_action(
58
+			'wp_ajax_nopriv_get_transaction_details_for_gateways',
59
+			array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
60
+		);
61
+		add_filter(
62
+			'FHEE__EED_Recaptcha___bypass_recaptcha__bypass_request_params_array',
63
+			array('EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method'),
64
+			10,
65
+			1
66
+		);
67
+	}
68
+
69
+
70
+	/**
71
+	 *    ajax switch_spco_billing_form
72
+	 *
73
+	 * @throws \EE_Error
74
+	 */
75
+	public static function switch_spco_billing_form()
76
+	{
77
+		EED_Single_Page_Checkout::process_ajax_request('switch_payment_method');
78
+	}
79
+
80
+
81
+	/**
82
+	 *    ajax save_payer_details
83
+	 *
84
+	 * @throws \EE_Error
85
+	 */
86
+	public static function save_payer_details()
87
+	{
88
+		EED_Single_Page_Checkout::process_ajax_request('save_payer_details_via_ajax');
89
+	}
90
+
91
+
92
+	/**
93
+	 *    ajax get_transaction_details
94
+	 *
95
+	 * @throws \EE_Error
96
+	 */
97
+	public static function get_transaction_details()
98
+	{
99
+		EED_Single_Page_Checkout::process_ajax_request('get_transaction_details_for_gateways');
100
+	}
101
+
102
+
103
+	/**
104
+	 * bypass_recaptcha_for_load_payment_method
105
+	 *
106
+	 * @access public
107
+	 * @return array
108
+	 * @throws InvalidArgumentException
109
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
110
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
111
+	 */
112
+	public static function bypass_recaptcha_for_load_payment_method()
113
+	{
114
+		return array(
115
+			'EESID'  => EE_Registry::instance()->SSN->id(),
116
+			'step'   => 'payment_options',
117
+			'action' => 'spco_billing_form',
118
+		);
119
+	}
120
+
121
+
122
+	/**
123
+	 *    class constructor
124
+	 *
125
+	 * @access    public
126
+	 * @param    EE_Checkout $checkout
127
+	 */
128
+	public function __construct(EE_Checkout $checkout)
129
+	{
130
+		$this->_slug = 'payment_options';
131
+		$this->_name = esc_html__('Payment Options', 'event_espresso');
132
+		$this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
133
+		$this->checkout = $checkout;
134
+		$this->_reset_success_message();
135
+		$this->set_instructions(
136
+			esc_html__(
137
+				'Please select a method of payment and provide any necessary billing information before proceeding.',
138
+				'event_espresso'
139
+			)
140
+		);
141
+	}
142
+
143
+
144
+	/**
145
+	 * @return null
146
+	 */
147
+	public function line_item_display()
148
+	{
149
+		return $this->line_item_display;
150
+	}
151
+
152
+
153
+	/**
154
+	 * @param null $line_item_display
155
+	 */
156
+	public function set_line_item_display($line_item_display)
157
+	{
158
+		$this->line_item_display = $line_item_display;
159
+	}
160
+
161
+
162
+	/**
163
+	 * @return boolean
164
+	 */
165
+	public function handle_IPN_in_this_request()
166
+	{
167
+		return $this->handle_IPN_in_this_request;
168
+	}
169
+
170
+
171
+	/**
172
+	 * @param boolean $handle_IPN_in_this_request
173
+	 */
174
+	public function set_handle_IPN_in_this_request($handle_IPN_in_this_request)
175
+	{
176
+		$this->handle_IPN_in_this_request = filter_var($handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN);
177
+	}
178
+
179
+
180
+	/**
181
+	 * translate_js_strings
182
+	 *
183
+	 * @return void
184
+	 */
185
+	public function translate_js_strings()
186
+	{
187
+		EE_Registry::$i18n_js_strings['no_payment_method'] = esc_html__(
188
+			'Please select a method of payment in order to continue.',
189
+			'event_espresso'
190
+		);
191
+		EE_Registry::$i18n_js_strings['invalid_payment_method'] = esc_html__(
192
+			'A valid method of payment could not be determined. Please refresh the page and try again.',
193
+			'event_espresso'
194
+		);
195
+		EE_Registry::$i18n_js_strings['forwarding_to_offsite'] = esc_html__(
196
+			'Forwarding to Secure Payment Provider.',
197
+			'event_espresso'
198
+		);
199
+	}
200
+
201
+
202
+	/**
203
+	 * enqueue_styles_and_scripts
204
+	 *
205
+	 * @return void
206
+	 * @throws EE_Error
207
+	 * @throws InvalidArgumentException
208
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
209
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
210
+	 */
211
+	public function enqueue_styles_and_scripts()
212
+	{
213
+		$transaction = $this->checkout->transaction;
214
+		// if the transaction isn't set or nothing is owed on it, don't enqueue any JS
215
+		if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
216
+			return;
217
+		}
218
+		foreach (EEM_Payment_Method::instance()->get_all_for_transaction(
219
+			$transaction,
220
+			EEM_Payment_Method::scope_cart
221
+		) as $payment_method) {
222
+			$type_obj = $payment_method->type_obj();
223
+			if ($type_obj instanceof EE_PMT_Base) {
224
+				$billing_form = $type_obj->generate_new_billing_form($transaction);
225
+				if ($billing_form instanceof EE_Form_Section_Proper) {
226
+					$billing_form->enqueue_js();
227
+				}
228
+			}
229
+		}
230
+	}
231
+
232
+
233
+	/**
234
+	 * initialize_reg_step
235
+	 *
236
+	 * @return bool
237
+	 * @throws EE_Error
238
+	 * @throws InvalidArgumentException
239
+	 * @throws ReflectionException
240
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
241
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
242
+	 */
243
+	public function initialize_reg_step()
244
+	{
245
+		// TODO: if /when we implement donations, then this will need overriding
246
+		if (// don't need payment options for:
247
+			// registrations made via the admin
248
+			// completed transactions
249
+			// overpaid transactions
250
+			// $ 0.00 transactions(no payment required)
251
+			! $this->checkout->payment_required()
252
+			// but do NOT remove if current action being called belongs to this reg step
253
+			&& ! is_callable(array($this, $this->checkout->action))
254
+			&& ! $this->completed()
255
+		) {
256
+			// and if so, then we no longer need the Payment Options step
257
+			if ($this->is_current_step()) {
258
+				$this->checkout->generate_reg_form = false;
259
+			}
260
+			$this->checkout->remove_reg_step($this->_slug);
261
+			// DEBUG LOG
262
+			// $this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
263
+			return false;
264
+		}
265
+		// load EEM_Payment_Method
266
+		EE_Registry::instance()->load_model('Payment_Method');
267
+		// get all active payment methods
268
+		$this->checkout->available_payment_methods = EEM_Payment_Method::instance()->get_all_for_transaction(
269
+			$this->checkout->transaction,
270
+			EEM_Payment_Method::scope_cart
271
+		);
272
+		return true;
273
+	}
274
+
275
+
276
+	/**
277
+	 * @return EE_Form_Section_Proper
278
+	 * @throws EE_Error
279
+	 * @throws InvalidArgumentException
280
+	 * @throws ReflectionException
281
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
282
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
283
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
284
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
285
+	 */
286
+	public function generate_reg_form()
287
+	{
288
+		// reset in case someone changes their mind
289
+		$this->_reset_selected_method_of_payment();
290
+		// set some defaults
291
+		$this->checkout->selected_method_of_payment = 'payments_closed';
292
+		$registrations_requiring_payment = array();
293
+		$registrations_for_free_events = array();
294
+		$registrations_requiring_pre_approval = array();
295
+		$sold_out_events = array();
296
+		$insufficient_spaces_available = array();
297
+		$no_payment_required = true;
298
+		// loop thru registrations to gather info
299
+		$registrations = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
300
+		$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
301
+			$registrations,
302
+			$this->checkout->revisit
303
+		);
304
+		foreach ($registrations as $REG_ID => $registration) {
305
+			/** @var $registration EE_Registration */
306
+			// has this registration lost it's space ?
307
+			if (isset($ejected_registrations[ $REG_ID ])) {
308
+				if ($registration->event()->is_sold_out() || $registration->event()->is_sold_out(true)) {
309
+					$sold_out_events[ $registration->event()->ID() ] = $registration->event();
310
+				} else {
311
+					$insufficient_spaces_available[ $registration->event()->ID() ] = $registration->event();
312
+				}
313
+				continue;
314
+			}
315
+			// event requires admin approval
316
+			if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
317
+				// add event to list of events with pre-approval reg status
318
+				$registrations_requiring_pre_approval[ $REG_ID ] = $registration;
319
+				do_action(
320
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
321
+					$registration->event(),
322
+					$this
323
+				);
324
+				continue;
325
+			}
326
+			if ($this->checkout->revisit
327
+				&& $registration->status_ID() !== EEM_Registration::status_id_approved
328
+				&& (
329
+					$registration->event()->is_sold_out()
330
+					|| $registration->event()->is_sold_out(true)
331
+				)
332
+			) {
333
+				// add event to list of events that are sold out
334
+				$sold_out_events[ $registration->event()->ID() ] = $registration->event();
335
+				do_action(
336
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
337
+					$registration->event(),
338
+					$this
339
+				);
340
+				continue;
341
+			}
342
+			// are they allowed to pay now and is there monies owing?
343
+			if ($registration->owes_monies_and_can_pay()) {
344
+				$registrations_requiring_payment[ $REG_ID ] = $registration;
345
+				do_action(
346
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
347
+					$registration->event(),
348
+					$this
349
+				);
350
+			} elseif (! $this->checkout->revisit
351
+					  && $registration->status_ID() !== EEM_Registration::status_id_not_approved
352
+					  && $registration->ticket()->is_free()
353
+			) {
354
+				$registrations_for_free_events[ $registration->event()->ID() ] = $registration;
355
+			}
356
+		}
357
+		$subsections = array();
358
+		// now decide which template to load
359
+		if (! empty($sold_out_events)) {
360
+			$subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
361
+		}
362
+		if (! empty($insufficient_spaces_available)) {
363
+			$subsections['insufficient_space'] = $this->_insufficient_spaces_available(
364
+				$insufficient_spaces_available
365
+			);
366
+		}
367
+		if (! empty($registrations_requiring_pre_approval)) {
368
+			$subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
369
+				$registrations_requiring_pre_approval
370
+			);
371
+		}
372
+		if (! empty($registrations_for_free_events)) {
373
+			$subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
374
+		}
375
+		if (! empty($registrations_requiring_payment)) {
376
+			if ($this->checkout->amount_owing > 0) {
377
+				// autoload Line_Item_Display classes
378
+				EEH_Autoloader::register_line_item_filter_autoloaders();
379
+				$line_item_filter_processor = new EE_Line_Item_Filter_Processor(
380
+					apply_filters(
381
+						'FHEE__SPCO__EE_Line_Item_Filter_Collection',
382
+						new EE_Line_Item_Filter_Collection()
383
+					),
384
+					$this->checkout->cart->get_grand_total()
385
+				);
386
+				/** @var EE_Line_Item $filtered_line_item_tree */
387
+				$filtered_line_item_tree = $line_item_filter_processor->process();
388
+				EEH_Autoloader::register_line_item_display_autoloaders();
389
+				$this->set_line_item_display(new EE_Line_Item_Display('spco'));
390
+				$subsections['payment_options'] = $this->_display_payment_options(
391
+					$this->line_item_display->display_line_item(
392
+						$filtered_line_item_tree,
393
+						array('registrations' => $registrations)
394
+					)
395
+				);
396
+				$this->checkout->amount_owing = $filtered_line_item_tree->total();
397
+				$this->_apply_registration_payments_to_amount_owing($registrations);
398
+			}
399
+			$no_payment_required = false;
400
+		} else {
401
+			$this->_hide_reg_step_submit_button_if_revisit();
402
+		}
403
+		$this->_save_selected_method_of_payment();
404
+
405
+		$subsections['default_hidden_inputs'] = $this->reg_step_hidden_inputs();
406
+		$subsections['extra_hidden_inputs'] = $this->_extra_hidden_inputs($no_payment_required);
407
+
408
+		return new EE_Form_Section_Proper(
409
+			array(
410
+				'name'            => $this->reg_form_name(),
411
+				'html_id'         => $this->reg_form_name(),
412
+				'subsections'     => $subsections,
413
+				'layout_strategy' => new EE_No_Layout(),
414
+			)
415
+		);
416
+	}
417
+
418
+
419
+	/**
420
+	 * add line item filters required for this reg step
421
+	 * these filters are applied via this line in EE_SPCO_Reg_Step_Payment_Options::set_hooks():
422
+	 *        add_filter( 'FHEE__SPCO__EE_Line_Item_Filter_Collection', array( 'EE_SPCO_Reg_Step_Payment_Options',
423
+	 *        'add_spco_line_item_filters' ) ); so any code that wants to use the same set of filters during the
424
+	 *        payment options reg step, can apply these filters via the following: apply_filters(
425
+	 *        'FHEE__SPCO__EE_Line_Item_Filter_Collection', new EE_Line_Item_Filter_Collection() ) or to an existing
426
+	 *        filter collection by passing that instead of instantiating a new collection
427
+	 *
428
+	 * @param \EE_Line_Item_Filter_Collection $line_item_filter_collection
429
+	 * @return EE_Line_Item_Filter_Collection
430
+	 * @throws EE_Error
431
+	 * @throws InvalidArgumentException
432
+	 * @throws ReflectionException
433
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
434
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
435
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
436
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
437
+	 */
438
+	public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
439
+	{
440
+		if (! EE_Registry::instance()->SSN instanceof EE_Session) {
441
+			return $line_item_filter_collection;
442
+		}
443
+		if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
444
+			return $line_item_filter_collection;
445
+		}
446
+		if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
447
+			return $line_item_filter_collection;
448
+		}
449
+		$line_item_filter_collection->add(
450
+			new EE_Billable_Line_Item_Filter(
451
+				EE_SPCO_Reg_Step_Payment_Options::remove_ejected_registrations(
452
+					EE_Registry::instance()->SSN->checkout()->transaction->registrations(
453
+						EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
454
+					)
455
+				)
456
+			)
457
+		);
458
+		$line_item_filter_collection->add(new EE_Non_Zero_Line_Item_Filter());
459
+		return $line_item_filter_collection;
460
+	}
461
+
462
+
463
+	/**
464
+	 * remove_ejected_registrations
465
+	 * if a registrant has lost their potential space at an event due to lack of payment,
466
+	 * then this method removes them from the list of registrations being paid for during this request
467
+	 *
468
+	 * @param \EE_Registration[] $registrations
469
+	 * @return EE_Registration[]
470
+	 * @throws EE_Error
471
+	 * @throws InvalidArgumentException
472
+	 * @throws ReflectionException
473
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
474
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
475
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
476
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
477
+	 */
478
+	public static function remove_ejected_registrations(array $registrations)
479
+	{
480
+		$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
481
+			$registrations,
482
+			EE_Registry::instance()->SSN->checkout()->revisit
483
+		);
484
+		foreach ($registrations as $REG_ID => $registration) {
485
+			// has this registration lost it's space ?
486
+			if (isset($ejected_registrations[ $REG_ID ])) {
487
+				unset($registrations[ $REG_ID ]);
488
+				continue;
489
+			}
490
+		}
491
+		return $registrations;
492
+	}
493
+
494
+
495
+	/**
496
+	 * find_registrations_that_lost_their_space
497
+	 * If a registrant chooses an offline payment method like Invoice,
498
+	 * then no space is reserved for them at the event until they fully pay fo that site
499
+	 * (unless the event's default reg status is set to APPROVED)
500
+	 * if a registrant then later returns to pay, but the number of spaces available has been reduced due to sales,
501
+	 * then this method will determine which registrations have lost the ability to complete the reg process.
502
+	 *
503
+	 * @param \EE_Registration[] $registrations
504
+	 * @param bool               $revisit
505
+	 * @return array
506
+	 * @throws EE_Error
507
+	 * @throws InvalidArgumentException
508
+	 * @throws ReflectionException
509
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
510
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
511
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
512
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
513
+	 */
514
+	public static function find_registrations_that_lost_their_space(array $registrations, $revisit = false)
515
+	{
516
+		// registrations per event
517
+		$event_reg_count = array();
518
+		// spaces left per event
519
+		$event_spaces_remaining = array();
520
+		// tickets left sorted by ID
521
+		$tickets_remaining = array();
522
+		// registrations that have lost their space
523
+		$ejected_registrations = array();
524
+		foreach ($registrations as $REG_ID => $registration) {
525
+			if ($registration->status_ID() === EEM_Registration::status_id_approved
526
+				|| apply_filters(
527
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__find_registrations_that_lost_their_space__allow_reg_payment',
528
+					false,
529
+					$registration,
530
+					$revisit
531
+				)
532
+			) {
533
+				continue;
534
+			}
535
+			$EVT_ID = $registration->event_ID();
536
+			$ticket = $registration->ticket();
537
+			if (! isset($tickets_remaining[ $ticket->ID() ])) {
538
+				$tickets_remaining[ $ticket->ID() ] = $ticket->remaining();
539
+			}
540
+			if ($tickets_remaining[ $ticket->ID() ] > 0) {
541
+				if (! isset($event_reg_count[ $EVT_ID ])) {
542
+					$event_reg_count[ $EVT_ID ] = 0;
543
+				}
544
+				$event_reg_count[ $EVT_ID ]++;
545
+				if (! isset($event_spaces_remaining[ $EVT_ID ])) {
546
+					$event_spaces_remaining[ $EVT_ID ] = $registration->event()->spaces_remaining_for_sale();
547
+				}
548
+			}
549
+			if ($revisit
550
+				&& ($tickets_remaining[ $ticket->ID() ] === 0
551
+					|| $event_reg_count[ $EVT_ID ] > $event_spaces_remaining[ $EVT_ID ]
552
+				)
553
+			) {
554
+				$ejected_registrations[ $REG_ID ] = $registration->event();
555
+				if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
556
+					/** @type EE_Registration_Processor $registration_processor */
557
+					$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
558
+					// at this point, we should have enough details about the registrant to consider the registration
559
+					// NOT incomplete
560
+					$registration_processor->manually_update_registration_status(
561
+						$registration,
562
+						EEM_Registration::status_id_wait_list
563
+					);
564
+				}
565
+			}
566
+		}
567
+		return $ejected_registrations;
568
+	}
569
+
570
+
571
+	/**
572
+	 * _hide_reg_step_submit_button
573
+	 * removes the html for the reg step submit button
574
+	 * by replacing it with an empty string via filter callback
575
+	 *
576
+	 * @return void
577
+	 */
578
+	protected function _adjust_registration_status_if_event_old_sold()
579
+	{
580
+	}
581
+
582
+
583
+	/**
584
+	 * _hide_reg_step_submit_button
585
+	 * removes the html for the reg step submit button
586
+	 * by replacing it with an empty string via filter callback
587
+	 *
588
+	 * @return void
589
+	 */
590
+	protected function _hide_reg_step_submit_button_if_revisit()
591
+	{
592
+		if ($this->checkout->revisit) {
593
+			add_filter('FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string');
594
+		}
595
+	}
596
+
597
+
598
+	/**
599
+	 * sold_out_events
600
+	 * displays notices regarding events that have sold out since hte registrant first signed up
601
+	 *
602
+	 * @param \EE_Event[] $sold_out_events_array
603
+	 * @return \EE_Form_Section_Proper
604
+	 * @throws \EE_Error
605
+	 */
606
+	private function _sold_out_events($sold_out_events_array = array())
607
+	{
608
+		// set some defaults
609
+		$this->checkout->selected_method_of_payment = 'events_sold_out';
610
+		$sold_out_events = '';
611
+		foreach ($sold_out_events_array as $sold_out_event) {
612
+			$sold_out_events .= EEH_HTML::li(
613
+				EEH_HTML::span(
614
+					'  ' . $sold_out_event->name(),
615
+					'',
616
+					'dashicons dashicons-marker ee-icon-size-16 pink-text'
617
+				)
618
+			);
619
+		}
620
+		return new EE_Form_Section_Proper(
621
+			array(
622
+				'layout_strategy' => new EE_Template_Layout(
623
+					array(
624
+						'layout_template_file' => SPCO_REG_STEPS_PATH
625
+												  . $this->_slug
626
+												  . DS
627
+												  . 'sold_out_events.template.php',
628
+						'template_args'        => apply_filters(
629
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
630
+							array(
631
+								'sold_out_events'     => $sold_out_events,
632
+								'sold_out_events_msg' => apply_filters(
633
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__sold_out_events_msg',
634
+									sprintf(
635
+										esc_html__(
636
+											'It appears that the event you were about to make a payment for has sold out since you first registered. If you have already made a partial payment towards this event, please contact the event administrator for a refund.%3$s%3$s%1$sPlease note that availability can change at any time due to cancellations, so please check back again later if registration for this event(s) is important to you.%2$s',
637
+											'event_espresso'
638
+										),
639
+										'<strong>',
640
+										'</strong>',
641
+										'<br />'
642
+									)
643
+								),
644
+							)
645
+						),
646
+					)
647
+				),
648
+			)
649
+		);
650
+	}
651
+
652
+
653
+	/**
654
+	 * _insufficient_spaces_available
655
+	 * displays notices regarding events that do not have enough remaining spaces
656
+	 * to satisfy the current number of registrations looking to pay
657
+	 *
658
+	 * @param \EE_Event[] $insufficient_spaces_events_array
659
+	 * @return \EE_Form_Section_Proper
660
+	 * @throws \EE_Error
661
+	 */
662
+	private function _insufficient_spaces_available($insufficient_spaces_events_array = array())
663
+	{
664
+		// set some defaults
665
+		$this->checkout->selected_method_of_payment = 'invoice';
666
+		$insufficient_space_events = '';
667
+		foreach ($insufficient_spaces_events_array as $event) {
668
+			if ($event instanceof EE_Event) {
669
+				$insufficient_space_events .= EEH_HTML::li(
670
+					EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
671
+				);
672
+			}
673
+		}
674
+		return new EE_Form_Section_Proper(
675
+			array(
676
+				'subsections'     => array(
677
+					'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
678
+					'extra_hidden_inputs'   => $this->_extra_hidden_inputs(),
679
+				),
680
+				'layout_strategy' => new EE_Template_Layout(
681
+					array(
682
+						'layout_template_file' => SPCO_REG_STEPS_PATH
683
+												  . $this->_slug
684
+												  . DS
685
+												  . 'sold_out_events.template.php',
686
+						'template_args'        => apply_filters(
687
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__template_args',
688
+							array(
689
+								'sold_out_events'     => $insufficient_space_events,
690
+								'sold_out_events_msg' => apply_filters(
691
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__insufficient_space_msg',
692
+									esc_html__(
693
+										'It appears that the event you were about to make a payment for has sold additional tickets since you first registered, and there are no longer enough spaces left to accommodate your selections. You may continue to pay and secure the available space(s) remaining, or simply cancel if you no longer wish to purchase. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
694
+										'event_espresso'
695
+									)
696
+								),
697
+							)
698
+						),
699
+					)
700
+				),
701
+			)
702
+		);
703
+	}
704
+
705
+
706
+	/**
707
+	 * registrations_requiring_pre_approval
708
+	 *
709
+	 * @param array $registrations_requiring_pre_approval
710
+	 * @return EE_Form_Section_Proper
711
+	 * @throws EE_Error
712
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
713
+	 */
714
+	private function _registrations_requiring_pre_approval($registrations_requiring_pre_approval = array())
715
+	{
716
+		$events_requiring_pre_approval = '';
717
+		foreach ($registrations_requiring_pre_approval as $registration) {
718
+			if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
719
+				$events_requiring_pre_approval[ $registration->event()->ID() ] = EEH_HTML::li(
720
+					EEH_HTML::span(
721
+						'',
722
+						'',
723
+						'dashicons dashicons-marker ee-icon-size-16 orange-text'
724
+					)
725
+					. EEH_HTML::span($registration->event()->name(), '', 'orange-text')
726
+				);
727
+			}
728
+		}
729
+		return new EE_Form_Section_Proper(
730
+			array(
731
+				'layout_strategy' => new EE_Template_Layout(
732
+					array(
733
+						'layout_template_file' => SPCO_REG_STEPS_PATH
734
+												  . $this->_slug
735
+												  . DS
736
+												  . 'events_requiring_pre_approval.template.php', // layout_template
737
+						'template_args'        => apply_filters(
738
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
739
+							array(
740
+								'events_requiring_pre_approval'     => implode('', $events_requiring_pre_approval),
741
+								'events_requiring_pre_approval_msg' => apply_filters(
742
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___events_requiring_pre_approval__events_requiring_pre_approval_msg',
743
+									esc_html__(
744
+										'The following events do not require payment at this time and will not be billed during this transaction. Billing will only occur after the attendee has been approved by the event organizer. You will be notified when your registration has been processed. If this is a free event, then no billing will occur.',
745
+										'event_espresso'
746
+									)
747
+								),
748
+							)
749
+						),
750
+					)
751
+				),
752
+			)
753
+		);
754
+	}
755
+
756
+
757
+	/**
758
+	 * _no_payment_required
759
+	 *
760
+	 * @param \EE_Event[] $registrations_for_free_events
761
+	 * @return \EE_Form_Section_Proper
762
+	 * @throws \EE_Error
763
+	 */
764
+	private function _no_payment_required($registrations_for_free_events = array())
765
+	{
766
+		// set some defaults
767
+		$this->checkout->selected_method_of_payment = 'no_payment_required';
768
+		// generate no_payment_required form
769
+		return new EE_Form_Section_Proper(
770
+			array(
771
+				'layout_strategy' => new EE_Template_Layout(
772
+					array(
773
+						'layout_template_file' => SPCO_REG_STEPS_PATH
774
+												  . $this->_slug
775
+												  . DS
776
+												  . 'no_payment_required.template.php', // layout_template
777
+						'template_args'        => apply_filters(
778
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___no_payment_required__template_args',
779
+							array(
780
+								'revisit'                       => $this->checkout->revisit,
781
+								'registrations'                 => array(),
782
+								'ticket_count'                  => array(),
783
+								'registrations_for_free_events' => $registrations_for_free_events,
784
+								'no_payment_required_msg'       => EEH_HTML::p(
785
+									esc_html__('This is a free event, so no billing will occur.', 'event_espresso')
786
+								),
787
+							)
788
+						),
789
+					)
790
+				),
791
+			)
792
+		);
793
+	}
794
+
795
+
796
+	/**
797
+	 * _display_payment_options
798
+	 *
799
+	 * @param string $transaction_details
800
+	 * @return EE_Form_Section_Proper
801
+	 * @throws EE_Error
802
+	 * @throws InvalidArgumentException
803
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
804
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
805
+	 */
806
+	private function _display_payment_options($transaction_details = '')
807
+	{
808
+		// has method_of_payment been set by no-js user?
809
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment();
810
+		// build payment options form
811
+		return apply_filters(
812
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__payment_options_form',
813
+			new EE_Form_Section_Proper(
814
+				array(
815
+					'subsections'     => array(
816
+						'before_payment_options' => apply_filters(
817
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__before_payment_options',
818
+							new EE_Form_Section_Proper(
819
+								array('layout_strategy' => new EE_Div_Per_Section_Layout())
820
+							)
821
+						),
822
+						'payment_options'        => $this->_setup_payment_options(),
823
+						'after_payment_options'  => apply_filters(
824
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__after_payment_options',
825
+							new EE_Form_Section_Proper(
826
+								array('layout_strategy' => new EE_Div_Per_Section_Layout())
827
+							)
828
+						),
829
+					),
830
+					'layout_strategy' => new EE_Template_Layout(
831
+						array(
832
+							'layout_template_file' => $this->_template,
833
+							'template_args'        => apply_filters(
834
+								'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__template_args',
835
+								array(
836
+									'reg_count'                 => $this->line_item_display->total_items(),
837
+									'transaction_details'       => $transaction_details,
838
+									'available_payment_methods' => array(),
839
+								)
840
+							),
841
+						)
842
+					),
843
+				)
844
+			)
845
+		);
846
+	}
847
+
848
+
849
+	/**
850
+	 * _extra_hidden_inputs
851
+	 *
852
+	 * @param bool $no_payment_required
853
+	 * @return \EE_Form_Section_Proper
854
+	 * @throws \EE_Error
855
+	 */
856
+	private function _extra_hidden_inputs($no_payment_required = true)
857
+	{
858
+		return new EE_Form_Section_Proper(
859
+			array(
860
+				'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
861
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
862
+				'subsections'     => array(
863
+					'spco_no_payment_required' => new EE_Hidden_Input(
864
+						array(
865
+							'normalization_strategy' => new EE_Boolean_Normalization(),
866
+							'html_name'              => 'spco_no_payment_required',
867
+							'html_id'                => 'spco-no-payment-required-payment_options',
868
+							'default'                => $no_payment_required,
869
+						)
870
+					),
871
+					'spco_transaction_id'      => new EE_Fixed_Hidden_Input(
872
+						array(
873
+							'normalization_strategy' => new EE_Int_Normalization(),
874
+							'html_name'              => 'spco_transaction_id',
875
+							'html_id'                => 'spco-transaction-id',
876
+							'default'                => $this->checkout->transaction->ID(),
877
+						)
878
+					),
879
+				),
880
+			)
881
+		);
882
+	}
883
+
884
+
885
+	/**
886
+	 *    _apply_registration_payments_to_amount_owing
887
+	 *
888
+	 * @access protected
889
+	 * @param array $registrations
890
+	 * @throws EE_Error
891
+	 */
892
+	protected function _apply_registration_payments_to_amount_owing(array $registrations)
893
+	{
894
+		$payments = array();
895
+		foreach ($registrations as $registration) {
896
+			if ($registration instanceof EE_Registration && $registration->owes_monies_and_can_pay()) {
897
+				$payments += $registration->registration_payments();
898
+			}
899
+		}
900
+		if (! empty($payments)) {
901
+			foreach ($payments as $payment) {
902
+				if ($payment instanceof EE_Registration_Payment) {
903
+					$this->checkout->amount_owing -= $payment->amount();
904
+				}
905
+			}
906
+		}
907
+	}
908
+
909
+
910
+	/**
911
+	 *    _reset_selected_method_of_payment
912
+	 *
913
+	 * @access    private
914
+	 * @param    bool $force_reset
915
+	 * @return void
916
+	 * @throws InvalidArgumentException
917
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
918
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
919
+	 */
920
+	private function _reset_selected_method_of_payment($force_reset = false)
921
+	{
922
+		$reset_payment_method = $force_reset
923
+			? true
924
+			: sanitize_text_field(EE_Registry::instance()->REQ->get('reset_payment_method', false));
925
+		if ($reset_payment_method) {
926
+			$this->checkout->selected_method_of_payment = null;
927
+			$this->checkout->payment_method = null;
928
+			$this->checkout->billing_form = null;
929
+			$this->_save_selected_method_of_payment();
930
+		}
931
+	}
932
+
933
+
934
+	/**
935
+	 * _save_selected_method_of_payment
936
+	 * stores the selected_method_of_payment in the session
937
+	 * so that it's available for all subsequent requests including AJAX
938
+	 *
939
+	 * @access        private
940
+	 * @param string $selected_method_of_payment
941
+	 * @return void
942
+	 * @throws InvalidArgumentException
943
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
944
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
945
+	 */
946
+	private function _save_selected_method_of_payment($selected_method_of_payment = '')
947
+	{
948
+		$selected_method_of_payment = ! empty($selected_method_of_payment)
949
+			? $selected_method_of_payment
950
+			: $this->checkout->selected_method_of_payment;
951
+		EE_Registry::instance()->SSN->set_session_data(
952
+			array('selected_method_of_payment' => $selected_method_of_payment)
953
+		);
954
+	}
955
+
956
+
957
+	/**
958
+	 * _setup_payment_options
959
+	 *
960
+	 * @return EE_Form_Section_Proper
961
+	 * @throws EE_Error
962
+	 * @throws InvalidArgumentException
963
+	 * @throws ReflectionException
964
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
965
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
966
+	 */
967
+	public function _setup_payment_options()
968
+	{
969
+		// load payment method classes
970
+		$this->checkout->available_payment_methods = $this->_get_available_payment_methods();
971
+		if (empty($this->checkout->available_payment_methods)) {
972
+			EE_Error::add_error(
973
+				apply_filters(
974
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options___setup_payment_options__error_message_no_payment_methods',
975
+					sprintf(
976
+						esc_html__(
977
+							'Sorry, you cannot complete your purchase because a payment method is not active.%1$s Please contact %2$s for assistance and provide a description of the problem.',
978
+							'event_espresso'
979
+						),
980
+						'<br>',
981
+						EE_Registry::instance()->CFG->organization->get_pretty('email')
982
+					)
983
+				),
984
+				__FILE__,
985
+				__FUNCTION__,
986
+				__LINE__
987
+			);
988
+		}
989
+		// switch up header depending on number of available payment methods
990
+		$payment_method_header = count($this->checkout->available_payment_methods) > 1
991
+			? apply_filters(
992
+				'FHEE__registration_page_payment_options__method_of_payment_hdr',
993
+				esc_html__('Please Select Your Method of Payment', 'event_espresso')
994
+			)
995
+			: apply_filters(
996
+				'FHEE__registration_page_payment_options__method_of_payment_hdr',
997
+				esc_html__('Method of Payment', 'event_espresso')
998
+			);
999
+		$available_payment_methods = array(
1000
+			// display the "Payment Method" header
1001
+			'payment_method_header' => new EE_Form_Section_HTML(
1002
+				EEH_HTML::h4($payment_method_header, 'method-of-payment-hdr')
1003
+			),
1004
+		);
1005
+		// the list of actual payment methods ( invoice, paypal, etc ) in a  ( slug => HTML )  format
1006
+		$available_payment_method_options = array();
1007
+		$default_payment_method_option = array();
1008
+		// additional instructions to be displayed and hidden below payment methods (adding a clearing div to start)
1009
+		$payment_methods_billing_info = array(
1010
+			new EE_Form_Section_HTML(
1011
+				EEH_HTML::div('<br />', '', '', 'clear:both;')
1012
+			),
1013
+		);
1014
+		// loop through payment methods
1015
+		foreach ($this->checkout->available_payment_methods as $payment_method) {
1016
+			if ($payment_method instanceof EE_Payment_Method) {
1017
+				$payment_method_button = EEH_HTML::img(
1018
+					$payment_method->button_url(),
1019
+					$payment_method->name(),
1020
+					'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1021
+					'spco-payment-method-btn-img'
1022
+				);
1023
+				// check if any payment methods are set as default
1024
+				// if payment method is already selected OR nothing is selected and this payment method should be
1025
+				// open_by_default
1026
+				if (($this->checkout->selected_method_of_payment === $payment_method->slug())
1027
+					|| (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1028
+				) {
1029
+					$this->checkout->selected_method_of_payment = $payment_method->slug();
1030
+					$this->_save_selected_method_of_payment();
1031
+					$default_payment_method_option[ $payment_method->slug() ] = $payment_method_button;
1032
+				} else {
1033
+					$available_payment_method_options[ $payment_method->slug() ] = $payment_method_button;
1034
+				}
1035
+				$payment_methods_billing_info[ $payment_method->slug(
1036
+				) . '-info' ] = $this->_payment_method_billing_info(
1037
+					$payment_method
1038
+				);
1039
+			}
1040
+		}
1041
+		// prepend available_payment_method_options with default_payment_method_option so that it appears first in list
1042
+		// of PMs
1043
+		$available_payment_method_options = $default_payment_method_option + $available_payment_method_options;
1044
+		// now generate the actual form  inputs
1045
+		$available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
1046
+			$available_payment_method_options
1047
+		);
1048
+		$available_payment_methods += $payment_methods_billing_info;
1049
+		// build the available payment methods form
1050
+		return new EE_Form_Section_Proper(
1051
+			array(
1052
+				'html_id'         => 'spco-available-methods-of-payment-dv',
1053
+				'subsections'     => $available_payment_methods,
1054
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1055
+			)
1056
+		);
1057
+	}
1058
+
1059
+
1060
+	/**
1061
+	 * _get_available_payment_methods
1062
+	 *
1063
+	 * @return EE_Payment_Method[]
1064
+	 * @throws EE_Error
1065
+	 * @throws InvalidArgumentException
1066
+	 * @throws ReflectionException
1067
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1068
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1069
+	 */
1070
+	protected function _get_available_payment_methods()
1071
+	{
1072
+		if (! empty($this->checkout->available_payment_methods)) {
1073
+			return $this->checkout->available_payment_methods;
1074
+		}
1075
+		$available_payment_methods = array();
1076
+		// load EEM_Payment_Method
1077
+		EE_Registry::instance()->load_model('Payment_Method');
1078
+		/** @type EEM_Payment_Method $EEM_Payment_Method */
1079
+		$EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
1080
+		// get all active payment methods
1081
+		$payment_methods = $EEM_Payment_Method->get_all_for_transaction(
1082
+			$this->checkout->transaction,
1083
+			EEM_Payment_Method::scope_cart
1084
+		);
1085
+		foreach ($payment_methods as $payment_method) {
1086
+			if ($payment_method instanceof EE_Payment_Method) {
1087
+				$available_payment_methods[ $payment_method->slug() ] = $payment_method;
1088
+			}
1089
+		}
1090
+		return $available_payment_methods;
1091
+	}
1092
+
1093
+
1094
+	/**
1095
+	 *    _available_payment_method_inputs
1096
+	 *
1097
+	 * @access    private
1098
+	 * @param    array $available_payment_method_options
1099
+	 * @return    \EE_Form_Section_Proper
1100
+	 */
1101
+	private function _available_payment_method_inputs($available_payment_method_options = array())
1102
+	{
1103
+		// generate inputs
1104
+		return new EE_Form_Section_Proper(
1105
+			array(
1106
+				'html_id'         => 'ee-available-payment-method-inputs',
1107
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1108
+				'subsections'     => array(
1109
+					'' => new EE_Radio_Button_Input(
1110
+						$available_payment_method_options,
1111
+						array(
1112
+							'html_name'          => 'selected_method_of_payment',
1113
+							'html_class'         => 'spco-payment-method',
1114
+							'default'            => $this->checkout->selected_method_of_payment,
1115
+							'label_size'         => 11,
1116
+							'enforce_label_size' => true,
1117
+						)
1118
+					),
1119
+				),
1120
+			)
1121
+		);
1122
+	}
1123
+
1124
+
1125
+	/**
1126
+	 *    _payment_method_billing_info
1127
+	 *
1128
+	 * @access    private
1129
+	 * @param    EE_Payment_Method $payment_method
1130
+	 * @return EE_Form_Section_Proper
1131
+	 * @throws EE_Error
1132
+	 * @throws InvalidArgumentException
1133
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1134
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1135
+	 */
1136
+	private function _payment_method_billing_info(EE_Payment_Method $payment_method)
1137
+	{
1138
+		$currently_selected = $this->checkout->selected_method_of_payment === $payment_method->slug()
1139
+			? true
1140
+			: false;
1141
+		// generate the billing form for payment method
1142
+		$billing_form = $currently_selected
1143
+			? $this->_get_billing_form_for_payment_method($payment_method)
1144
+			: new EE_Form_Section_HTML();
1145
+		$this->checkout->billing_form = $currently_selected
1146
+			? $billing_form
1147
+			: $this->checkout->billing_form;
1148
+		// it's all in the details
1149
+		$info_html = EEH_HTML::h3(
1150
+			esc_html__('Important information regarding your payment', 'event_espresso'),
1151
+			'',
1152
+			'spco-payment-method-hdr'
1153
+		);
1154
+		// add some info regarding the step, either from what's saved in the admin,
1155
+		// or a default string depending on whether the PM has a billing form or not
1156
+		if ($payment_method->description()) {
1157
+			$payment_method_info = $payment_method->description();
1158
+		} elseif ($billing_form instanceof EE_Billing_Info_Form) {
1159
+			$payment_method_info = sprintf(
1160
+				esc_html__(
1161
+					'Please provide the following billing information, then click the "%1$s" button below in order to proceed.',
1162
+					'event_espresso'
1163
+				),
1164
+				$this->submit_button_text()
1165
+			);
1166
+		} else {
1167
+			$payment_method_info = sprintf(
1168
+				esc_html__('Please click the "%1$s" button below in order to proceed.', 'event_espresso'),
1169
+				$this->submit_button_text()
1170
+			);
1171
+		}
1172
+		$info_html .= EEH_HTML::p(
1173
+			apply_filters(
1174
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options___payment_method_billing_info__payment_method_info',
1175
+				$payment_method_info
1176
+			),
1177
+			'',
1178
+			'spco-payment-method-desc ee-attention'
1179
+		);
1180
+		return new EE_Form_Section_Proper(
1181
+			array(
1182
+				'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1183
+				'html_class'      => 'spco-payment-method-info-dv',
1184
+				// only display the selected or default PM
1185
+				'html_style'      => $currently_selected ? '' : 'display:none;',
1186
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1187
+				'subsections'     => array(
1188
+					'info'         => new EE_Form_Section_HTML($info_html),
1189
+					'billing_form' => $currently_selected ? $billing_form : new EE_Form_Section_HTML(),
1190
+				),
1191
+			)
1192
+		);
1193
+	}
1194
+
1195
+
1196
+	/**
1197
+	 * get_billing_form_html_for_payment_method
1198
+	 *
1199
+	 * @access public
1200
+	 * @return string
1201
+	 * @throws EE_Error
1202
+	 * @throws InvalidArgumentException
1203
+	 * @throws ReflectionException
1204
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1205
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1206
+	 */
1207
+	public function get_billing_form_html_for_payment_method()
1208
+	{
1209
+		// how have they chosen to pay?
1210
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1211
+		$this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1212
+		if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1213
+			return false;
1214
+		}
1215
+		if (apply_filters(
1216
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1217
+			false
1218
+		)) {
1219
+			EE_Error::add_success(
1220
+				apply_filters(
1221
+					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1222
+					sprintf(
1223
+						esc_html__(
1224
+							'You have selected "%s" as your method of payment. Please note the important payment information below.',
1225
+							'event_espresso'
1226
+						),
1227
+						$this->checkout->payment_method->name()
1228
+					)
1229
+				)
1230
+			);
1231
+		}
1232
+		// now generate billing form for selected method of payment
1233
+		$payment_method_billing_form = $this->_get_billing_form_for_payment_method($this->checkout->payment_method);
1234
+		// fill form with attendee info if applicable
1235
+		if ($payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
1236
+			&& $this->checkout->transaction_has_primary_registrant()
1237
+		) {
1238
+			$payment_method_billing_form->populate_from_attendee(
1239
+				$this->checkout->transaction->primary_registration()->attendee()
1240
+			);
1241
+		}
1242
+		// and debug content
1243
+		if ($payment_method_billing_form instanceof EE_Billing_Info_Form
1244
+			&& $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1245
+		) {
1246
+			$payment_method_billing_form =
1247
+				$this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1248
+					$payment_method_billing_form
1249
+				);
1250
+		}
1251
+		$billing_info = $payment_method_billing_form instanceof EE_Form_Section_Proper
1252
+			? $payment_method_billing_form->get_html()
1253
+			: '';
1254
+		$this->checkout->json_response->set_return_data(array('payment_method_info' => $billing_info));
1255
+		// localize validation rules for main form
1256
+		$this->checkout->current_step->reg_form->localize_validation_rules();
1257
+		$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1258
+		return true;
1259
+	}
1260
+
1261
+
1262
+	/**
1263
+	 * _get_billing_form_for_payment_method
1264
+	 *
1265
+	 * @access private
1266
+	 * @param EE_Payment_Method $payment_method
1267
+	 * @return EE_Billing_Info_Form|EE_Form_Section_HTML
1268
+	 * @throws EE_Error
1269
+	 * @throws InvalidArgumentException
1270
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1271
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1272
+	 */
1273
+	private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method)
1274
+	{
1275
+		$billing_form = $payment_method->type_obj()->billing_form(
1276
+			$this->checkout->transaction,
1277
+			array('amount_owing' => $this->checkout->amount_owing)
1278
+		);
1279
+		if ($billing_form instanceof EE_Billing_Info_Form) {
1280
+			if (apply_filters(
1281
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1282
+				false
1283
+			)
1284
+				&& EE_Registry::instance()->REQ->is_set('payment_method')
1285
+			) {
1286
+				EE_Error::add_success(
1287
+					apply_filters(
1288
+						'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1289
+						sprintf(
1290
+							esc_html__(
1291
+								'You have selected "%s" as your method of payment. Please note the important payment information below.',
1292
+								'event_espresso'
1293
+							),
1294
+							$payment_method->name()
1295
+						)
1296
+					)
1297
+				);
1298
+			}
1299
+			return apply_filters(
1300
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
1301
+				$billing_form,
1302
+				$payment_method
1303
+			);
1304
+		}
1305
+		// no actual billing form, so return empty HTML form section
1306
+		return new EE_Form_Section_HTML();
1307
+	}
1308
+
1309
+
1310
+	/**
1311
+	 * _get_selected_method_of_payment
1312
+	 *
1313
+	 * @access private
1314
+	 * @param boolean $required whether to throw an error if the "selected_method_of_payment"
1315
+	 *                          is not found in the incoming request
1316
+	 * @param string  $request_param
1317
+	 * @return NULL|string
1318
+	 * @throws EE_Error
1319
+	 * @throws InvalidArgumentException
1320
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1321
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1322
+	 */
1323
+	private function _get_selected_method_of_payment(
1324
+		$required = false,
1325
+		$request_param = 'selected_method_of_payment'
1326
+	) {
1327
+		// is selected_method_of_payment set in the request ?
1328
+		$selected_method_of_payment = EE_Registry::instance()->REQ->get($request_param, false);
1329
+		if ($selected_method_of_payment) {
1330
+			// sanitize it
1331
+			$selected_method_of_payment = is_array($selected_method_of_payment)
1332
+				? array_shift($selected_method_of_payment)
1333
+				: $selected_method_of_payment;
1334
+			$selected_method_of_payment = sanitize_text_field($selected_method_of_payment);
1335
+			// store it in the session so that it's available for all subsequent requests including AJAX
1336
+			$this->_save_selected_method_of_payment($selected_method_of_payment);
1337
+		} else {
1338
+			// or is is set in the session ?
1339
+			$selected_method_of_payment = EE_Registry::instance()->SSN->get_session_data(
1340
+				'selected_method_of_payment'
1341
+			);
1342
+		}
1343
+		// do ya really really gotta have it?
1344
+		if (empty($selected_method_of_payment) && $required) {
1345
+			EE_Error::add_error(
1346
+				sprintf(
1347
+					esc_html__(
1348
+						'The selected method of payment could not be determined.%sPlease ensure that you have selected one before proceeding.%sIf you continue to experience difficulties, then refresh your browser and try again, or contact %s for assistance.',
1349
+						'event_espresso'
1350
+					),
1351
+					'<br/>',
1352
+					'<br/>',
1353
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
1354
+				),
1355
+				__FILE__,
1356
+				__FUNCTION__,
1357
+				__LINE__
1358
+			);
1359
+			return null;
1360
+		}
1361
+		return $selected_method_of_payment;
1362
+	}
1363
+
1364
+
1365
+
1366
+
1367
+
1368
+
1369
+	/********************************************************************************************************/
1370
+	/***********************************  SWITCH PAYMENT METHOD  ************************************/
1371
+	/********************************************************************************************************/
1372
+	/**
1373
+	 * switch_payment_method
1374
+	 *
1375
+	 * @access public
1376
+	 * @return string
1377
+	 * @throws EE_Error
1378
+	 * @throws InvalidArgumentException
1379
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1380
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1381
+	 */
1382
+	public function switch_payment_method()
1383
+	{
1384
+		if (! $this->_verify_payment_method_is_set()) {
1385
+			return false;
1386
+		}
1387
+		if (apply_filters(
1388
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1389
+			false
1390
+		)) {
1391
+			EE_Error::add_success(
1392
+				apply_filters(
1393
+					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1394
+					sprintf(
1395
+						esc_html__(
1396
+							'You have selected "%s" as your method of payment. Please note the important payment information below.',
1397
+							'event_espresso'
1398
+						),
1399
+						$this->checkout->payment_method->name()
1400
+					)
1401
+				)
1402
+			);
1403
+		}
1404
+		// generate billing form for selected method of payment if it hasn't been done already
1405
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1406
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1407
+				$this->checkout->payment_method
1408
+			);
1409
+		}
1410
+		// fill form with attendee info if applicable
1411
+		if (apply_filters(
1412
+			'FHEE__populate_billing_form_fields_from_attendee',
1413
+			(
1414
+				$this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1415
+				&& $this->checkout->transaction_has_primary_registrant()
1416
+			),
1417
+			$this->checkout->billing_form,
1418
+			$this->checkout->transaction
1419
+		)
1420
+		) {
1421
+			$this->checkout->billing_form->populate_from_attendee(
1422
+				$this->checkout->transaction->primary_registration()->attendee()
1423
+			);
1424
+		}
1425
+		// and debug content
1426
+		if ($this->checkout->billing_form instanceof EE_Billing_Info_Form
1427
+			&& $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1428
+		) {
1429
+			$this->checkout->billing_form =
1430
+				$this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1431
+					$this->checkout->billing_form
1432
+				);
1433
+		}
1434
+		// get html and validation rules for form
1435
+		if ($this->checkout->billing_form instanceof EE_Form_Section_Proper) {
1436
+			$this->checkout->json_response->set_return_data(
1437
+				array('payment_method_info' => $this->checkout->billing_form->get_html())
1438
+			);
1439
+			// localize validation rules for main form
1440
+			$this->checkout->billing_form->localize_validation_rules(true);
1441
+			$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1442
+		} else {
1443
+			$this->checkout->json_response->set_return_data(array('payment_method_info' => ''));
1444
+		}
1445
+		// prevents advancement to next step
1446
+		$this->checkout->continue_reg = false;
1447
+		return true;
1448
+	}
1449
+
1450
+
1451
+	/**
1452
+	 * _verify_payment_method_is_set
1453
+	 *
1454
+	 * @return bool
1455
+	 * @throws EE_Error
1456
+	 * @throws InvalidArgumentException
1457
+	 * @throws ReflectionException
1458
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1459
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1460
+	 */
1461
+	protected function _verify_payment_method_is_set()
1462
+	{
1463
+		// generate billing form for selected method of payment if it hasn't been done already
1464
+		if (empty($this->checkout->selected_method_of_payment)) {
1465
+			// how have they chosen to pay?
1466
+			$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1467
+		} else {
1468
+			// choose your own adventure based on method_of_payment
1469
+			switch ($this->checkout->selected_method_of_payment) {
1470
+				case 'events_sold_out':
1471
+					EE_Error::add_attention(
1472
+						apply_filters(
1473
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__sold_out_events_msg',
1474
+							esc_html__(
1475
+								'It appears that the event you were about to make a payment for has sold out since this form first loaded. Please contact the event administrator if you believe this is an error.',
1476
+								'event_espresso'
1477
+							)
1478
+						),
1479
+						__FILE__,
1480
+						__FUNCTION__,
1481
+						__LINE__
1482
+					);
1483
+					return false;
1484
+					break;
1485
+				case 'payments_closed':
1486
+					EE_Error::add_attention(
1487
+						apply_filters(
1488
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__payments_closed_msg',
1489
+							esc_html__(
1490
+								'It appears that the event you were about to make a payment for is not accepting payments at this time. Please contact the event administrator if you believe this is an error.',
1491
+								'event_espresso'
1492
+							)
1493
+						),
1494
+						__FILE__,
1495
+						__FUNCTION__,
1496
+						__LINE__
1497
+					);
1498
+					return false;
1499
+					break;
1500
+				case 'no_payment_required':
1501
+					EE_Error::add_attention(
1502
+						apply_filters(
1503
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__no_payment_required_msg',
1504
+							esc_html__(
1505
+								'It appears that the event you were about to make a payment for does not require payment. Please contact the event administrator if you believe this is an error.',
1506
+								'event_espresso'
1507
+							)
1508
+						),
1509
+						__FILE__,
1510
+						__FUNCTION__,
1511
+						__LINE__
1512
+					);
1513
+					return false;
1514
+					break;
1515
+				default:
1516
+			}
1517
+		}
1518
+		// verify payment method
1519
+		if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1520
+			// get payment method for selected method of payment
1521
+			$this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1522
+		}
1523
+		return $this->checkout->payment_method instanceof EE_Payment_Method ? true : false;
1524
+	}
1525
+
1526
+
1527
+
1528
+	/********************************************************************************************************/
1529
+	/***************************************  SAVE PAYER DETAILS  ****************************************/
1530
+	/********************************************************************************************************/
1531
+	/**
1532
+	 * save_payer_details_via_ajax
1533
+	 *
1534
+	 * @return void
1535
+	 * @throws EE_Error
1536
+	 * @throws InvalidArgumentException
1537
+	 * @throws ReflectionException
1538
+	 * @throws RuntimeException
1539
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1540
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1541
+	 */
1542
+	public function save_payer_details_via_ajax()
1543
+	{
1544
+		if (! $this->_verify_payment_method_is_set()) {
1545
+			return;
1546
+		}
1547
+		// generate billing form for selected method of payment if it hasn't been done already
1548
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1549
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1550
+				$this->checkout->payment_method
1551
+			);
1552
+		}
1553
+		// generate primary attendee from payer info if applicable
1554
+		if (! $this->checkout->transaction_has_primary_registrant()) {
1555
+			$attendee = $this->_create_attendee_from_request_data();
1556
+			if ($attendee instanceof EE_Attendee) {
1557
+				foreach ($this->checkout->transaction->registrations() as $registration) {
1558
+					if ($registration->is_primary_registrant()) {
1559
+						$this->checkout->primary_attendee_obj = $attendee;
1560
+						$registration->_add_relation_to($attendee, 'Attendee');
1561
+						$registration->set_attendee_id($attendee->ID());
1562
+						$registration->update_cache_after_object_save('Attendee', $attendee);
1563
+					}
1564
+				}
1565
+			}
1566
+		}
1567
+	}
1568
+
1569
+
1570
+	/**
1571
+	 * create_attendee_from_request_data
1572
+	 * uses info from alternate GET or POST data (such as AJAX) to create a new attendee
1573
+	 *
1574
+	 * @return EE_Attendee
1575
+	 * @throws EE_Error
1576
+	 * @throws InvalidArgumentException
1577
+	 * @throws ReflectionException
1578
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1579
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1580
+	 */
1581
+	protected function _create_attendee_from_request_data()
1582
+	{
1583
+		// get State ID
1584
+		$STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1585
+		if (! empty($STA_ID)) {
1586
+			// can we get state object from name ?
1587
+			EE_Registry::instance()->load_model('State');
1588
+			$state = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
1589
+			$STA_ID = is_array($state) && ! empty($state) ? reset($state) : $STA_ID;
1590
+		}
1591
+		// get Country ISO
1592
+		$CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1593
+		if (! empty($CNT_ISO)) {
1594
+			// can we get country object from name ?
1595
+			EE_Registry::instance()->load_model('Country');
1596
+			$country = EEM_Country::instance()->get_col(
1597
+				array(array('CNT_name' => $CNT_ISO), 'limit' => 1),
1598
+				'CNT_ISO'
1599
+			);
1600
+			$CNT_ISO = is_array($country) && ! empty($country) ? reset($country) : $CNT_ISO;
1601
+		}
1602
+		// grab attendee data
1603
+		$attendee_data = array(
1604
+			'ATT_fname'    => ! empty($_REQUEST['first_name']) ? sanitize_text_field($_REQUEST['first_name']) : '',
1605
+			'ATT_lname'    => ! empty($_REQUEST['last_name']) ? sanitize_text_field($_REQUEST['last_name']) : '',
1606
+			'ATT_email'    => ! empty($_REQUEST['email']) ? sanitize_email($_REQUEST['email']) : '',
1607
+			'ATT_address'  => ! empty($_REQUEST['address']) ? sanitize_text_field($_REQUEST['address']) : '',
1608
+			'ATT_address2' => ! empty($_REQUEST['address2']) ? sanitize_text_field($_REQUEST['address2']) : '',
1609
+			'ATT_city'     => ! empty($_REQUEST['city']) ? sanitize_text_field($_REQUEST['city']) : '',
1610
+			'STA_ID'       => $STA_ID,
1611
+			'CNT_ISO'      => $CNT_ISO,
1612
+			'ATT_zip'      => ! empty($_REQUEST['zip']) ? sanitize_text_field($_REQUEST['zip']) : '',
1613
+			'ATT_phone'    => ! empty($_REQUEST['phone']) ? sanitize_text_field($_REQUEST['phone']) : '',
1614
+		);
1615
+		// validate the email address since it is the most important piece of info
1616
+		if (empty($attendee_data['ATT_email']) || $attendee_data['ATT_email'] !== $_REQUEST['email']) {
1617
+			EE_Error::add_error(
1618
+				esc_html__('An invalid email address was submitted.', 'event_espresso'),
1619
+				__FILE__,
1620
+				__FUNCTION__,
1621
+				__LINE__
1622
+			);
1623
+		}
1624
+		// does this attendee already exist in the db ? we're searching using a combination of first name, last name,
1625
+		// AND email address
1626
+		if (! empty($attendee_data['ATT_fname'])
1627
+			&& ! empty($attendee_data['ATT_lname'])
1628
+			&& ! empty($attendee_data['ATT_email'])
1629
+		) {
1630
+			$existing_attendee = EE_Registry::instance()->LIB->EEM_Attendee->find_existing_attendee(
1631
+				array(
1632
+					'ATT_fname' => $attendee_data['ATT_fname'],
1633
+					'ATT_lname' => $attendee_data['ATT_lname'],
1634
+					'ATT_email' => $attendee_data['ATT_email'],
1635
+				)
1636
+			);
1637
+			if ($existing_attendee instanceof EE_Attendee) {
1638
+				return $existing_attendee;
1639
+			}
1640
+		}
1641
+		// no existing attendee? kk let's create a new one
1642
+		// kinda lame, but we need a first and last name to create an attendee, so use the email address if those
1643
+		// don't exist
1644
+		$attendee_data['ATT_fname'] = ! empty($attendee_data['ATT_fname'])
1645
+			? $attendee_data['ATT_fname']
1646
+			: $attendee_data['ATT_email'];
1647
+		$attendee_data['ATT_lname'] = ! empty($attendee_data['ATT_lname'])
1648
+			? $attendee_data['ATT_lname']
1649
+			: $attendee_data['ATT_email'];
1650
+		return EE_Attendee::new_instance($attendee_data);
1651
+	}
1652
+
1653
+
1654
+
1655
+	/********************************************************************************************************/
1656
+	/****************************************  PROCESS REG STEP  *****************************************/
1657
+	/********************************************************************************************************/
1658
+	/**
1659
+	 * process_reg_step
1660
+	 *
1661
+	 * @return bool
1662
+	 * @throws EE_Error
1663
+	 * @throws InvalidArgumentException
1664
+	 * @throws ReflectionException
1665
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1666
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1667
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1668
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
1669
+	 */
1670
+	public function process_reg_step()
1671
+	{
1672
+		// how have they chosen to pay?
1673
+		$this->checkout->selected_method_of_payment = $this->checkout->transaction->is_free()
1674
+			? 'no_payment_required'
1675
+			: $this->_get_selected_method_of_payment(true);
1676
+		// choose your own adventure based on method_of_payment
1677
+		switch ($this->checkout->selected_method_of_payment) {
1678
+			case 'events_sold_out':
1679
+				$this->checkout->redirect = true;
1680
+				$this->checkout->redirect_url = $this->checkout->cancel_page_url;
1681
+				$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1682
+				// mark this reg step as completed
1683
+				$this->set_completed();
1684
+				return false;
1685
+				break;
1686
+
1687
+			case 'payments_closed':
1688
+				if (apply_filters(
1689
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__payments_closed__display_success',
1690
+					false
1691
+				)) {
1692
+					EE_Error::add_success(
1693
+						esc_html__('no payment required at this time.', 'event_espresso'),
1694
+						__FILE__,
1695
+						__FUNCTION__,
1696
+						__LINE__
1697
+					);
1698
+				}
1699
+				// mark this reg step as completed
1700
+				$this->set_completed();
1701
+				return true;
1702
+				break;
1703
+
1704
+			case 'no_payment_required':
1705
+				if (apply_filters(
1706
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__no_payment_required__display_success',
1707
+					false
1708
+				)) {
1709
+					EE_Error::add_success(
1710
+						esc_html__('no payment required.', 'event_espresso'),
1711
+						__FILE__,
1712
+						__FUNCTION__,
1713
+						__LINE__
1714
+					);
1715
+				}
1716
+				// mark this reg step as completed
1717
+				$this->set_completed();
1718
+				return true;
1719
+				break;
1720
+
1721
+			default:
1722
+				$registrations = EE_Registry::instance()->SSN->checkout()->transaction->registrations(
1723
+					EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
1724
+				);
1725
+				$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
1726
+					$registrations,
1727
+					EE_Registry::instance()->SSN->checkout()->revisit
1728
+				);
1729
+				// calculate difference between the two arrays
1730
+				$registrations = array_diff($registrations, $ejected_registrations);
1731
+				if (empty($registrations)) {
1732
+					$this->_redirect_because_event_sold_out();
1733
+					return false;
1734
+				}
1735
+				$payment_successful = $this->_process_payment();
1736
+				if ($payment_successful) {
1737
+					$this->checkout->continue_reg = true;
1738
+					$this->_maybe_set_completed($this->checkout->payment_method);
1739
+				} else {
1740
+					$this->checkout->continue_reg = false;
1741
+				}
1742
+				return $payment_successful;
1743
+		}
1744
+	}
1745
+
1746
+
1747
+	/**
1748
+	 * _redirect_because_event_sold_out
1749
+	 *
1750
+	 * @access protected
1751
+	 * @return void
1752
+	 */
1753
+	protected function _redirect_because_event_sold_out()
1754
+	{
1755
+		$this->checkout->continue_reg = false;
1756
+		// set redirect URL
1757
+		$this->checkout->redirect_url = add_query_arg(
1758
+			array('e_reg_url_link' => $this->checkout->reg_url_link),
1759
+			$this->checkout->current_step->reg_step_url()
1760
+		);
1761
+		$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1762
+	}
1763
+
1764
+
1765
+	/**
1766
+	 * _maybe_set_completed
1767
+	 *
1768
+	 * @access protected
1769
+	 * @param \EE_Payment_Method $payment_method
1770
+	 * @return void
1771
+	 * @throws \EE_Error
1772
+	 */
1773
+	protected function _maybe_set_completed(EE_Payment_Method $payment_method)
1774
+	{
1775
+		switch ($payment_method->type_obj()->payment_occurs()) {
1776
+			case EE_PMT_Base::offsite:
1777
+				break;
1778
+			case EE_PMT_Base::onsite:
1779
+			case EE_PMT_Base::offline:
1780
+				// mark this reg step as completed
1781
+				$this->set_completed();
1782
+				break;
1783
+		}
1784
+	}
1785
+
1786
+
1787
+	/**
1788
+	 *    update_reg_step
1789
+	 *    this is the final step after a user  revisits the site to retry a payment
1790
+	 *
1791
+	 * @return bool
1792
+	 * @throws EE_Error
1793
+	 * @throws InvalidArgumentException
1794
+	 * @throws ReflectionException
1795
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1796
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1797
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1798
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
1799
+	 */
1800
+	public function update_reg_step()
1801
+	{
1802
+		$success = true;
1803
+		// if payment required
1804
+		if ($this->checkout->transaction->total() > 0) {
1805
+			do_action(
1806
+				'AHEE__EE_Single_Page_Checkout__process_finalize_registration__before_gateway',
1807
+				$this->checkout->transaction
1808
+			);
1809
+			// attempt payment via payment method
1810
+			$success = $this->process_reg_step();
1811
+		}
1812
+		if ($success && ! $this->checkout->redirect) {
1813
+			$this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn(
1814
+				$this->checkout->transaction->ID()
1815
+			);
1816
+			// set return URL
1817
+			$this->checkout->redirect_url = add_query_arg(
1818
+				array('e_reg_url_link' => $this->checkout->reg_url_link),
1819
+				$this->checkout->thank_you_page_url
1820
+			);
1821
+		}
1822
+		return $success;
1823
+	}
1824
+
1825
+
1826
+	/**
1827
+	 *    _process_payment
1828
+	 *
1829
+	 * @access private
1830
+	 * @return bool
1831
+	 * @throws EE_Error
1832
+	 * @throws InvalidArgumentException
1833
+	 * @throws ReflectionException
1834
+	 * @throws RuntimeException
1835
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1836
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1837
+	 */
1838
+	private function _process_payment()
1839
+	{
1840
+		// basically confirm that the event hasn't sold out since they hit the page
1841
+		if (! $this->_last_second_ticket_verifications()) {
1842
+			return false;
1843
+		}
1844
+		// ya gotta make a choice man
1845
+		if (empty($this->checkout->selected_method_of_payment)) {
1846
+			$this->checkout->json_response->set_plz_select_method_of_payment(
1847
+				esc_html__('Please select a method of payment before proceeding.', 'event_espresso')
1848
+			);
1849
+			return false;
1850
+		}
1851
+		// get EE_Payment_Method object
1852
+		if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1853
+			return false;
1854
+		}
1855
+		// setup billing form
1856
+		if ($this->checkout->payment_method->is_on_site()) {
1857
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1858
+				$this->checkout->payment_method
1859
+			);
1860
+			// bad billing form ?
1861
+			if (! $this->_billing_form_is_valid()) {
1862
+				return false;
1863
+			}
1864
+		}
1865
+		// ensure primary registrant has been fully processed
1866
+		if (! $this->_setup_primary_registrant_prior_to_payment()) {
1867
+			return false;
1868
+		}
1869
+		// if session is close to expiring (under 10 minutes by default)
1870
+		if ((time() - EE_Registry::instance()->SSN->expiration()) < EE_Registry::instance()->SSN->extension()) {
1871
+			// add some time to session expiration so that payment can be completed
1872
+			EE_Registry::instance()->SSN->extend_expiration();
1873
+		}
1874
+		/** @type EE_Transaction_Processor $transaction_processor */
1875
+		// $transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
1876
+		// in case a registrant leaves to an Off-Site Gateway and never returns, we want to approve any registrations
1877
+		// for events with a default reg status of Approved
1878
+		// $transaction_processor->toggle_registration_statuses_for_default_approved_events(
1879
+		//      $this->checkout->transaction, $this->checkout->reg_cache_where_params
1880
+		// );
1881
+		// attempt payment
1882
+		$payment = $this->_attempt_payment($this->checkout->payment_method);
1883
+		// process results
1884
+		$payment = $this->_validate_payment($payment);
1885
+		$payment = $this->_post_payment_processing($payment);
1886
+		// verify payment
1887
+		if ($payment instanceof EE_Payment) {
1888
+			// store that for later
1889
+			$this->checkout->payment = $payment;
1890
+			// we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1891
+			$this->checkout->transaction->toggle_failed_transaction_status();
1892
+			$payment_status = $payment->status();
1893
+			if ($payment_status === EEM_Payment::status_id_approved
1894
+				|| $payment_status === EEM_Payment::status_id_pending
1895
+			) {
1896
+				return true;
1897
+			} else {
1898
+				return false;
1899
+			}
1900
+		} elseif ($payment === true) {
1901
+			// please note that offline payment methods will NOT make a payment,
1902
+			// but instead just mark themselves as the PMD_ID on the transaction, and return true
1903
+			$this->checkout->payment = $payment;
1904
+			return true;
1905
+		}
1906
+		// where's my money?
1907
+		return false;
1908
+	}
1909
+
1910
+
1911
+	/**
1912
+	 * _last_second_ticket_verifications
1913
+	 *
1914
+	 * @access public
1915
+	 * @return bool
1916
+	 * @throws EE_Error
1917
+	 */
1918
+	protected function _last_second_ticket_verifications()
1919
+	{
1920
+		// don't bother re-validating if not a return visit
1921
+		if (! $this->checkout->revisit) {
1922
+			return true;
1923
+		}
1924
+		$registrations = $this->checkout->transaction->registrations();
1925
+		if (empty($registrations)) {
1926
+			return false;
1927
+		}
1928
+		foreach ($registrations as $registration) {
1929
+			if ($registration instanceof EE_Registration && ! $registration->is_approved()) {
1930
+				$event = $registration->event_obj();
1931
+				if ($event instanceof EE_Event && $event->is_sold_out(true)) {
1932
+					EE_Error::add_error(
1933
+						apply_filters(
1934
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___last_second_ticket_verifications__sold_out_events_msg',
1935
+							sprintf(
1936
+								esc_html__(
1937
+									'It appears that the %1$s event that you were about to make a payment for has sold out since you first registered and/or arrived at this page. Please refresh the page and try again. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
1938
+									'event_espresso'
1939
+								),
1940
+								$event->name()
1941
+							)
1942
+						),
1943
+						__FILE__,
1944
+						__FUNCTION__,
1945
+						__LINE__
1946
+					);
1947
+					return false;
1948
+				}
1949
+			}
1950
+		}
1951
+		return true;
1952
+	}
1953
+
1954
+
1955
+	/**
1956
+	 * redirect_form
1957
+	 *
1958
+	 * @access public
1959
+	 * @return bool
1960
+	 * @throws EE_Error
1961
+	 * @throws InvalidArgumentException
1962
+	 * @throws ReflectionException
1963
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1964
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1965
+	 */
1966
+	public function redirect_form()
1967
+	{
1968
+		$payment_method_billing_info = $this->_payment_method_billing_info(
1969
+			$this->_get_payment_method_for_selected_method_of_payment()
1970
+		);
1971
+		$html = $payment_method_billing_info->get_html();
1972
+		$html .= $this->checkout->redirect_form;
1973
+		EE_Registry::instance()->REQ->add_output($html);
1974
+		return true;
1975
+	}
1976
+
1977
+
1978
+	/**
1979
+	 * _billing_form_is_valid
1980
+	 *
1981
+	 * @access private
1982
+	 * @return bool
1983
+	 * @throws \EE_Error
1984
+	 */
1985
+	private function _billing_form_is_valid()
1986
+	{
1987
+		if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1988
+			return true;
1989
+		}
1990
+		if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
1991
+			if ($this->checkout->billing_form->was_submitted()) {
1992
+				$this->checkout->billing_form->receive_form_submission();
1993
+				if ($this->checkout->billing_form->is_valid()) {
1994
+					return true;
1995
+				}
1996
+				$validation_errors = $this->checkout->billing_form->get_validation_errors_accumulated();
1997
+				$error_strings = array();
1998
+				foreach ($validation_errors as $validation_error) {
1999
+					if ($validation_error instanceof EE_Validation_Error) {
2000
+						$form_section = $validation_error->get_form_section();
2001
+						if ($form_section instanceof EE_Form_Input_Base) {
2002
+							$label = $form_section->html_label_text();
2003
+						} elseif ($form_section instanceof EE_Form_Section_Base) {
2004
+							$label = $form_section->name();
2005
+						} else {
2006
+							$label = esc_html__('Validation Error', 'event_espresso');
2007
+						}
2008
+						$error_strings[] = sprintf('%1$s: %2$s', $label, $validation_error->getMessage());
2009
+					}
2010
+				}
2011
+				EE_Error::add_error(
2012
+					sprintf(
2013
+						esc_html__(
2014
+							'One or more billing form inputs are invalid and require correction before proceeding. %1$s %2$s',
2015
+							'event_espresso'
2016
+						),
2017
+						'<br/>',
2018
+						implode('<br/>', $error_strings)
2019
+					),
2020
+					__FILE__,
2021
+					__FUNCTION__,
2022
+					__LINE__
2023
+				);
2024
+			} else {
2025
+				EE_Error::add_error(
2026
+					esc_html__(
2027
+						'The billing form was not submitted or something prevented it\'s submission.',
2028
+						'event_espresso'
2029
+					),
2030
+					__FILE__,
2031
+					__FUNCTION__,
2032
+					__LINE__
2033
+				);
2034
+			}
2035
+		} else {
2036
+			EE_Error::add_error(
2037
+				esc_html__(
2038
+					'The submitted billing form is invalid possibly due to a technical reason.',
2039
+					'event_espresso'
2040
+				),
2041
+				__FILE__,
2042
+				__FUNCTION__,
2043
+				__LINE__
2044
+			);
2045
+		}
2046
+		return false;
2047
+	}
2048
+
2049
+
2050
+	/**
2051
+	 * _setup_primary_registrant_prior_to_payment
2052
+	 * ensures that the primary registrant has a valid attendee object created with the critical details populated
2053
+	 * (first & last name & email) and that both the transaction object and primary registration object have been saved
2054
+	 * plz note that any other registrations will NOT be saved at this point (because they may not have any details
2055
+	 * yet)
2056
+	 *
2057
+	 * @access private
2058
+	 * @return bool
2059
+	 * @throws EE_Error
2060
+	 * @throws InvalidArgumentException
2061
+	 * @throws ReflectionException
2062
+	 * @throws RuntimeException
2063
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2064
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2065
+	 */
2066
+	private function _setup_primary_registrant_prior_to_payment()
2067
+	{
2068
+		// check if transaction has a primary registrant and that it has a related Attendee object
2069
+		// if not, then we need to at least gather some primary registrant data before attempting payment
2070
+		if ($this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
2071
+			&& ! $this->checkout->transaction_has_primary_registrant()
2072
+			&& ! $this->_capture_primary_registration_data_from_billing_form()
2073
+		) {
2074
+			return false;
2075
+		}
2076
+		// because saving an object clears it's cache, we need to do the chevy shuffle
2077
+		// grab the primary_registration object
2078
+		$primary_registration = $this->checkout->transaction->primary_registration();
2079
+		// at this point we'll consider a TXN to not have been failed
2080
+		$this->checkout->transaction->toggle_failed_transaction_status();
2081
+		// save the TXN ( which clears cached copy of primary_registration)
2082
+		$this->checkout->transaction->save();
2083
+		// grab TXN ID and save it to the primary_registration
2084
+		$primary_registration->set_transaction_id($this->checkout->transaction->ID());
2085
+		// save what we have so far
2086
+		$primary_registration->save();
2087
+		return true;
2088
+	}
2089
+
2090
+
2091
+	/**
2092
+	 * _capture_primary_registration_data_from_billing_form
2093
+	 *
2094
+	 * @access private
2095
+	 * @return bool
2096
+	 * @throws EE_Error
2097
+	 * @throws InvalidArgumentException
2098
+	 * @throws ReflectionException
2099
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2100
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2101
+	 */
2102
+	private function _capture_primary_registration_data_from_billing_form()
2103
+	{
2104
+		// convert billing form data into an attendee
2105
+		$this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2106
+		if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2107
+			EE_Error::add_error(
2108
+				sprintf(
2109
+					esc_html__(
2110
+						'The billing form details could not be used for attendee details due to a technical issue.%sPlease try again or contact %s for assistance.',
2111
+						'event_espresso'
2112
+					),
2113
+					'<br/>',
2114
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2115
+				),
2116
+				__FILE__,
2117
+				__FUNCTION__,
2118
+				__LINE__
2119
+			);
2120
+			return false;
2121
+		}
2122
+		$primary_registration = $this->checkout->transaction->primary_registration();
2123
+		if (! $primary_registration instanceof EE_Registration) {
2124
+			EE_Error::add_error(
2125
+				sprintf(
2126
+					esc_html__(
2127
+						'The primary registrant for this transaction could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2128
+						'event_espresso'
2129
+					),
2130
+					'<br/>',
2131
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2132
+				),
2133
+				__FILE__,
2134
+				__FUNCTION__,
2135
+				__LINE__
2136
+			);
2137
+			return false;
2138
+		}
2139
+		if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2140
+			  instanceof
2141
+			  EE_Attendee
2142
+		) {
2143
+			EE_Error::add_error(
2144
+				sprintf(
2145
+					esc_html__(
2146
+						'The primary registrant could not be associated with this transaction due to a technical issue.%sPlease try again or contact %s for assistance.',
2147
+						'event_espresso'
2148
+					),
2149
+					'<br/>',
2150
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2151
+				),
2152
+				__FILE__,
2153
+				__FUNCTION__,
2154
+				__LINE__
2155
+			);
2156
+			return false;
2157
+		}
2158
+		/** @type EE_Registration_Processor $registration_processor */
2159
+		$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
2160
+		// at this point, we should have enough details about the registrant to consider the registration NOT incomplete
2161
+		$registration_processor->toggle_incomplete_registration_status_to_default($primary_registration);
2162
+		return true;
2163
+	}
2164
+
2165
+
2166
+	/**
2167
+	 * _get_payment_method_for_selected_method_of_payment
2168
+	 * retrieves a valid payment method
2169
+	 *
2170
+	 * @access public
2171
+	 * @return EE_Payment_Method
2172
+	 * @throws EE_Error
2173
+	 * @throws InvalidArgumentException
2174
+	 * @throws ReflectionException
2175
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2176
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2177
+	 */
2178
+	private function _get_payment_method_for_selected_method_of_payment()
2179
+	{
2180
+		if ($this->checkout->selected_method_of_payment === 'events_sold_out') {
2181
+			$this->_redirect_because_event_sold_out();
2182
+			return null;
2183
+		}
2184
+		// get EE_Payment_Method object
2185
+		if (isset($this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ])) {
2186
+			$payment_method = $this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ];
2187
+		} else {
2188
+			// load EEM_Payment_Method
2189
+			EE_Registry::instance()->load_model('Payment_Method');
2190
+			/** @type EEM_Payment_Method $EEM_Payment_Method */
2191
+			$EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
2192
+			$payment_method = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2193
+		}
2194
+		// verify $payment_method
2195
+		if (! $payment_method instanceof EE_Payment_Method) {
2196
+			// not a payment
2197
+			EE_Error::add_error(
2198
+				sprintf(
2199
+					esc_html__(
2200
+						'The selected method of payment could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2201
+						'event_espresso'
2202
+					),
2203
+					'<br/>',
2204
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2205
+				),
2206
+				__FILE__,
2207
+				__FUNCTION__,
2208
+				__LINE__
2209
+			);
2210
+			return null;
2211
+		}
2212
+		// and verify it has a valid Payment_Method Type object
2213
+		if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2214
+			// not a payment
2215
+			EE_Error::add_error(
2216
+				sprintf(
2217
+					esc_html__(
2218
+						'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2219
+						'event_espresso'
2220
+					),
2221
+					'<br/>',
2222
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2223
+				),
2224
+				__FILE__,
2225
+				__FUNCTION__,
2226
+				__LINE__
2227
+			);
2228
+			return null;
2229
+		}
2230
+		return $payment_method;
2231
+	}
2232
+
2233
+
2234
+	/**
2235
+	 *    _attempt_payment
2236
+	 *
2237
+	 * @access    private
2238
+	 * @type    EE_Payment_Method $payment_method
2239
+	 * @return mixed EE_Payment | boolean
2240
+	 * @throws EE_Error
2241
+	 * @throws InvalidArgumentException
2242
+	 * @throws ReflectionException
2243
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2244
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2245
+	 */
2246
+	private function _attempt_payment(EE_Payment_Method $payment_method)
2247
+	{
2248
+		$payment = null;
2249
+		$this->checkout->transaction->save();
2250
+		$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2251
+		if (! $payment_processor instanceof EE_Payment_Processor) {
2252
+			return false;
2253
+		}
2254
+		try {
2255
+			$payment_processor->set_revisit($this->checkout->revisit);
2256
+			// generate payment object
2257
+			$payment = $payment_processor->process_payment(
2258
+				$payment_method,
2259
+				$this->checkout->transaction,
2260
+				$this->checkout->amount_owing,
2261
+				$this->checkout->billing_form,
2262
+				$this->_get_return_url($payment_method),
2263
+				'CART',
2264
+				$this->checkout->admin_request,
2265
+				true,
2266
+				$this->reg_step_url()
2267
+			);
2268
+		} catch (Exception $e) {
2269
+			$this->_handle_payment_processor_exception($e);
2270
+		}
2271
+		return $payment;
2272
+	}
2273
+
2274
+
2275
+	/**
2276
+	 * _handle_payment_processor_exception
2277
+	 *
2278
+	 * @access protected
2279
+	 * @param \Exception $e
2280
+	 * @return void
2281
+	 * @throws EE_Error
2282
+	 * @throws InvalidArgumentException
2283
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2284
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2285
+	 */
2286
+	protected function _handle_payment_processor_exception(Exception $e)
2287
+	{
2288
+		EE_Error::add_error(
2289
+			sprintf(
2290
+				esc_html__(
2291
+					'The payment could not br processed due to a technical issue.%1$sPlease try again or contact %2$s for assistance.||The following Exception was thrown in %4$s on line %5$s:%1$s%3$s',
2292
+					'event_espresso'
2293
+				),
2294
+				'<br/>',
2295
+				EE_Registry::instance()->CFG->organization->get_pretty('email'),
2296
+				$e->getMessage(),
2297
+				$e->getFile(),
2298
+				$e->getLine()
2299
+			),
2300
+			__FILE__,
2301
+			__FUNCTION__,
2302
+			__LINE__
2303
+		);
2304
+	}
2305
+
2306
+
2307
+	/**
2308
+	 * _get_return_url
2309
+	 *
2310
+	 * @access protected
2311
+	 * @param \EE_Payment_Method $payment_method
2312
+	 * @return string
2313
+	 * @throws \EE_Error
2314
+	 */
2315
+	protected function _get_return_url(EE_Payment_Method $payment_method)
2316
+	{
2317
+		$return_url = '';
2318
+		switch ($payment_method->type_obj()->payment_occurs()) {
2319
+			case EE_PMT_Base::offsite:
2320
+				$return_url = add_query_arg(
2321
+					array(
2322
+						'action'                     => 'process_gateway_response',
2323
+						'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2324
+						'spco_txn'                   => $this->checkout->transaction->ID(),
2325
+					),
2326
+					$this->reg_step_url()
2327
+				);
2328
+				break;
2329
+			case EE_PMT_Base::onsite:
2330
+			case EE_PMT_Base::offline:
2331
+				$return_url = $this->checkout->next_step->reg_step_url();
2332
+				break;
2333
+		}
2334
+		return $return_url;
2335
+	}
2336
+
2337
+
2338
+	/**
2339
+	 * _validate_payment
2340
+	 *
2341
+	 * @access private
2342
+	 * @param EE_Payment $payment
2343
+	 * @return EE_Payment|FALSE
2344
+	 * @throws EE_Error
2345
+	 * @throws InvalidArgumentException
2346
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2347
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2348
+	 */
2349
+	private function _validate_payment($payment = null)
2350
+	{
2351
+		if ($this->checkout->payment_method->is_off_line()) {
2352
+			return true;
2353
+		}
2354
+		// verify payment object
2355
+		if (! $payment instanceof EE_Payment) {
2356
+			// not a payment
2357
+			EE_Error::add_error(
2358
+				sprintf(
2359
+					esc_html__(
2360
+						'A valid payment was not generated due to a technical issue.%1$sPlease try again or contact %2$s for assistance.',
2361
+						'event_espresso'
2362
+					),
2363
+					'<br/>',
2364
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2365
+				),
2366
+				__FILE__,
2367
+				__FUNCTION__,
2368
+				__LINE__
2369
+			);
2370
+			return false;
2371
+		}
2372
+		return $payment;
2373
+	}
2374
+
2375
+
2376
+	/**
2377
+	 * _post_payment_processing
2378
+	 *
2379
+	 * @access private
2380
+	 * @param EE_Payment|bool $payment
2381
+	 * @return bool
2382
+	 * @throws EE_Error
2383
+	 * @throws InvalidArgumentException
2384
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2385
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2386
+	 */
2387
+	private function _post_payment_processing($payment = null)
2388
+	{
2389
+		// Off-Line payment?
2390
+		if ($payment === true) {
2391
+			// $this->_setup_redirect_for_next_step();
2392
+			return true;
2393
+			// On-Site payment?
2394
+		} elseif ($this->checkout->payment_method->is_on_site()) {
2395
+			if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2396
+				// $this->_setup_redirect_for_next_step();
2397
+				$this->checkout->continue_reg = false;
2398
+			}
2399
+			// Off-Site payment?
2400
+		} elseif ($this->checkout->payment_method->is_off_site()) {
2401
+			// if a payment object was made and it specifies a redirect url, then we'll setup that redirect info
2402
+			if ($payment instanceof EE_Payment && $payment->redirect_url()) {
2403
+				do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()');
2404
+				$this->checkout->redirect = true;
2405
+				$this->checkout->redirect_form = $payment->redirect_form();
2406
+				$this->checkout->redirect_url = $this->reg_step_url('redirect_form');
2407
+				// set JSON response
2408
+				$this->checkout->json_response->set_redirect_form($this->checkout->redirect_form);
2409
+				// and lastly, let's bump the payment status to pending
2410
+				$payment->set_status(EEM_Payment::status_id_pending);
2411
+				$payment->save();
2412
+			} else {
2413
+				// not a payment
2414
+				$this->checkout->continue_reg = false;
2415
+				EE_Error::add_error(
2416
+					sprintf(
2417
+						esc_html__(
2418
+							'It appears the Off Site Payment Method was not configured properly.%sPlease try again or contact %s for assistance.',
2419
+							'event_espresso'
2420
+						),
2421
+						'<br/>',
2422
+						EE_Registry::instance()->CFG->organization->get_pretty('email')
2423
+					),
2424
+					__FILE__,
2425
+					__FUNCTION__,
2426
+					__LINE__
2427
+				);
2428
+			}
2429
+		} else {
2430
+			// ummm ya... not Off-Line, not On-Site, not off-Site ????
2431
+			$this->checkout->continue_reg = false;
2432
+			return false;
2433
+		}
2434
+		return $payment;
2435
+	}
2436
+
2437
+
2438
+	/**
2439
+	 *    _process_payment_status
2440
+	 *
2441
+	 * @access private
2442
+	 * @type    EE_Payment $payment
2443
+	 * @param string       $payment_occurs
2444
+	 * @return bool
2445
+	 * @throws EE_Error
2446
+	 * @throws InvalidArgumentException
2447
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2448
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2449
+	 */
2450
+	private function _process_payment_status($payment, $payment_occurs = EE_PMT_Base::offline)
2451
+	{
2452
+		// off-line payment? carry on
2453
+		if ($payment_occurs === EE_PMT_Base::offline) {
2454
+			return true;
2455
+		}
2456
+		// verify payment validity
2457
+		if ($payment instanceof EE_Payment) {
2458
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()');
2459
+			$msg = $payment->gateway_response();
2460
+			// check results
2461
+			switch ($payment->status()) {
2462
+				// good payment
2463
+				case EEM_Payment::status_id_approved:
2464
+					EE_Error::add_success(
2465
+						esc_html__('Your payment was processed successfully.', 'event_espresso'),
2466
+						__FILE__,
2467
+						__FUNCTION__,
2468
+						__LINE__
2469
+					);
2470
+					return true;
2471
+					break;
2472
+				// slow payment
2473
+				case EEM_Payment::status_id_pending:
2474
+					if (empty($msg)) {
2475
+						$msg = esc_html__(
2476
+							'Your payment appears to have been processed successfully, but the Instant Payment Notification has not yet been received. It should arrive shortly.',
2477
+							'event_espresso'
2478
+						);
2479
+					}
2480
+					EE_Error::add_success($msg, __FILE__, __FUNCTION__, __LINE__);
2481
+					return true;
2482
+					break;
2483
+				// don't wanna payment
2484
+				case EEM_Payment::status_id_cancelled:
2485
+					if (empty($msg)) {
2486
+						$msg = _n(
2487
+							'Payment cancelled. Please try again.',
2488
+							'Payment cancelled. Please try again or select another method of payment.',
2489
+							count($this->checkout->available_payment_methods),
2490
+							'event_espresso'
2491
+						);
2492
+					}
2493
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2494
+					return false;
2495
+					break;
2496
+				// not enough payment
2497
+				case EEM_Payment::status_id_declined:
2498
+					if (empty($msg)) {
2499
+						$msg = _n(
2500
+							'We\'re sorry but your payment was declined. Please try again.',
2501
+							'We\'re sorry but your payment was declined. Please try again or select another method of payment.',
2502
+							count($this->checkout->available_payment_methods),
2503
+							'event_espresso'
2504
+						);
2505
+					}
2506
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2507
+					return false;
2508
+					break;
2509
+				// bad payment
2510
+				case EEM_Payment::status_id_failed:
2511
+					if (! empty($msg)) {
2512
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2513
+						return false;
2514
+					}
2515
+					// default to error below
2516
+					break;
2517
+			}
2518
+		}
2519
+		// off-site payment gateway responses are too unreliable, so let's just assume that
2520
+		// the payment processing is just running slower than the registrant's request
2521
+		if ($payment_occurs === EE_PMT_Base::offsite) {
2522
+			return true;
2523
+		}
2524
+		EE_Error::add_error(
2525
+			sprintf(
2526
+				esc_html__(
2527
+					'Your payment could not be processed successfully due to a technical issue.%sPlease try again or contact %s for assistance.',
2528
+					'event_espresso'
2529
+				),
2530
+				'<br/>',
2531
+				EE_Registry::instance()->CFG->organization->get_pretty('email')
2532
+			),
2533
+			__FILE__,
2534
+			__FUNCTION__,
2535
+			__LINE__
2536
+		);
2537
+		return false;
2538
+	}
2539
+
2540
+
2541
+
2542
+
2543
+
2544
+
2545
+	/********************************************************************************************************/
2546
+	/**********************************  PROCESS GATEWAY RESPONSE  **********************************/
2547
+	/********************************************************************************************************/
2548
+	/**
2549
+	 * process_gateway_response
2550
+	 * this is the return point for Off-Site Payment Methods
2551
+	 * It will attempt to "handle the IPN" if it appears that this has not already occurred,
2552
+	 * otherwise, it will load up the last payment made for the TXN.
2553
+	 * If the payment retrieved looks good, it will then either:
2554
+	 *    complete the current step and allow advancement to the next reg step
2555
+	 *        or present the payment options again
2556
+	 *
2557
+	 * @access private
2558
+	 * @return EE_Payment|FALSE
2559
+	 * @throws EE_Error
2560
+	 * @throws InvalidArgumentException
2561
+	 * @throws ReflectionException
2562
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2563
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2564
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2565
+	 */
2566
+	public function process_gateway_response()
2567
+	{
2568
+		$payment = null;
2569
+		// how have they chosen to pay?
2570
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2571
+		// get EE_Payment_Method object
2572
+		if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2573
+			$this->checkout->continue_reg = false;
2574
+			return false;
2575
+		}
2576
+		if (! $this->checkout->payment_method->is_off_site()) {
2577
+			return false;
2578
+		}
2579
+		$this->_validate_offsite_return();
2580
+		// DEBUG LOG
2581
+		// $this->checkout->log(
2582
+		//     __CLASS__,
2583
+		//     __FUNCTION__,
2584
+		//     __LINE__,
2585
+		//     array(
2586
+		//         'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2587
+		//         'payment_method'             => $this->checkout->payment_method,
2588
+		//     ),
2589
+		//     true
2590
+		// );
2591
+		// verify TXN
2592
+		if ($this->checkout->transaction instanceof EE_Transaction) {
2593
+			$gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2594
+			if (! $gateway instanceof EE_Offsite_Gateway) {
2595
+				$this->checkout->continue_reg = false;
2596
+				return false;
2597
+			}
2598
+			$payment = $this->_process_off_site_payment($gateway);
2599
+			$payment = $this->_process_cancelled_payments($payment);
2600
+			$payment = $this->_validate_payment($payment);
2601
+			// if payment was not declined by the payment gateway or cancelled by the registrant
2602
+			if ($this->_process_payment_status($payment, EE_PMT_Base::offsite)) {
2603
+				// $this->_setup_redirect_for_next_step();
2604
+				// store that for later
2605
+				$this->checkout->payment = $payment;
2606
+				// mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2607
+				// because we will complete this step during the IPN processing then
2608
+				if ($gateway instanceof EE_Offsite_Gateway && ! $this->handle_IPN_in_this_request()) {
2609
+					$this->set_completed();
2610
+				}
2611
+				return true;
2612
+			}
2613
+		}
2614
+		// DEBUG LOG
2615
+		// $this->checkout->log(
2616
+		//     __CLASS__,
2617
+		//     __FUNCTION__,
2618
+		//     __LINE__,
2619
+		//     array('payment' => $payment)
2620
+		// );
2621
+		$this->checkout->continue_reg = false;
2622
+		return false;
2623
+	}
2624
+
2625
+
2626
+	/**
2627
+	 * _validate_return
2628
+	 *
2629
+	 * @access private
2630
+	 * @return void
2631
+	 * @throws EE_Error
2632
+	 * @throws InvalidArgumentException
2633
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2634
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2635
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2636
+	 */
2637
+	private function _validate_offsite_return()
2638
+	{
2639
+		$TXN_ID = (int) EE_Registry::instance()->REQ->get('spco_txn', 0);
2640
+		if ($TXN_ID !== $this->checkout->transaction->ID()) {
2641
+			// Houston... we might have a problem
2642
+			$invalid_TXN = false;
2643
+			// first gather some info
2644
+			$valid_TXN = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2645
+			$primary_registrant = $valid_TXN instanceof EE_Transaction
2646
+				? $valid_TXN->primary_registration()
2647
+				: null;
2648
+			// let's start by retrieving the cart for this TXN
2649
+			$cart = $this->checkout->get_cart_for_transaction($this->checkout->transaction);
2650
+			if ($cart instanceof EE_Cart) {
2651
+				// verify that the current cart has tickets
2652
+				$tickets = $cart->get_tickets();
2653
+				if (empty($tickets)) {
2654
+					$invalid_TXN = true;
2655
+				}
2656
+			} else {
2657
+				$invalid_TXN = true;
2658
+			}
2659
+			$valid_TXN_SID = $primary_registrant instanceof EE_Registration
2660
+				? $primary_registrant->session_ID()
2661
+				: null;
2662
+			// validate current Session ID and compare against valid TXN session ID
2663
+			if ($invalid_TXN // if this is already true, then skip other checks
2664
+				|| EE_Session::instance()->id() === null
2665
+				|| (
2666
+					// WARNING !!!
2667
+					// this could be PayPal sending back duplicate requests (ya they do that)
2668
+					// or it **could** mean someone is simply registering AGAIN after having just done so
2669
+					// so now we need to determine if this current TXN looks valid or not
2670
+					// and whether this reg step has even been started ?
2671
+					EE_Session::instance()->id() === $valid_TXN_SID
2672
+					// really? you're half way through this reg step, but you never started it ?
2673
+					&& $this->checkout->transaction->reg_step_completed($this->slug()) === false
2674
+				)
2675
+			) {
2676
+				$invalid_TXN = true;
2677
+			}
2678
+			if ($invalid_TXN) {
2679
+				// is the valid TXN completed ?
2680
+				if ($valid_TXN instanceof EE_Transaction) {
2681
+					// has this step even been started ?
2682
+					$reg_step_completed = $valid_TXN->reg_step_completed($this->slug());
2683
+					if ($reg_step_completed !== false && $reg_step_completed !== true) {
2684
+						// so it **looks** like this is a double request from PayPal
2685
+						// so let's try to pick up where we left off
2686
+						$this->checkout->transaction = $valid_TXN;
2687
+						$this->checkout->refresh_all_entities(true);
2688
+						return;
2689
+					}
2690
+				}
2691
+				// you appear to be lost?
2692
+				$this->_redirect_wayward_request($primary_registrant);
2693
+			}
2694
+		}
2695
+	}
2696
+
2697
+
2698
+	/**
2699
+	 * _redirect_wayward_request
2700
+	 *
2701
+	 * @access private
2702
+	 * @param \EE_Registration|null $primary_registrant
2703
+	 * @return bool
2704
+	 * @throws EE_Error
2705
+	 * @throws InvalidArgumentException
2706
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2707
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2708
+	 */
2709
+	private function _redirect_wayward_request(EE_Registration $primary_registrant)
2710
+	{
2711
+		if (! $primary_registrant instanceof EE_Registration) {
2712
+			// try redirecting based on the current TXN
2713
+			$primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2714
+				? $this->checkout->transaction->primary_registration()
2715
+				: null;
2716
+		}
2717
+		if (! $primary_registrant instanceof EE_Registration) {
2718
+			EE_Error::add_error(
2719
+				sprintf(
2720
+					esc_html__(
2721
+						'Invalid information was received from the Off-Site Payment Processor and your Transaction details could not be retrieved from the database.%1$sPlease try again or contact %2$s for assistance.',
2722
+						'event_espresso'
2723
+					),
2724
+					'<br/>',
2725
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2726
+				),
2727
+				__FILE__,
2728
+				__FUNCTION__,
2729
+				__LINE__
2730
+			);
2731
+			return false;
2732
+		}
2733
+		// make sure transaction is not locked
2734
+		$this->checkout->transaction->unlock();
2735
+		wp_safe_redirect(
2736
+			add_query_arg(
2737
+				array(
2738
+					'e_reg_url_link' => $primary_registrant->reg_url_link(),
2739
+				),
2740
+				$this->checkout->thank_you_page_url
2741
+			)
2742
+		);
2743
+		exit();
2744
+	}
2745
+
2746
+
2747
+	/**
2748
+	 * _process_off_site_payment
2749
+	 *
2750
+	 * @access private
2751
+	 * @param \EE_Offsite_Gateway $gateway
2752
+	 * @return EE_Payment
2753
+	 * @throws EE_Error
2754
+	 * @throws InvalidArgumentException
2755
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2756
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2757
+	 */
2758
+	private function _process_off_site_payment(EE_Offsite_Gateway $gateway)
2759
+	{
2760
+		try {
2761
+			$request_data = \EE_Registry::instance()->REQ->params();
2762
+			// if gateway uses_separate_IPN_request, then we don't have to process the IPN manually
2763
+			$this->set_handle_IPN_in_this_request(
2764
+				$gateway->handle_IPN_in_this_request($request_data, false)
2765
+			);
2766
+			if ($this->handle_IPN_in_this_request()) {
2767
+				// get payment details and process results
2768
+				/** @type EE_Payment_Processor $payment_processor */
2769
+				$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2770
+				$payment = $payment_processor->process_ipn(
2771
+					$request_data,
2772
+					$this->checkout->transaction,
2773
+					$this->checkout->payment_method,
2774
+					true,
2775
+					false
2776
+				);
2777
+				// $payment_source = 'process_ipn';
2778
+			} else {
2779
+				$payment = $this->checkout->transaction->last_payment();
2780
+				// $payment_source = 'last_payment';
2781
+			}
2782
+		} catch (Exception $e) {
2783
+			// let's just eat the exception and try to move on using any previously set payment info
2784
+			$payment = $this->checkout->transaction->last_payment();
2785
+			// $payment_source = 'last_payment after Exception';
2786
+			// but if we STILL don't have a payment object
2787
+			if (! $payment instanceof EE_Payment) {
2788
+				// then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2789
+				$this->_handle_payment_processor_exception($e);
2790
+			}
2791
+		}
2792
+		// DEBUG LOG
2793
+		// $this->checkout->log(
2794
+		//     __CLASS__,
2795
+		//     __FUNCTION__,
2796
+		//     __LINE__,
2797
+		//     array(
2798
+		//         'process_ipn_payment' => $payment,
2799
+		//         'payment_source'      => $payment_source,
2800
+		//     )
2801
+		// );
2802
+		return $payment;
2803
+	}
2804
+
2805
+
2806
+	/**
2807
+	 * _process_cancelled_payments
2808
+	 * just makes sure that the payment status gets updated correctly
2809
+	 * so tha tan error isn't generated during payment validation
2810
+	 *
2811
+	 * @access private
2812
+	 * @param EE_Payment $payment
2813
+	 * @return EE_Payment | FALSE
2814
+	 * @throws \EE_Error
2815
+	 */
2816
+	private function _process_cancelled_payments($payment = null)
2817
+	{
2818
+		if ($payment instanceof EE_Payment
2819
+			&& isset($_REQUEST['ee_cancel_payment'])
2820
+			&& $payment->status() === EEM_Payment::status_id_failed
2821
+		) {
2822
+			$payment->set_status(EEM_Payment::status_id_cancelled);
2823
+		}
2824
+		return $payment;
2825
+	}
2826
+
2827
+
2828
+	/**
2829
+	 *    get_transaction_details_for_gateways
2830
+	 *
2831
+	 * @access    public
2832
+	 * @return int
2833
+	 * @throws EE_Error
2834
+	 * @throws InvalidArgumentException
2835
+	 * @throws ReflectionException
2836
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2837
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2838
+	 */
2839
+	public function get_transaction_details_for_gateways()
2840
+	{
2841
+		$txn_details = array();
2842
+		// ya gotta make a choice man
2843
+		if (empty($this->checkout->selected_method_of_payment)) {
2844
+			$txn_details = array(
2845
+				'error' => esc_html__('Please select a method of payment before proceeding.', 'event_espresso'),
2846
+			);
2847
+		}
2848
+		// get EE_Payment_Method object
2849
+		if (empty($txn_details)
2850
+			&&
2851
+			! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()
2852
+		) {
2853
+			$txn_details = array(
2854
+				'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2855
+				'error'                      => esc_html__(
2856
+					'A valid Payment Method could not be determined.',
2857
+					'event_espresso'
2858
+				),
2859
+			);
2860
+		}
2861
+		if (empty($txn_details) && $this->checkout->transaction instanceof EE_Transaction) {
2862
+			$return_url = $this->_get_return_url($this->checkout->payment_method);
2863
+			$txn_details = array(
2864
+				'TXN_ID'         => $this->checkout->transaction->ID(),
2865
+				'TXN_timestamp'  => $this->checkout->transaction->datetime(),
2866
+				'TXN_total'      => $this->checkout->transaction->total(),
2867
+				'TXN_paid'       => $this->checkout->transaction->paid(),
2868
+				'TXN_reg_steps'  => $this->checkout->transaction->reg_steps(),
2869
+				'STS_ID'         => $this->checkout->transaction->status_ID(),
2870
+				'PMD_ID'         => $this->checkout->transaction->payment_method_ID(),
2871
+				'payment_amount' => $this->checkout->amount_owing,
2872
+				'return_url'     => $return_url,
2873
+				'cancel_url'     => add_query_arg(array('ee_cancel_payment' => true), $return_url),
2874
+				'notify_url'     => EE_Config::instance()->core->txn_page_url(
2875
+					array(
2876
+						'e_reg_url_link'    => $this->checkout->transaction->primary_registration()->reg_url_link(),
2877
+						'ee_payment_method' => $this->checkout->payment_method->slug(),
2878
+					)
2879
+				),
2880
+			);
2881
+		}
2882
+		echo wp_json_encode($txn_details);
2883
+		exit();
2884
+	}
2885
+
2886
+
2887
+	/**
2888
+	 *    __sleep
2889
+	 * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon
2890
+	 * serialization EE_Checkout will handle the reimplementation of itself upon waking, but we won't bother with the
2891
+	 * reg form, because if needed, it will be regenerated anyways
2892
+	 *
2893
+	 * @return array
2894
+	 */
2895
+	public function __sleep()
2896
+	{
2897
+		// remove the reg form and the checkout
2898
+		return array_diff(array_keys(get_object_vars($this)), array('reg_form', 'checkout', 'line_item_display'));
2899
+	}
2900 2900
 }
Please login to merge, or discard this patch.
Spacing   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
     {
130 130
         $this->_slug = 'payment_options';
131 131
         $this->_name = esc_html__('Payment Options', 'event_espresso');
132
-        $this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
132
+        $this->_template = SPCO_REG_STEPS_PATH.$this->_slug.DS.'payment_options_main.template.php';
133 133
         $this->checkout = $checkout;
134 134
         $this->_reset_success_message();
135 135
         $this->set_instructions(
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
     {
213 213
         $transaction = $this->checkout->transaction;
214 214
         // if the transaction isn't set or nothing is owed on it, don't enqueue any JS
215
-        if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
215
+        if ( ! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
216 216
             return;
217 217
         }
218 218
         foreach (EEM_Payment_Method::instance()->get_all_for_transaction(
@@ -304,18 +304,18 @@  discard block
 block discarded – undo
304 304
         foreach ($registrations as $REG_ID => $registration) {
305 305
             /** @var $registration EE_Registration */
306 306
             // has this registration lost it's space ?
307
-            if (isset($ejected_registrations[ $REG_ID ])) {
307
+            if (isset($ejected_registrations[$REG_ID])) {
308 308
                 if ($registration->event()->is_sold_out() || $registration->event()->is_sold_out(true)) {
309
-                    $sold_out_events[ $registration->event()->ID() ] = $registration->event();
309
+                    $sold_out_events[$registration->event()->ID()] = $registration->event();
310 310
                 } else {
311
-                    $insufficient_spaces_available[ $registration->event()->ID() ] = $registration->event();
311
+                    $insufficient_spaces_available[$registration->event()->ID()] = $registration->event();
312 312
                 }
313 313
                 continue;
314 314
             }
315 315
             // event requires admin approval
316 316
             if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
317 317
                 // add event to list of events with pre-approval reg status
318
-                $registrations_requiring_pre_approval[ $REG_ID ] = $registration;
318
+                $registrations_requiring_pre_approval[$REG_ID] = $registration;
319 319
                 do_action(
320 320
                     'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
321 321
                     $registration->event(),
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
                 )
332 332
             ) {
333 333
                 // add event to list of events that are sold out
334
-                $sold_out_events[ $registration->event()->ID() ] = $registration->event();
334
+                $sold_out_events[$registration->event()->ID()] = $registration->event();
335 335
                 do_action(
336 336
                     'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
337 337
                     $registration->event(),
@@ -341,38 +341,38 @@  discard block
 block discarded – undo
341 341
             }
342 342
             // are they allowed to pay now and is there monies owing?
343 343
             if ($registration->owes_monies_and_can_pay()) {
344
-                $registrations_requiring_payment[ $REG_ID ] = $registration;
344
+                $registrations_requiring_payment[$REG_ID] = $registration;
345 345
                 do_action(
346 346
                     'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
347 347
                     $registration->event(),
348 348
                     $this
349 349
                 );
350
-            } elseif (! $this->checkout->revisit
350
+            } elseif ( ! $this->checkout->revisit
351 351
                       && $registration->status_ID() !== EEM_Registration::status_id_not_approved
352 352
                       && $registration->ticket()->is_free()
353 353
             ) {
354
-                $registrations_for_free_events[ $registration->event()->ID() ] = $registration;
354
+                $registrations_for_free_events[$registration->event()->ID()] = $registration;
355 355
             }
356 356
         }
357 357
         $subsections = array();
358 358
         // now decide which template to load
359
-        if (! empty($sold_out_events)) {
359
+        if ( ! empty($sold_out_events)) {
360 360
             $subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
361 361
         }
362
-        if (! empty($insufficient_spaces_available)) {
362
+        if ( ! empty($insufficient_spaces_available)) {
363 363
             $subsections['insufficient_space'] = $this->_insufficient_spaces_available(
364 364
                 $insufficient_spaces_available
365 365
             );
366 366
         }
367
-        if (! empty($registrations_requiring_pre_approval)) {
367
+        if ( ! empty($registrations_requiring_pre_approval)) {
368 368
             $subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
369 369
                 $registrations_requiring_pre_approval
370 370
             );
371 371
         }
372
-        if (! empty($registrations_for_free_events)) {
372
+        if ( ! empty($registrations_for_free_events)) {
373 373
             $subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
374 374
         }
375
-        if (! empty($registrations_requiring_payment)) {
375
+        if ( ! empty($registrations_requiring_payment)) {
376 376
             if ($this->checkout->amount_owing > 0) {
377 377
                 // autoload Line_Item_Display classes
378 378
                 EEH_Autoloader::register_line_item_filter_autoloaders();
@@ -437,13 +437,13 @@  discard block
 block discarded – undo
437 437
      */
438 438
     public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
439 439
     {
440
-        if (! EE_Registry::instance()->SSN instanceof EE_Session) {
440
+        if ( ! EE_Registry::instance()->SSN instanceof EE_Session) {
441 441
             return $line_item_filter_collection;
442 442
         }
443
-        if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
443
+        if ( ! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
444 444
             return $line_item_filter_collection;
445 445
         }
446
-        if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
446
+        if ( ! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
447 447
             return $line_item_filter_collection;
448 448
         }
449 449
         $line_item_filter_collection->add(
@@ -483,8 +483,8 @@  discard block
 block discarded – undo
483 483
         );
484 484
         foreach ($registrations as $REG_ID => $registration) {
485 485
             // has this registration lost it's space ?
486
-            if (isset($ejected_registrations[ $REG_ID ])) {
487
-                unset($registrations[ $REG_ID ]);
486
+            if (isset($ejected_registrations[$REG_ID])) {
487
+                unset($registrations[$REG_ID]);
488 488
                 continue;
489 489
             }
490 490
         }
@@ -534,24 +534,24 @@  discard block
 block discarded – undo
534 534
             }
535 535
             $EVT_ID = $registration->event_ID();
536 536
             $ticket = $registration->ticket();
537
-            if (! isset($tickets_remaining[ $ticket->ID() ])) {
538
-                $tickets_remaining[ $ticket->ID() ] = $ticket->remaining();
537
+            if ( ! isset($tickets_remaining[$ticket->ID()])) {
538
+                $tickets_remaining[$ticket->ID()] = $ticket->remaining();
539 539
             }
540
-            if ($tickets_remaining[ $ticket->ID() ] > 0) {
541
-                if (! isset($event_reg_count[ $EVT_ID ])) {
542
-                    $event_reg_count[ $EVT_ID ] = 0;
540
+            if ($tickets_remaining[$ticket->ID()] > 0) {
541
+                if ( ! isset($event_reg_count[$EVT_ID])) {
542
+                    $event_reg_count[$EVT_ID] = 0;
543 543
                 }
544
-                $event_reg_count[ $EVT_ID ]++;
545
-                if (! isset($event_spaces_remaining[ $EVT_ID ])) {
546
-                    $event_spaces_remaining[ $EVT_ID ] = $registration->event()->spaces_remaining_for_sale();
544
+                $event_reg_count[$EVT_ID]++;
545
+                if ( ! isset($event_spaces_remaining[$EVT_ID])) {
546
+                    $event_spaces_remaining[$EVT_ID] = $registration->event()->spaces_remaining_for_sale();
547 547
                 }
548 548
             }
549 549
             if ($revisit
550
-                && ($tickets_remaining[ $ticket->ID() ] === 0
551
-                    || $event_reg_count[ $EVT_ID ] > $event_spaces_remaining[ $EVT_ID ]
550
+                && ($tickets_remaining[$ticket->ID()] === 0
551
+                    || $event_reg_count[$EVT_ID] > $event_spaces_remaining[$EVT_ID]
552 552
                 )
553 553
             ) {
554
-                $ejected_registrations[ $REG_ID ] = $registration->event();
554
+                $ejected_registrations[$REG_ID] = $registration->event();
555 555
                 if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
556 556
                     /** @type EE_Registration_Processor $registration_processor */
557 557
                     $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
         foreach ($sold_out_events_array as $sold_out_event) {
612 612
             $sold_out_events .= EEH_HTML::li(
613 613
                 EEH_HTML::span(
614
-                    '  ' . $sold_out_event->name(),
614
+                    '  '.$sold_out_event->name(),
615 615
                     '',
616 616
                     'dashicons dashicons-marker ee-icon-size-16 pink-text'
617 617
                 )
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
         foreach ($insufficient_spaces_events_array as $event) {
668 668
             if ($event instanceof EE_Event) {
669 669
                 $insufficient_space_events .= EEH_HTML::li(
670
-                    EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
670
+                    EEH_HTML::span(' '.$event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
671 671
                 );
672 672
             }
673 673
         }
@@ -716,7 +716,7 @@  discard block
 block discarded – undo
716 716
         $events_requiring_pre_approval = '';
717 717
         foreach ($registrations_requiring_pre_approval as $registration) {
718 718
             if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
719
-                $events_requiring_pre_approval[ $registration->event()->ID() ] = EEH_HTML::li(
719
+                $events_requiring_pre_approval[$registration->event()->ID()] = EEH_HTML::li(
720 720
                     EEH_HTML::span(
721 721
                         '',
722 722
                         '',
@@ -857,7 +857,7 @@  discard block
 block discarded – undo
857 857
     {
858 858
         return new EE_Form_Section_Proper(
859 859
             array(
860
-                'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
860
+                'html_id'         => 'ee-'.$this->slug().'-extra-hidden-inputs',
861 861
                 'layout_strategy' => new EE_Div_Per_Section_Layout(),
862 862
                 'subsections'     => array(
863 863
                     'spco_no_payment_required' => new EE_Hidden_Input(
@@ -897,7 +897,7 @@  discard block
 block discarded – undo
897 897
                 $payments += $registration->registration_payments();
898 898
             }
899 899
         }
900
-        if (! empty($payments)) {
900
+        if ( ! empty($payments)) {
901 901
             foreach ($payments as $payment) {
902 902
                 if ($payment instanceof EE_Registration_Payment) {
903 903
                     $this->checkout->amount_owing -= $payment->amount();
@@ -1017,23 +1017,23 @@  discard block
 block discarded – undo
1017 1017
                 $payment_method_button = EEH_HTML::img(
1018 1018
                     $payment_method->button_url(),
1019 1019
                     $payment_method->name(),
1020
-                    'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1020
+                    'spco-payment-method-'.$payment_method->slug().'-btn-img',
1021 1021
                     'spco-payment-method-btn-img'
1022 1022
                 );
1023 1023
                 // check if any payment methods are set as default
1024 1024
                 // if payment method is already selected OR nothing is selected and this payment method should be
1025 1025
                 // open_by_default
1026 1026
                 if (($this->checkout->selected_method_of_payment === $payment_method->slug())
1027
-                    || (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1027
+                    || ( ! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1028 1028
                 ) {
1029 1029
                     $this->checkout->selected_method_of_payment = $payment_method->slug();
1030 1030
                     $this->_save_selected_method_of_payment();
1031
-                    $default_payment_method_option[ $payment_method->slug() ] = $payment_method_button;
1031
+                    $default_payment_method_option[$payment_method->slug()] = $payment_method_button;
1032 1032
                 } else {
1033
-                    $available_payment_method_options[ $payment_method->slug() ] = $payment_method_button;
1033
+                    $available_payment_method_options[$payment_method->slug()] = $payment_method_button;
1034 1034
                 }
1035
-                $payment_methods_billing_info[ $payment_method->slug(
1036
-                ) . '-info' ] = $this->_payment_method_billing_info(
1035
+                $payment_methods_billing_info[$payment_method->slug(
1036
+                ).'-info'] = $this->_payment_method_billing_info(
1037 1037
                     $payment_method
1038 1038
                 );
1039 1039
             }
@@ -1069,7 +1069,7 @@  discard block
 block discarded – undo
1069 1069
      */
1070 1070
     protected function _get_available_payment_methods()
1071 1071
     {
1072
-        if (! empty($this->checkout->available_payment_methods)) {
1072
+        if ( ! empty($this->checkout->available_payment_methods)) {
1073 1073
             return $this->checkout->available_payment_methods;
1074 1074
         }
1075 1075
         $available_payment_methods = array();
@@ -1084,7 +1084,7 @@  discard block
 block discarded – undo
1084 1084
         );
1085 1085
         foreach ($payment_methods as $payment_method) {
1086 1086
             if ($payment_method instanceof EE_Payment_Method) {
1087
-                $available_payment_methods[ $payment_method->slug() ] = $payment_method;
1087
+                $available_payment_methods[$payment_method->slug()] = $payment_method;
1088 1088
             }
1089 1089
         }
1090 1090
         return $available_payment_methods;
@@ -1179,7 +1179,7 @@  discard block
 block discarded – undo
1179 1179
         );
1180 1180
         return new EE_Form_Section_Proper(
1181 1181
             array(
1182
-                'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1182
+                'html_id'         => 'spco-payment-method-info-'.$payment_method->slug(),
1183 1183
                 'html_class'      => 'spco-payment-method-info-dv',
1184 1184
                 // only display the selected or default PM
1185 1185
                 'html_style'      => $currently_selected ? '' : 'display:none;',
@@ -1209,7 +1209,7 @@  discard block
 block discarded – undo
1209 1209
         // how have they chosen to pay?
1210 1210
         $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1211 1211
         $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1212
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1212
+        if ( ! $this->checkout->payment_method instanceof EE_Payment_Method) {
1213 1213
             return false;
1214 1214
         }
1215 1215
         if (apply_filters(
@@ -1381,7 +1381,7 @@  discard block
 block discarded – undo
1381 1381
      */
1382 1382
     public function switch_payment_method()
1383 1383
     {
1384
-        if (! $this->_verify_payment_method_is_set()) {
1384
+        if ( ! $this->_verify_payment_method_is_set()) {
1385 1385
             return false;
1386 1386
         }
1387 1387
         if (apply_filters(
@@ -1516,7 +1516,7 @@  discard block
 block discarded – undo
1516 1516
             }
1517 1517
         }
1518 1518
         // verify payment method
1519
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1519
+        if ( ! $this->checkout->payment_method instanceof EE_Payment_Method) {
1520 1520
             // get payment method for selected method of payment
1521 1521
             $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1522 1522
         }
@@ -1541,7 +1541,7 @@  discard block
 block discarded – undo
1541 1541
      */
1542 1542
     public function save_payer_details_via_ajax()
1543 1543
     {
1544
-        if (! $this->_verify_payment_method_is_set()) {
1544
+        if ( ! $this->_verify_payment_method_is_set()) {
1545 1545
             return;
1546 1546
         }
1547 1547
         // generate billing form for selected method of payment if it hasn't been done already
@@ -1551,7 +1551,7 @@  discard block
 block discarded – undo
1551 1551
             );
1552 1552
         }
1553 1553
         // generate primary attendee from payer info if applicable
1554
-        if (! $this->checkout->transaction_has_primary_registrant()) {
1554
+        if ( ! $this->checkout->transaction_has_primary_registrant()) {
1555 1555
             $attendee = $this->_create_attendee_from_request_data();
1556 1556
             if ($attendee instanceof EE_Attendee) {
1557 1557
                 foreach ($this->checkout->transaction->registrations() as $registration) {
@@ -1582,7 +1582,7 @@  discard block
 block discarded – undo
1582 1582
     {
1583 1583
         // get State ID
1584 1584
         $STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1585
-        if (! empty($STA_ID)) {
1585
+        if ( ! empty($STA_ID)) {
1586 1586
             // can we get state object from name ?
1587 1587
             EE_Registry::instance()->load_model('State');
1588 1588
             $state = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
@@ -1590,7 +1590,7 @@  discard block
 block discarded – undo
1590 1590
         }
1591 1591
         // get Country ISO
1592 1592
         $CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1593
-        if (! empty($CNT_ISO)) {
1593
+        if ( ! empty($CNT_ISO)) {
1594 1594
             // can we get country object from name ?
1595 1595
             EE_Registry::instance()->load_model('Country');
1596 1596
             $country = EEM_Country::instance()->get_col(
@@ -1623,7 +1623,7 @@  discard block
 block discarded – undo
1623 1623
         }
1624 1624
         // does this attendee already exist in the db ? we're searching using a combination of first name, last name,
1625 1625
         // AND email address
1626
-        if (! empty($attendee_data['ATT_fname'])
1626
+        if ( ! empty($attendee_data['ATT_fname'])
1627 1627
             && ! empty($attendee_data['ATT_lname'])
1628 1628
             && ! empty($attendee_data['ATT_email'])
1629 1629
         ) {
@@ -1838,7 +1838,7 @@  discard block
 block discarded – undo
1838 1838
     private function _process_payment()
1839 1839
     {
1840 1840
         // basically confirm that the event hasn't sold out since they hit the page
1841
-        if (! $this->_last_second_ticket_verifications()) {
1841
+        if ( ! $this->_last_second_ticket_verifications()) {
1842 1842
             return false;
1843 1843
         }
1844 1844
         // ya gotta make a choice man
@@ -1849,7 +1849,7 @@  discard block
 block discarded – undo
1849 1849
             return false;
1850 1850
         }
1851 1851
         // get EE_Payment_Method object
1852
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1852
+        if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1853 1853
             return false;
1854 1854
         }
1855 1855
         // setup billing form
@@ -1858,12 +1858,12 @@  discard block
 block discarded – undo
1858 1858
                 $this->checkout->payment_method
1859 1859
             );
1860 1860
             // bad billing form ?
1861
-            if (! $this->_billing_form_is_valid()) {
1861
+            if ( ! $this->_billing_form_is_valid()) {
1862 1862
                 return false;
1863 1863
             }
1864 1864
         }
1865 1865
         // ensure primary registrant has been fully processed
1866
-        if (! $this->_setup_primary_registrant_prior_to_payment()) {
1866
+        if ( ! $this->_setup_primary_registrant_prior_to_payment()) {
1867 1867
             return false;
1868 1868
         }
1869 1869
         // if session is close to expiring (under 10 minutes by default)
@@ -1918,7 +1918,7 @@  discard block
 block discarded – undo
1918 1918
     protected function _last_second_ticket_verifications()
1919 1919
     {
1920 1920
         // don't bother re-validating if not a return visit
1921
-        if (! $this->checkout->revisit) {
1921
+        if ( ! $this->checkout->revisit) {
1922 1922
             return true;
1923 1923
         }
1924 1924
         $registrations = $this->checkout->transaction->registrations();
@@ -1984,7 +1984,7 @@  discard block
 block discarded – undo
1984 1984
      */
1985 1985
     private function _billing_form_is_valid()
1986 1986
     {
1987
-        if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1987
+        if ( ! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1988 1988
             return true;
1989 1989
         }
1990 1990
         if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
@@ -2103,7 +2103,7 @@  discard block
 block discarded – undo
2103 2103
     {
2104 2104
         // convert billing form data into an attendee
2105 2105
         $this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2106
-        if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2106
+        if ( ! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2107 2107
             EE_Error::add_error(
2108 2108
                 sprintf(
2109 2109
                     esc_html__(
@@ -2120,7 +2120,7 @@  discard block
 block discarded – undo
2120 2120
             return false;
2121 2121
         }
2122 2122
         $primary_registration = $this->checkout->transaction->primary_registration();
2123
-        if (! $primary_registration instanceof EE_Registration) {
2123
+        if ( ! $primary_registration instanceof EE_Registration) {
2124 2124
             EE_Error::add_error(
2125 2125
                 sprintf(
2126 2126
                     esc_html__(
@@ -2136,7 +2136,7 @@  discard block
 block discarded – undo
2136 2136
             );
2137 2137
             return false;
2138 2138
         }
2139
-        if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2139
+        if ( ! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2140 2140
               instanceof
2141 2141
               EE_Attendee
2142 2142
         ) {
@@ -2182,8 +2182,8 @@  discard block
 block discarded – undo
2182 2182
             return null;
2183 2183
         }
2184 2184
         // get EE_Payment_Method object
2185
-        if (isset($this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ])) {
2186
-            $payment_method = $this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ];
2185
+        if (isset($this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment])) {
2186
+            $payment_method = $this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment];
2187 2187
         } else {
2188 2188
             // load EEM_Payment_Method
2189 2189
             EE_Registry::instance()->load_model('Payment_Method');
@@ -2192,7 +2192,7 @@  discard block
 block discarded – undo
2192 2192
             $payment_method = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2193 2193
         }
2194 2194
         // verify $payment_method
2195
-        if (! $payment_method instanceof EE_Payment_Method) {
2195
+        if ( ! $payment_method instanceof EE_Payment_Method) {
2196 2196
             // not a payment
2197 2197
             EE_Error::add_error(
2198 2198
                 sprintf(
@@ -2210,7 +2210,7 @@  discard block
 block discarded – undo
2210 2210
             return null;
2211 2211
         }
2212 2212
         // and verify it has a valid Payment_Method Type object
2213
-        if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2213
+        if ( ! $payment_method->type_obj() instanceof EE_PMT_Base) {
2214 2214
             // not a payment
2215 2215
             EE_Error::add_error(
2216 2216
                 sprintf(
@@ -2248,7 +2248,7 @@  discard block
 block discarded – undo
2248 2248
         $payment = null;
2249 2249
         $this->checkout->transaction->save();
2250 2250
         $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2251
-        if (! $payment_processor instanceof EE_Payment_Processor) {
2251
+        if ( ! $payment_processor instanceof EE_Payment_Processor) {
2252 2252
             return false;
2253 2253
         }
2254 2254
         try {
@@ -2352,7 +2352,7 @@  discard block
 block discarded – undo
2352 2352
             return true;
2353 2353
         }
2354 2354
         // verify payment object
2355
-        if (! $payment instanceof EE_Payment) {
2355
+        if ( ! $payment instanceof EE_Payment) {
2356 2356
             // not a payment
2357 2357
             EE_Error::add_error(
2358 2358
                 sprintf(
@@ -2392,7 +2392,7 @@  discard block
 block discarded – undo
2392 2392
             return true;
2393 2393
             // On-Site payment?
2394 2394
         } elseif ($this->checkout->payment_method->is_on_site()) {
2395
-            if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2395
+            if ( ! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2396 2396
                 // $this->_setup_redirect_for_next_step();
2397 2397
                 $this->checkout->continue_reg = false;
2398 2398
             }
@@ -2508,7 +2508,7 @@  discard block
 block discarded – undo
2508 2508
                     break;
2509 2509
                 // bad payment
2510 2510
                 case EEM_Payment::status_id_failed:
2511
-                    if (! empty($msg)) {
2511
+                    if ( ! empty($msg)) {
2512 2512
                         EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2513 2513
                         return false;
2514 2514
                     }
@@ -2569,11 +2569,11 @@  discard block
 block discarded – undo
2569 2569
         // how have they chosen to pay?
2570 2570
         $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2571 2571
         // get EE_Payment_Method object
2572
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2572
+        if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2573 2573
             $this->checkout->continue_reg = false;
2574 2574
             return false;
2575 2575
         }
2576
-        if (! $this->checkout->payment_method->is_off_site()) {
2576
+        if ( ! $this->checkout->payment_method->is_off_site()) {
2577 2577
             return false;
2578 2578
         }
2579 2579
         $this->_validate_offsite_return();
@@ -2591,7 +2591,7 @@  discard block
 block discarded – undo
2591 2591
         // verify TXN
2592 2592
         if ($this->checkout->transaction instanceof EE_Transaction) {
2593 2593
             $gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2594
-            if (! $gateway instanceof EE_Offsite_Gateway) {
2594
+            if ( ! $gateway instanceof EE_Offsite_Gateway) {
2595 2595
                 $this->checkout->continue_reg = false;
2596 2596
                 return false;
2597 2597
             }
@@ -2708,13 +2708,13 @@  discard block
 block discarded – undo
2708 2708
      */
2709 2709
     private function _redirect_wayward_request(EE_Registration $primary_registrant)
2710 2710
     {
2711
-        if (! $primary_registrant instanceof EE_Registration) {
2711
+        if ( ! $primary_registrant instanceof EE_Registration) {
2712 2712
             // try redirecting based on the current TXN
2713 2713
             $primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2714 2714
                 ? $this->checkout->transaction->primary_registration()
2715 2715
                 : null;
2716 2716
         }
2717
-        if (! $primary_registrant instanceof EE_Registration) {
2717
+        if ( ! $primary_registrant instanceof EE_Registration) {
2718 2718
             EE_Error::add_error(
2719 2719
                 sprintf(
2720 2720
                     esc_html__(
@@ -2784,7 +2784,7 @@  discard block
 block discarded – undo
2784 2784
             $payment = $this->checkout->transaction->last_payment();
2785 2785
             // $payment_source = 'last_payment after Exception';
2786 2786
             // but if we STILL don't have a payment object
2787
-            if (! $payment instanceof EE_Payment) {
2787
+            if ( ! $payment instanceof EE_Payment) {
2788 2788
                 // then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2789 2789
                 $this->_handle_payment_processor_exception($e);
2790 2790
             }
Please login to merge, or discard this patch.
core/db_classes/EE_Message_Template_Group.class.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -211,7 +211,7 @@
 block discarded – undo
211 211
      * appropriately.
212 212
      *
213 213
      * @throws EE_Error
214
-     * @return EE_message_type|false if exception thrown.
214
+     * @return null|EE_message_type if exception thrown.
215 215
      */
216 216
     public function message_type_obj()
217 217
     {
Please login to merge, or discard this patch.
Indentation   +483 added lines, -483 removed lines patch added patch discarded remove patch
@@ -13,487 +13,487 @@
 block discarded – undo
13 13
 class EE_Message_Template_Group extends EE_Soft_Delete_Base_Class
14 14
 {
15 15
 
16
-    /**
17
-     * Extra Meta key prefix for whether a given context for this message tmeplate group is active or not.
18
-     */
19
-    const ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX = 'active_context_';
20
-
21
-    /**
22
-     * @param array  $props_n_values
23
-     * @param string $timezone
24
-     * @return EE_Message_Template_Group|mixed
25
-     * @throws EE_Error
26
-     */
27
-    public static function new_instance($props_n_values = array(), $timezone = '')
28
-    {
29
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone);
30
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone);
31
-    }
32
-
33
-
34
-    /**
35
-     * @param array  $props_n_values
36
-     * @param string $timezone
37
-     * @return EE_Message_Template_Group
38
-     */
39
-    public static function new_instance_from_db($props_n_values = array(), $timezone = '')
40
-    {
41
-        return new self($props_n_values, true, $timezone);
42
-    }
43
-
44
-
45
-    /**
46
-     * @param bool $message_type
47
-     * @throws EE_Error
48
-     */
49
-    public function set_message_type($message_type = false)
50
-    {
51
-        if (! $message_type) {
52
-            throw new EE_Error(esc_html__('Missing required value for the message_type parameter', 'event_espresso'));
53
-        }
54
-        $this->set('MTP_message_type', $message_type);
55
-    }
56
-
57
-
58
-    /**
59
-     * @param bool $messenger
60
-     * @throws EE_Error
61
-     */
62
-    public function set_messenger($messenger = false)
63
-    {
64
-        if (! $messenger) {
65
-            throw new EE_Error(esc_html__('Missing required value for the messenger parameter', 'event_espresso'));
66
-        }
67
-        $this->set('MTP_messenger', $messenger);
68
-    }
69
-
70
-
71
-    /**
72
-     * @param bool $GRP_ID
73
-     * @throws EE_Error
74
-     */
75
-    public function set_group_template_id($GRP_ID = false)
76
-    {
77
-        if (! $GRP_ID) {
78
-            throw new EE_Error(
79
-                esc_html__(
80
-                    'Missing required value for the message template group id',
81
-                    'event_espresso'
82
-                )
83
-            );
84
-        }
85
-        $this->set('GRP_ID', $GRP_ID);
86
-    }
87
-
88
-
89
-    /**
90
-     * get Group ID
91
-     *
92
-     * @access public
93
-     * @return int
94
-     * @throws EE_Error
95
-     */
96
-    public function GRP_ID()
97
-    {
98
-        return $this->get('GRP_ID');
99
-    }
100
-
101
-
102
-    /**
103
-     * get User ID
104
-     *
105
-     * @access public
106
-     * @return int
107
-     * @throws EE_Error
108
-     */
109
-    public function user()
110
-    {
111
-        $user_id = $this->get('MTP_user_id');
112
-        return empty($user_id) ? get_current_user_id() : $user_id;
113
-    }
114
-
115
-
116
-    /**
117
-     * Wrapper for the user function() (preserve backward compat)
118
-     *
119
-     * @since  4.5.0
120
-     * @return int
121
-     * @throws EE_Error
122
-     */
123
-    public function wp_user()
124
-    {
125
-        return $this->user();
126
-    }
127
-
128
-
129
-    /**
130
-     * This simply returns a count of all related events to this message template group
131
-     *
132
-     * @return int
133
-     */
134
-    public function count_events()
135
-    {
136
-        return $this->count_related('Event');
137
-    }
138
-
139
-
140
-    /**
141
-     * returns the name saved in the db for this template
142
-     *
143
-     * @return string
144
-     * @throws EE_Error
145
-     */
146
-    public function name()
147
-    {
148
-        return $this->get('MTP_name');
149
-    }
150
-
151
-
152
-    /**
153
-     * Returns the description saved in the db for this template group
154
-     *
155
-     * @return string
156
-     * @throws EE_Error
157
-     */
158
-    public function description()
159
-    {
160
-        return $this->get('MTP_description');
161
-    }
162
-
163
-
164
-    /**
165
-     * returns all related EE_Message_Template objects
166
-     *
167
-     * @param  array $query_params like EEM_Base::get_all()
168
-     * @return EE_Message_Template[]
169
-     * @throws EE_Error
170
-     */
171
-    public function message_templates($query_params = array())
172
-    {
173
-        return $this->get_many_related('Message_Template', $query_params);
174
-    }
175
-
176
-
177
-    /**
178
-     * get Message Messenger
179
-     *
180
-     * @access public
181
-     * @return string
182
-     * @throws EE_Error
183
-     */
184
-    public function messenger()
185
-    {
186
-        return $this->get('MTP_messenger');
187
-    }
188
-
189
-
190
-    /**
191
-     * get Message Messenger OBJECT
192
-     * If an attempt to get the corresponding messenger object fails, then we set this message
193
-     * template group to inactive, and save to db.  Then return null so client code can handle
194
-     * appropriately.
195
-     *
196
-     * @return EE_messenger
197
-     * @throws EE_Error
198
-     */
199
-    public function messenger_obj()
200
-    {
201
-        $messenger = $this->messenger();
202
-        try {
203
-            $messenger = EEH_MSG_Template::messenger_obj($messenger);
204
-        } catch (EE_Error $e) {
205
-            // if an exception was thrown then let's deactivate this message template group because it means there is no
206
-            // class for this messenger in this group.
207
-            $this->set('MTP_is_active', false);
208
-            $this->save();
209
-            return null;
210
-        }
211
-        return $messenger;
212
-    }
213
-
214
-
215
-    /**
216
-     * get Message Type
217
-     *
218
-     * @access public
219
-     * @return string
220
-     * @throws EE_Error
221
-     */
222
-    public function message_type()
223
-    {
224
-        return $this->get('MTP_message_type');
225
-    }
226
-
227
-
228
-    /**
229
-     * get Message type OBJECT
230
-     * If an attempt to get the corresponding message type object fails, then we set this message
231
-     * template group to inactive, and save to db.  Then return null so client code can handle
232
-     * appropriately.
233
-     *
234
-     * @throws EE_Error
235
-     * @return EE_message_type|false if exception thrown.
236
-     */
237
-    public function message_type_obj()
238
-    {
239
-        $message_type = $this->message_type();
240
-        try {
241
-            $message_type = EEH_MSG_Template::message_type_obj($message_type);
242
-        } catch (EE_Error $e) {
243
-            // if an exception was thrown then let's deactivate this message template group because it means there is no
244
-            // class for the message type in this group.
245
-            $this->set('MTP_is_active', false);
246
-            $this->save();
247
-            return null;
248
-        }
249
-        return $message_type;
250
-    }
251
-
252
-
253
-    /**
254
-     * @return array
255
-     * @throws EE_Error
256
-     */
257
-    public function contexts_config()
258
-    {
259
-        return $this->message_type_obj()->get_contexts();
260
-    }
261
-
262
-
263
-    /**
264
-     * This returns the context_label for contexts as set in the message type object
265
-     * Note this is an array with singular and plural keys
266
-     *
267
-     * @access public
268
-     * @return array labels for "context"
269
-     * @throws EE_Error
270
-     */
271
-    public function context_label()
272
-    {
273
-        $obj = $this->message_type_obj();
274
-        return $obj->get_context_label();
275
-    }
276
-
277
-
278
-    /**
279
-     * This returns an array of EE_Message_Template objects indexed by context and field.
280
-     *
281
-     * @return array ()
282
-     * @throws EE_Error
283
-     */
284
-    public function context_templates()
285
-    {
286
-        $mtps_arr = array();
287
-        $mtps = $this->get_many_related('Message_Template');
288
-        if (empty($mtps)) {
289
-            return array();
290
-        }
291
-        // note contexts could have CHECKBOX fields per context. So we return the objects indexed by context AND field.
292
-        foreach ($mtps as $mtp) {
293
-            $mtps_arr[ $mtp->get('MTP_context') ][ $mtp->get('MTP_template_field') ] = $mtp;
294
-        }
295
-        return $mtps_arr;
296
-    }
297
-
298
-
299
-    /**
300
-     * this returns if the template group this template belongs to is global
301
-     *
302
-     * @return bool true if it is, false if it isn't
303
-     * @throws EE_Error
304
-     */
305
-    public function is_global()
306
-    {
307
-        return $this->get('MTP_is_global');
308
-    }
309
-
310
-
311
-    /**
312
-     * this returns if the template group this template belongs to is active (i.e. turned "on" or not)
313
-     *
314
-     * @return bool true if it is, false if it isn't
315
-     * @throws EE_Error
316
-     */
317
-    public function is_active()
318
-    {
319
-        return $this->get('MTP_is_active');
320
-    }
321
-
322
-
323
-    /**
324
-     * This will return an array of shortcodes => labels from the messenger and message_type objects associated with
325
-     * this template.
326
-     *
327
-     * @since 4.3.0
328
-     * @uses  EEH_MSG_Template::get_shortcodes()
329
-     * @param string $context what context we're going to return shortcodes for
330
-     * @param array  $fields  what fields we're returning valid shortcodes for.  If empty then we assume all fields are
331
-     *                        to be returned.
332
-     * @param bool   $merged  If TRUE then we don't return shortcodes indexed by field but instead an array of the
333
-     *                        unique shortcodes for all the given (or all) fields.
334
-     * @return mixed (array|bool) an array of shortcodes in the format array( '[shortcode] => 'label') OR FALSE if no
335
-     *                        shortcodes found.
336
-     * @throws EE_Error
337
-     */
338
-    public function get_shortcodes($context, $fields = array(), $merged = false)
339
-    {
340
-        $messenger = $this->messenger();
341
-        $message_type = $this->message_type();
342
-        return EEH_MSG_Template::get_shortcodes($message_type, $messenger, $fields, $context, $merged);
343
-    }
344
-
345
-
346
-    /**
347
-     * This just gets the template pack name assigned to this message template group.  If it's not set, then we just
348
-     * use the default template pack.
349
-     *
350
-     * @since 4.5.0
351
-     * @return string
352
-     * @throws EE_Error
353
-     */
354
-    public function get_template_pack_name()
355
-    {
356
-        return $this->get_extra_meta('MTP_template_pack', true, 'default');
357
-    }
358
-
359
-
360
-    /**
361
-     * This returns the specific template pack object referenced by the template pack name attached to this message
362
-     * template group.  If no template pack is assigned then the default template pack is retrieved.
363
-     *
364
-     * @since 4.5.0
365
-     * @return EE_Messages_Template_Pack
366
-     * @throws EE_Error
367
-     * @throws InvalidArgumentException
368
-     * @throws ReflectionException
369
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
370
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
371
-     */
372
-    public function get_template_pack()
373
-    {
374
-        $pack_name = $this->get_template_pack_name();
375
-        EE_Registry::instance()->load_helper('MSG_Template');
376
-        return EEH_MSG_Template::get_template_pack($pack_name);
377
-    }
378
-
379
-
380
-    /**
381
-     * This retrieves the template variation assigned to this message template group.  If it's not set, then we just
382
-     * use the default template variation.
383
-     *
384
-     * @since 4.5.0
385
-     * @return string
386
-     * @throws EE_Error
387
-     */
388
-    public function get_template_pack_variation()
389
-    {
390
-        return $this->get_extra_meta('MTP_variation', true, 'default');
391
-    }
392
-
393
-
394
-    /**
395
-     * This just sets the template pack name attached to this message template group.
396
-     *
397
-     * @since 4.5.0
398
-     * @param string $template_pack_name What message template pack is assigned.
399
-     * @return int
400
-     * @throws EE_Error
401
-     */
402
-    public function set_template_pack_name($template_pack_name)
403
-    {
404
-        return $this->update_extra_meta('MTP_template_pack', $template_pack_name);
405
-    }
406
-
407
-
408
-    /**
409
-     * This just sets the template pack variation attached to this message template group.
410
-     *
411
-     * @since 4.5.0
412
-     * @param string $variation What variation is being set on the message template group.
413
-     * @return int
414
-     * @throws EE_Error
415
-     */
416
-    public function set_template_pack_variation($variation)
417
-    {
418
-        return $this->update_extra_meta('MTP_variation', $variation);
419
-    }
420
-
421
-
422
-    /**
423
-     * Deactivates the given context.
424
-     *
425
-     * @param $context
426
-     * @return bool|int
427
-     * @throws EE_Error
428
-     * @throws InvalidIdentifierException
429
-     */
430
-    public function deactivate_context($context)
431
-    {
432
-        $this->validate_context($context);
433
-        return $this->update_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, false);
434
-    }
435
-
436
-
437
-    /**
438
-     * Activates the given context.
439
-     *
440
-     * @param $context
441
-     * @return bool|int
442
-     * @throws EE_Error
443
-     * @throws InvalidIdentifierException
444
-     */
445
-    public function activate_context($context)
446
-    {
447
-        $this->validate_context($context);
448
-        return $this->update_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, true);
449
-    }
450
-
451
-
452
-    /**
453
-     * Returns whether the context is active or not.
454
-     * Note, this will default to true if the extra meta record doesn't exist.
455
-     * Also, this does NOT account for whether the "To" field is empty or not. Some messengers may allow the "To" field
456
-     * to be empty (@see EE_Messenger::allow_empty_to_field()) so an empty "To" field is not always an indicator of
457
-     * whether a context is "active" or not.
458
-     *
459
-     * @param $context
460
-     * @return bool
461
-     * @throws EE_Error
462
-     * @throws InvalidIdentifierException
463
-     */
464
-    public function is_context_active($context)
465
-    {
466
-        $this->validate_context($context);
467
-        return filter_var(
468
-            $this->get_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, true, true),
469
-            FILTER_VALIDATE_BOOLEAN
470
-        );
471
-    }
472
-
473
-
474
-    /**
475
-     * Validates the incoming context to verify it matches a registered context for the related message type.
476
-     *
477
-     * @param string $context
478
-     * @throws EE_Error
479
-     * @throws InvalidIdentifierException
480
-     */
481
-    public function validate_context($context)
482
-    {
483
-        $contexts = $this->contexts_config();
484
-        if (! isset($contexts[ $context ])) {
485
-            throw new InvalidIdentifierException(
486
-                '',
487
-                '',
488
-                sprintf(
489
-                    esc_html__(
490
-                        'An invalid string identifying a context was provided.  "%1$s" was received, and one of "%2$s" was expected.',
491
-                        'event_espresso'
492
-                    ),
493
-                    $context,
494
-                    implode(',', array_keys($contexts))
495
-                )
496
-            );
497
-        }
498
-    }
16
+	/**
17
+	 * Extra Meta key prefix for whether a given context for this message tmeplate group is active or not.
18
+	 */
19
+	const ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX = 'active_context_';
20
+
21
+	/**
22
+	 * @param array  $props_n_values
23
+	 * @param string $timezone
24
+	 * @return EE_Message_Template_Group|mixed
25
+	 * @throws EE_Error
26
+	 */
27
+	public static function new_instance($props_n_values = array(), $timezone = '')
28
+	{
29
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone);
30
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone);
31
+	}
32
+
33
+
34
+	/**
35
+	 * @param array  $props_n_values
36
+	 * @param string $timezone
37
+	 * @return EE_Message_Template_Group
38
+	 */
39
+	public static function new_instance_from_db($props_n_values = array(), $timezone = '')
40
+	{
41
+		return new self($props_n_values, true, $timezone);
42
+	}
43
+
44
+
45
+	/**
46
+	 * @param bool $message_type
47
+	 * @throws EE_Error
48
+	 */
49
+	public function set_message_type($message_type = false)
50
+	{
51
+		if (! $message_type) {
52
+			throw new EE_Error(esc_html__('Missing required value for the message_type parameter', 'event_espresso'));
53
+		}
54
+		$this->set('MTP_message_type', $message_type);
55
+	}
56
+
57
+
58
+	/**
59
+	 * @param bool $messenger
60
+	 * @throws EE_Error
61
+	 */
62
+	public function set_messenger($messenger = false)
63
+	{
64
+		if (! $messenger) {
65
+			throw new EE_Error(esc_html__('Missing required value for the messenger parameter', 'event_espresso'));
66
+		}
67
+		$this->set('MTP_messenger', $messenger);
68
+	}
69
+
70
+
71
+	/**
72
+	 * @param bool $GRP_ID
73
+	 * @throws EE_Error
74
+	 */
75
+	public function set_group_template_id($GRP_ID = false)
76
+	{
77
+		if (! $GRP_ID) {
78
+			throw new EE_Error(
79
+				esc_html__(
80
+					'Missing required value for the message template group id',
81
+					'event_espresso'
82
+				)
83
+			);
84
+		}
85
+		$this->set('GRP_ID', $GRP_ID);
86
+	}
87
+
88
+
89
+	/**
90
+	 * get Group ID
91
+	 *
92
+	 * @access public
93
+	 * @return int
94
+	 * @throws EE_Error
95
+	 */
96
+	public function GRP_ID()
97
+	{
98
+		return $this->get('GRP_ID');
99
+	}
100
+
101
+
102
+	/**
103
+	 * get User ID
104
+	 *
105
+	 * @access public
106
+	 * @return int
107
+	 * @throws EE_Error
108
+	 */
109
+	public function user()
110
+	{
111
+		$user_id = $this->get('MTP_user_id');
112
+		return empty($user_id) ? get_current_user_id() : $user_id;
113
+	}
114
+
115
+
116
+	/**
117
+	 * Wrapper for the user function() (preserve backward compat)
118
+	 *
119
+	 * @since  4.5.0
120
+	 * @return int
121
+	 * @throws EE_Error
122
+	 */
123
+	public function wp_user()
124
+	{
125
+		return $this->user();
126
+	}
127
+
128
+
129
+	/**
130
+	 * This simply returns a count of all related events to this message template group
131
+	 *
132
+	 * @return int
133
+	 */
134
+	public function count_events()
135
+	{
136
+		return $this->count_related('Event');
137
+	}
138
+
139
+
140
+	/**
141
+	 * returns the name saved in the db for this template
142
+	 *
143
+	 * @return string
144
+	 * @throws EE_Error
145
+	 */
146
+	public function name()
147
+	{
148
+		return $this->get('MTP_name');
149
+	}
150
+
151
+
152
+	/**
153
+	 * Returns the description saved in the db for this template group
154
+	 *
155
+	 * @return string
156
+	 * @throws EE_Error
157
+	 */
158
+	public function description()
159
+	{
160
+		return $this->get('MTP_description');
161
+	}
162
+
163
+
164
+	/**
165
+	 * returns all related EE_Message_Template objects
166
+	 *
167
+	 * @param  array $query_params like EEM_Base::get_all()
168
+	 * @return EE_Message_Template[]
169
+	 * @throws EE_Error
170
+	 */
171
+	public function message_templates($query_params = array())
172
+	{
173
+		return $this->get_many_related('Message_Template', $query_params);
174
+	}
175
+
176
+
177
+	/**
178
+	 * get Message Messenger
179
+	 *
180
+	 * @access public
181
+	 * @return string
182
+	 * @throws EE_Error
183
+	 */
184
+	public function messenger()
185
+	{
186
+		return $this->get('MTP_messenger');
187
+	}
188
+
189
+
190
+	/**
191
+	 * get Message Messenger OBJECT
192
+	 * If an attempt to get the corresponding messenger object fails, then we set this message
193
+	 * template group to inactive, and save to db.  Then return null so client code can handle
194
+	 * appropriately.
195
+	 *
196
+	 * @return EE_messenger
197
+	 * @throws EE_Error
198
+	 */
199
+	public function messenger_obj()
200
+	{
201
+		$messenger = $this->messenger();
202
+		try {
203
+			$messenger = EEH_MSG_Template::messenger_obj($messenger);
204
+		} catch (EE_Error $e) {
205
+			// if an exception was thrown then let's deactivate this message template group because it means there is no
206
+			// class for this messenger in this group.
207
+			$this->set('MTP_is_active', false);
208
+			$this->save();
209
+			return null;
210
+		}
211
+		return $messenger;
212
+	}
213
+
214
+
215
+	/**
216
+	 * get Message Type
217
+	 *
218
+	 * @access public
219
+	 * @return string
220
+	 * @throws EE_Error
221
+	 */
222
+	public function message_type()
223
+	{
224
+		return $this->get('MTP_message_type');
225
+	}
226
+
227
+
228
+	/**
229
+	 * get Message type OBJECT
230
+	 * If an attempt to get the corresponding message type object fails, then we set this message
231
+	 * template group to inactive, and save to db.  Then return null so client code can handle
232
+	 * appropriately.
233
+	 *
234
+	 * @throws EE_Error
235
+	 * @return EE_message_type|false if exception thrown.
236
+	 */
237
+	public function message_type_obj()
238
+	{
239
+		$message_type = $this->message_type();
240
+		try {
241
+			$message_type = EEH_MSG_Template::message_type_obj($message_type);
242
+		} catch (EE_Error $e) {
243
+			// if an exception was thrown then let's deactivate this message template group because it means there is no
244
+			// class for the message type in this group.
245
+			$this->set('MTP_is_active', false);
246
+			$this->save();
247
+			return null;
248
+		}
249
+		return $message_type;
250
+	}
251
+
252
+
253
+	/**
254
+	 * @return array
255
+	 * @throws EE_Error
256
+	 */
257
+	public function contexts_config()
258
+	{
259
+		return $this->message_type_obj()->get_contexts();
260
+	}
261
+
262
+
263
+	/**
264
+	 * This returns the context_label for contexts as set in the message type object
265
+	 * Note this is an array with singular and plural keys
266
+	 *
267
+	 * @access public
268
+	 * @return array labels for "context"
269
+	 * @throws EE_Error
270
+	 */
271
+	public function context_label()
272
+	{
273
+		$obj = $this->message_type_obj();
274
+		return $obj->get_context_label();
275
+	}
276
+
277
+
278
+	/**
279
+	 * This returns an array of EE_Message_Template objects indexed by context and field.
280
+	 *
281
+	 * @return array ()
282
+	 * @throws EE_Error
283
+	 */
284
+	public function context_templates()
285
+	{
286
+		$mtps_arr = array();
287
+		$mtps = $this->get_many_related('Message_Template');
288
+		if (empty($mtps)) {
289
+			return array();
290
+		}
291
+		// note contexts could have CHECKBOX fields per context. So we return the objects indexed by context AND field.
292
+		foreach ($mtps as $mtp) {
293
+			$mtps_arr[ $mtp->get('MTP_context') ][ $mtp->get('MTP_template_field') ] = $mtp;
294
+		}
295
+		return $mtps_arr;
296
+	}
297
+
298
+
299
+	/**
300
+	 * this returns if the template group this template belongs to is global
301
+	 *
302
+	 * @return bool true if it is, false if it isn't
303
+	 * @throws EE_Error
304
+	 */
305
+	public function is_global()
306
+	{
307
+		return $this->get('MTP_is_global');
308
+	}
309
+
310
+
311
+	/**
312
+	 * this returns if the template group this template belongs to is active (i.e. turned "on" or not)
313
+	 *
314
+	 * @return bool true if it is, false if it isn't
315
+	 * @throws EE_Error
316
+	 */
317
+	public function is_active()
318
+	{
319
+		return $this->get('MTP_is_active');
320
+	}
321
+
322
+
323
+	/**
324
+	 * This will return an array of shortcodes => labels from the messenger and message_type objects associated with
325
+	 * this template.
326
+	 *
327
+	 * @since 4.3.0
328
+	 * @uses  EEH_MSG_Template::get_shortcodes()
329
+	 * @param string $context what context we're going to return shortcodes for
330
+	 * @param array  $fields  what fields we're returning valid shortcodes for.  If empty then we assume all fields are
331
+	 *                        to be returned.
332
+	 * @param bool   $merged  If TRUE then we don't return shortcodes indexed by field but instead an array of the
333
+	 *                        unique shortcodes for all the given (or all) fields.
334
+	 * @return mixed (array|bool) an array of shortcodes in the format array( '[shortcode] => 'label') OR FALSE if no
335
+	 *                        shortcodes found.
336
+	 * @throws EE_Error
337
+	 */
338
+	public function get_shortcodes($context, $fields = array(), $merged = false)
339
+	{
340
+		$messenger = $this->messenger();
341
+		$message_type = $this->message_type();
342
+		return EEH_MSG_Template::get_shortcodes($message_type, $messenger, $fields, $context, $merged);
343
+	}
344
+
345
+
346
+	/**
347
+	 * This just gets the template pack name assigned to this message template group.  If it's not set, then we just
348
+	 * use the default template pack.
349
+	 *
350
+	 * @since 4.5.0
351
+	 * @return string
352
+	 * @throws EE_Error
353
+	 */
354
+	public function get_template_pack_name()
355
+	{
356
+		return $this->get_extra_meta('MTP_template_pack', true, 'default');
357
+	}
358
+
359
+
360
+	/**
361
+	 * This returns the specific template pack object referenced by the template pack name attached to this message
362
+	 * template group.  If no template pack is assigned then the default template pack is retrieved.
363
+	 *
364
+	 * @since 4.5.0
365
+	 * @return EE_Messages_Template_Pack
366
+	 * @throws EE_Error
367
+	 * @throws InvalidArgumentException
368
+	 * @throws ReflectionException
369
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
370
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
371
+	 */
372
+	public function get_template_pack()
373
+	{
374
+		$pack_name = $this->get_template_pack_name();
375
+		EE_Registry::instance()->load_helper('MSG_Template');
376
+		return EEH_MSG_Template::get_template_pack($pack_name);
377
+	}
378
+
379
+
380
+	/**
381
+	 * This retrieves the template variation assigned to this message template group.  If it's not set, then we just
382
+	 * use the default template variation.
383
+	 *
384
+	 * @since 4.5.0
385
+	 * @return string
386
+	 * @throws EE_Error
387
+	 */
388
+	public function get_template_pack_variation()
389
+	{
390
+		return $this->get_extra_meta('MTP_variation', true, 'default');
391
+	}
392
+
393
+
394
+	/**
395
+	 * This just sets the template pack name attached to this message template group.
396
+	 *
397
+	 * @since 4.5.0
398
+	 * @param string $template_pack_name What message template pack is assigned.
399
+	 * @return int
400
+	 * @throws EE_Error
401
+	 */
402
+	public function set_template_pack_name($template_pack_name)
403
+	{
404
+		return $this->update_extra_meta('MTP_template_pack', $template_pack_name);
405
+	}
406
+
407
+
408
+	/**
409
+	 * This just sets the template pack variation attached to this message template group.
410
+	 *
411
+	 * @since 4.5.0
412
+	 * @param string $variation What variation is being set on the message template group.
413
+	 * @return int
414
+	 * @throws EE_Error
415
+	 */
416
+	public function set_template_pack_variation($variation)
417
+	{
418
+		return $this->update_extra_meta('MTP_variation', $variation);
419
+	}
420
+
421
+
422
+	/**
423
+	 * Deactivates the given context.
424
+	 *
425
+	 * @param $context
426
+	 * @return bool|int
427
+	 * @throws EE_Error
428
+	 * @throws InvalidIdentifierException
429
+	 */
430
+	public function deactivate_context($context)
431
+	{
432
+		$this->validate_context($context);
433
+		return $this->update_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, false);
434
+	}
435
+
436
+
437
+	/**
438
+	 * Activates the given context.
439
+	 *
440
+	 * @param $context
441
+	 * @return bool|int
442
+	 * @throws EE_Error
443
+	 * @throws InvalidIdentifierException
444
+	 */
445
+	public function activate_context($context)
446
+	{
447
+		$this->validate_context($context);
448
+		return $this->update_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, true);
449
+	}
450
+
451
+
452
+	/**
453
+	 * Returns whether the context is active or not.
454
+	 * Note, this will default to true if the extra meta record doesn't exist.
455
+	 * Also, this does NOT account for whether the "To" field is empty or not. Some messengers may allow the "To" field
456
+	 * to be empty (@see EE_Messenger::allow_empty_to_field()) so an empty "To" field is not always an indicator of
457
+	 * whether a context is "active" or not.
458
+	 *
459
+	 * @param $context
460
+	 * @return bool
461
+	 * @throws EE_Error
462
+	 * @throws InvalidIdentifierException
463
+	 */
464
+	public function is_context_active($context)
465
+	{
466
+		$this->validate_context($context);
467
+		return filter_var(
468
+			$this->get_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, true, true),
469
+			FILTER_VALIDATE_BOOLEAN
470
+		);
471
+	}
472
+
473
+
474
+	/**
475
+	 * Validates the incoming context to verify it matches a registered context for the related message type.
476
+	 *
477
+	 * @param string $context
478
+	 * @throws EE_Error
479
+	 * @throws InvalidIdentifierException
480
+	 */
481
+	public function validate_context($context)
482
+	{
483
+		$contexts = $this->contexts_config();
484
+		if (! isset($contexts[ $context ])) {
485
+			throw new InvalidIdentifierException(
486
+				'',
487
+				'',
488
+				sprintf(
489
+					esc_html__(
490
+						'An invalid string identifying a context was provided.  "%1$s" was received, and one of "%2$s" was expected.',
491
+						'event_espresso'
492
+					),
493
+					$context,
494
+					implode(',', array_keys($contexts))
495
+				)
496
+			);
497
+		}
498
+	}
499 499
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
      */
49 49
     public function set_message_type($message_type = false)
50 50
     {
51
-        if (! $message_type) {
51
+        if ( ! $message_type) {
52 52
             throw new EE_Error(esc_html__('Missing required value for the message_type parameter', 'event_espresso'));
53 53
         }
54 54
         $this->set('MTP_message_type', $message_type);
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
      */
62 62
     public function set_messenger($messenger = false)
63 63
     {
64
-        if (! $messenger) {
64
+        if ( ! $messenger) {
65 65
             throw new EE_Error(esc_html__('Missing required value for the messenger parameter', 'event_espresso'));
66 66
         }
67 67
         $this->set('MTP_messenger', $messenger);
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
      */
75 75
     public function set_group_template_id($GRP_ID = false)
76 76
     {
77
-        if (! $GRP_ID) {
77
+        if ( ! $GRP_ID) {
78 78
             throw new EE_Error(
79 79
                 esc_html__(
80 80
                     'Missing required value for the message template group id',
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
         }
291 291
         // note contexts could have CHECKBOX fields per context. So we return the objects indexed by context AND field.
292 292
         foreach ($mtps as $mtp) {
293
-            $mtps_arr[ $mtp->get('MTP_context') ][ $mtp->get('MTP_template_field') ] = $mtp;
293
+            $mtps_arr[$mtp->get('MTP_context')][$mtp->get('MTP_template_field')] = $mtp;
294 294
         }
295 295
         return $mtps_arr;
296 296
     }
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
     public function deactivate_context($context)
431 431
     {
432 432
         $this->validate_context($context);
433
-        return $this->update_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, false);
433
+        return $this->update_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX.$context, false);
434 434
     }
435 435
 
436 436
 
@@ -445,7 +445,7 @@  discard block
 block discarded – undo
445 445
     public function activate_context($context)
446 446
     {
447 447
         $this->validate_context($context);
448
-        return $this->update_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, true);
448
+        return $this->update_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX.$context, true);
449 449
     }
450 450
 
451 451
 
@@ -465,7 +465,7 @@  discard block
 block discarded – undo
465 465
     {
466 466
         $this->validate_context($context);
467 467
         return filter_var(
468
-            $this->get_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, true, true),
468
+            $this->get_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX.$context, true, true),
469 469
             FILTER_VALIDATE_BOOLEAN
470 470
         );
471 471
     }
@@ -481,7 +481,7 @@  discard block
 block discarded – undo
481 481
     public function validate_context($context)
482 482
     {
483 483
         $contexts = $this->contexts_config();
484
-        if (! isset($contexts[ $context ])) {
484
+        if ( ! isset($contexts[$context])) {
485 485
             throw new InvalidIdentifierException(
486 486
                 '',
487 487
                 '',
Please login to merge, or discard this patch.
core/libraries/messages/EE_Messages_Generator.lib.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
      * there's a single shared message template group among all the events.  Otherwise it returns null.
460 460
      *
461 461
      * @param array $event_ids
462
-     * @return EE_Message_Template_Group|null
462
+     * @return null|EE_Base_Class
463 463
      * @throws EE_Error
464 464
      * @throws InvalidArgumentException
465 465
      * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
     /**
496 496
      * Retrieves the global message template group for the current messenger and message type.
497 497
      *
498
-     * @return EE_Message_Template_Group|null
498
+     * @return null|EE_Base_Class
499 499
      * @throws EE_Error
500 500
      * @throws InvalidArgumentException
501 501
      * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
      * @param EE_Messages_Addressee     $recipient
642 642
      * @param array                     $templates formatted array of templates used for parsing data.
643 643
      * @param EE_Message_Template_Group $message_template_group
644
-     * @return bool|EE_Message
644
+     * @return EE_Message
645 645
      * @throws EE_Error
646 646
      */
647 647
     protected function _setup_message_object(
Please login to merge, or discard this patch.
Indentation   +969 added lines, -969 removed lines patch added patch discarded remove patch
@@ -12,973 +12,973 @@
 block discarded – undo
12 12
 {
13 13
 
14 14
 
15
-    /**
16
-     * @type EE_Messages_Data_Handler_Collection
17
-     */
18
-    protected $_data_handler_collection;
19
-
20
-    /**
21
-     * @type  EE_Message_Template_Group_Collection
22
-     */
23
-    protected $_template_collection;
24
-
25
-    /**
26
-     * This will hold the data handler for the current EE_Message being generated.
27
-     *
28
-     * @type EE_Messages_incoming_data
29
-     */
30
-    protected $_current_data_handler;
31
-
32
-    /**
33
-     * This holds the EE_Messages_Queue that contains the messages to generate.
34
-     *
35
-     * @type EE_Messages_Queue
36
-     */
37
-    protected $_generation_queue;
38
-
39
-    /**
40
-     * This holds the EE_Messages_Queue that will store the generated EE_Message objects.
41
-     *
42
-     * @type EE_Messages_Queue
43
-     */
44
-    protected $_ready_queue;
45
-
46
-    /**
47
-     * This is a container for any error messages that get created through the generation
48
-     * process.
49
-     *
50
-     * @type array
51
-     */
52
-    protected $_error_msg = array();
53
-
54
-    /**
55
-     * Flag used to set when the current EE_Message in the generation queue has been verified.
56
-     *
57
-     * @type bool
58
-     */
59
-    protected $_verified = false;
60
-
61
-    /**
62
-     * This will hold the current messenger object corresponding with the current EE_Message in the generation queue.
63
-     *
64
-     * @type EE_messenger
65
-     */
66
-    protected $_current_messenger;
67
-
68
-    /**
69
-     * This will hold the current message type object corresponding with the current EE_Message in the generation queue.
70
-     *
71
-     * @type EE_message_type
72
-     */
73
-    protected $_current_message_type;
74
-
75
-    /**
76
-     * @type EEH_Parse_Shortcodes
77
-     */
78
-    protected $_shortcode_parser;
79
-
80
-
81
-    /**
82
-     * @param EE_Messages_Queue                     $generation_queue
83
-     * @param \EE_Messages_Queue                    $ready_queue
84
-     * @param \EE_Messages_Data_Handler_Collection  $data_handler_collection
85
-     * @param \EE_Message_Template_Group_Collection $template_collection
86
-     * @param \EEH_Parse_Shortcodes                 $shortcode_parser
87
-     */
88
-    public function __construct(
89
-        EE_Messages_Queue $generation_queue,
90
-        EE_Messages_Queue $ready_queue,
91
-        EE_Messages_Data_Handler_Collection $data_handler_collection,
92
-        EE_Message_Template_Group_Collection $template_collection,
93
-        EEH_Parse_Shortcodes $shortcode_parser
94
-    ) {
95
-        $this->_generation_queue        = $generation_queue;
96
-        $this->_ready_queue             = $ready_queue;
97
-        $this->_data_handler_collection = $data_handler_collection;
98
-        $this->_template_collection     = $template_collection;
99
-        $this->_shortcode_parser        = $shortcode_parser;
100
-    }
101
-
102
-
103
-    /**
104
-     * @return EE_Messages_Queue
105
-     */
106
-    public function generation_queue()
107
-    {
108
-        return $this->_generation_queue;
109
-    }
110
-
111
-
112
-    /**
113
-     *  This iterates through the provided queue and generates the EE_Message objects.
114
-     *  When iterating through the queue, the queued item that served as the base for generating other EE_Message
115
-     *  objects gets removed and the new EE_Message objects get added to a NEW queue.  The NEW queue is then returned
116
-     *  for the caller to decide what to do with it.
117
-     *
118
-     * @param   bool $save Whether to save the EE_Message objects in the new queue or just return.
119
-     * @return EE_Messages_Queue The new queue for holding generated EE_Message objects.
120
-     * @throws EE_Error
121
-     * @throws ReflectionException
122
-     */
123
-    public function generate($save = true)
124
-    {
125
-        // iterate through the messages in the queue, generate, and add to new queue.
126
-        $this->_generation_queue->get_message_repository()->rewind();
127
-        while ($this->_generation_queue->get_message_repository()->valid()) {
128
-            // reset "current" properties
129
-            $this->_reset_current_properties();
130
-
131
-            /** @type EE_Message $msg */
132
-            $msg = $this->_generation_queue->get_message_repository()->current();
133
-
134
-            /**
135
-             * need to get the next object and capture it for setting manually after deletes.  The reason is that when
136
-             * an object is removed from the repo then valid for the next object will fail.
137
-             */
138
-            $this->_generation_queue->get_message_repository()->next();
139
-            $next_msg = $this->_generation_queue->get_message_repository()->current();
140
-            // restore pointer to current item
141
-            $this->_generation_queue->get_message_repository()->set_current($msg);
142
-
143
-            // skip and delete if the current $msg is NOT incomplete (queued for generation)
144
-            if ($msg->STS_ID() !== EEM_Message::status_incomplete) {
145
-                // we keep this item in the db just remove from the repo.
146
-                $this->_generation_queue->get_message_repository()->remove($msg);
147
-                // next item
148
-                $this->_generation_queue->get_message_repository()->set_current($next_msg);
149
-                continue;
150
-            }
151
-
152
-            if ($this->_verify()) {
153
-                // let's get generating!
154
-                $this->_generate();
155
-            }
156
-
157
-            // don't persist debug_only messages if the messages system is not in debug mode.
158
-            if ($msg->STS_ID() === EEM_Message::status_debug_only
159
-                && ! EEM_Message::debug()
160
-            ) {
161
-                do_action(
162
-                    'AHEE__EE_Messages_Generator__generate__before_debug_delete',
163
-                    $msg,
164
-                    $this->_error_msg,
165
-                    $this->_current_messenger,
166
-                    $this->_current_message_type,
167
-                    $this->_current_data_handler
168
-                );
169
-                $this->_generation_queue->get_message_repository()->delete();
170
-                $this->_generation_queue->get_message_repository()->set_current($next_msg);
171
-                continue;
172
-            }
173
-
174
-            // if there are error messages then let's set the status and the error message.
175
-            if ($this->_error_msg) {
176
-                // if the status is already debug only, then let's leave it at that.
177
-                if ($msg->STS_ID() !== EEM_Message::status_debug_only) {
178
-                    $msg->set_STS_ID(EEM_Message::status_failed);
179
-                }
180
-                do_action(
181
-                    'AHEE__EE_Messages_Generator__generate__processing_failed_message',
182
-                    $msg,
183
-                    $this->_error_msg,
184
-                    $this->_current_messenger,
185
-                    $this->_current_message_type,
186
-                    $this->_current_data_handler
187
-                );
188
-                $msg->set_error_message(
189
-                    esc_html__('Message failed to generate for the following reasons: ', 'event_espresso')
190
-                    . "\n"
191
-                    . implode("\n", $this->_error_msg)
192
-                );
193
-                $msg->set_modified(time());
194
-            } else {
195
-                do_action(
196
-                    'AHEE__EE_Messages_Generator__generate__before_successful_generated_message_delete',
197
-                    $msg,
198
-                    $this->_error_msg,
199
-                    $this->_current_messenger,
200
-                    $this->_current_message_type,
201
-                    $this->_current_data_handler
202
-                );
203
-                // remove from db
204
-                $this->_generation_queue->get_message_repository()->delete();
205
-            }
206
-            // next item
207
-            $this->_generation_queue->get_message_repository()->set_current($next_msg);
208
-        }
209
-
210
-        // generation queue is ALWAYS saved to record any errors in the generation process.
211
-        $this->_generation_queue->save();
212
-
213
-        /**
214
-         * save _ready_queue if flag set.
215
-         * Note: The EE_Message objects have values set via the EE_Base_Class::set_field_or_extra_meta() method.  This
216
-         * means if a field was added that is not a valid database column.  The EE_Message was already saved to the db
217
-         * so a EE_Extra_Meta entry could be created and attached to the EE_Message.  In those cases the save flag is
218
-         * irrelevant.
219
-         */
220
-        if ($save) {
221
-            $this->_ready_queue->save();
222
-        }
223
-
224
-        // final reset of properties
225
-        $this->_reset_current_properties();
226
-
227
-        return $this->_ready_queue;
228
-    }
229
-
230
-
231
-    /**
232
-     * This resets all the properties used for holding "current" values corresponding to the current EE_Message object
233
-     * in the generation queue.
234
-     */
235
-    protected function _reset_current_properties()
236
-    {
237
-        $this->_verified = false;
238
-        // make sure any _data value in the current message type is reset
239
-        if ($this->_current_message_type instanceof EE_message_type) {
240
-            $this->_current_message_type->reset_data();
241
-        }
242
-        $this->_current_messenger = $this->_current_message_type = $this->_current_data_handler = null;
243
-    }
244
-
245
-
246
-    /**
247
-     * This proceeds with the actual generation of a message.  By the time this is called, there should already be a
248
-     * $_current_data_handler set and all incoming information should be validated for the current EE_Message in the
249
-     * _generating_queue.
250
-     *
251
-     * @return bool Whether the message was successfully generated or not.
252
-     * @throws EE_Error
253
-     * @throws InvalidArgumentException
254
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
255
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
256
-     */
257
-    protected function _generate()
258
-    {
259
-        // double check verification has run and that everything is ready to work with (saves us having to validate
260
-        // everything again).
261
-        if (! $this->_verified) {
262
-            return false; // get out because we don't have a valid setup to work with.
263
-        }
264
-
265
-
266
-        try {
267
-            $addressees = $this->_current_message_type->get_addressees(
268
-                $this->_current_data_handler,
269
-                $this->_generation_queue->get_message_repository()->current()->context()
270
-            );
271
-        } catch (EE_Error $e) {
272
-            $this->_error_msg[] = $e->getMessage();
273
-            return false;
274
-        }
275
-
276
-
277
-        // if no addressees then get out because there is nothing to generation (possible bad data).
278
-        if (! $this->_valid_addressees($addressees)) {
279
-            do_action(
280
-                'AHEE__EE_Messages_Generator___generate__invalid_addressees',
281
-                $this->_generation_queue->get_message_repository()->current(),
282
-                $addressees,
283
-                $this->_current_messenger,
284
-                $this->_current_message_type,
285
-                $this->_current_data_handler
286
-            );
287
-            $this->_generation_queue->get_message_repository()->current()->set_STS_ID(
288
-                EEM_Message::status_debug_only
289
-            );
290
-            $this->_error_msg[] = esc_html__(
291
-                'This is not a critical error but an informational notice. Unable to generate messages EE_Messages_Addressee objects.  There were no attendees prepared by the data handler. Sometimes this is because messages only get generated for certain registration statuses. For example, the ticket notice message type only goes to approved registrations.',
292
-                'event_espresso'
293
-            );
294
-            return false;
295
-        }
296
-
297
-        $message_template_group = $this->_get_message_template_group();
298
-
299
-        // in the unlikely event there is no EE_Message_Template_Group available, get out!
300
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
301
-            $this->_error_msg[] = esc_html__(
302
-                'Unable to get the Message Templates for the Message being generated.  No message template group accessible.',
303
-                'event_espresso'
304
-            );
305
-            return false;
306
-        }
307
-
308
-        // get formatted templates for using to parse and setup EE_Message objects.
309
-        $templates = $this->_get_templates($message_template_group);
310
-
311
-
312
-        // setup new EE_Message objects (and add to _ready_queue)
313
-        return $this->_assemble_messages($addressees, $templates, $message_template_group);
314
-    }
315
-
316
-
317
-    /**
318
-     * Retrieves the message template group being used for generating messages.
319
-     * Note: this also utilizes the EE_Message_Template_Group_Collection to avoid having to hit the db multiple times.
320
-     *
321
-     * @return EE_Message_Template_Group|null
322
-     * @throws EE_Error
323
-     * @throws InvalidArgumentException
324
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
325
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
326
-     */
327
-    protected function _get_message_template_group()
328
-    {
329
-        // first see if there is a specific message template group requested (current message in the queue has a specific
330
-        // GRP_ID
331
-        $message_template_group = $this->_specific_message_template_group_from_queue();
332
-        if ($message_template_group instanceof EE_Message_Template_Group) {
333
-            return $message_template_group;
334
-        }
335
-
336
-        // get event_ids from the datahandler so we can check to see if there's already a message template group for them
337
-        // in the collection.
338
-        $event_ids              = $this->_get_event_ids_from_current_data_handler();
339
-        $message_template_group = $this->_template_collection->get_by_key(
340
-            $this->_template_collection->getKey(
341
-                $this->_current_messenger->name,
342
-                $this->_current_message_type->name,
343
-                $event_ids
344
-            )
345
-        );
346
-
347
-        // if we have a message template group then no need to hit the database, just return it.
348
-        if ($message_template_group instanceof EE_Message_Template_Group) {
349
-            return $message_template_group;
350
-        }
351
-
352
-        // okay made it here, so let's get the global group first for this messenger and message type to ensure
353
-        // there is no override set.
354
-        $global_message_template_group =
355
-            $this->_get_global_message_template_group_for_current_messenger_and_message_type();
356
-
357
-        if ($global_message_template_group instanceof EE_Message_Template_Group
358
-            && $global_message_template_group->get('MTP_is_override')
359
-        ) {
360
-            return $global_message_template_group;
361
-        }
362
-
363
-        // if we're still here, that means there was no message template group for the events in the collection and
364
-        // the global message template group for the messenger and message type is not set for override.  So next step is
365
-        // to see if there is a common shared custom message template group for this set of events.
366
-        $message_template_group = $this->_get_shared_message_template_for_events($event_ids);
367
-        if ($message_template_group instanceof EE_Message_Template_Group) {
368
-            return $message_template_group;
369
-        }
370
-
371
-        // STILL here?  Okay that means the fallback is to just use the global message template group for this event set.
372
-        // So we'll cache the global group for this event set (so this logic doesn't have to be repeated in this request)
373
-        // and return it.
374
-        if ($global_message_template_group instanceof EE_Message_Template_Group) {
375
-            $this->_template_collection->add(
376
-                $global_message_template_group,
377
-                $event_ids
378
-            );
379
-            return $global_message_template_group;
380
-        }
381
-
382
-        // if we land here that means there's NO active message template group for this set.
383
-        // TODO this will be a good target for some optimization down the road.  Whenever there is no active message
384
-        // template group for a given event set then cache that result so we don't repeat the logic.  However, for now,
385
-        // this should likely bit hit rarely enough that it's not a significant issue.
386
-        return null;
387
-    }
388
-
389
-
390
-    /**
391
-     * This checks the current message in the queue and determines if there is a specific Message Template Group
392
-     * requested for that message.
393
-     *
394
-     * @return EE_Message_Template_Group|null
395
-     * @throws EE_Error
396
-     * @throws InvalidArgumentException
397
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
398
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
399
-     */
400
-    protected function _specific_message_template_group_from_queue()
401
-    {
402
-        // is there a GRP_ID already on the EE_Message object?  If there is, then a specific template has been requested
403
-        // so let's use that.
404
-        $GRP_ID = $this->_generation_queue->get_message_repository()->current()->GRP_ID();
405
-
406
-        if ($GRP_ID) {
407
-            // attempt to retrieve from repo first
408
-            $message_template_group = $this->_template_collection->get_by_ID($GRP_ID);
409
-            if ($message_template_group instanceof EE_Message_Template_Group) {
410
-                return $message_template_group;  // got it!
411
-            }
412
-
413
-            // nope don't have it yet.  Get from DB then add to repo if its not here, then that means the current GRP_ID
414
-            // is not valid, so we'll continue on in the code assuming there's NO GRP_ID.
415
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
416
-            if ($message_template_group instanceof EE_Message_Template_Group) {
417
-                $this->_template_collection->add($message_template_group);
418
-                return $message_template_group;
419
-            }
420
-        }
421
-        return null;
422
-    }
423
-
424
-
425
-    /**
426
-     * Returns whether the event ids passed in all share the same message template group for the current message type
427
-     * and messenger.
428
-     *
429
-     * @param array $event_ids
430
-     * @return bool true means they DO share the same message template group, false means they don't.
431
-     * @throws EE_Error
432
-     * @throws InvalidArgumentException
433
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
434
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
435
-     */
436
-    protected function _queue_shares_same_message_template_group_for_events(array $event_ids)
437
-    {
438
-        foreach ($this->_current_data_handler->events as $event) {
439
-            $event_ids[ $event['ID'] ] = $event['ID'];
440
-        }
441
-        $count_of_message_template_groups = EEM_Message_Template_Group::instance()->count(
442
-            array(
443
-                array(
444
-                    'Event.EVT_ID'           => array('IN', $event_ids),
445
-                    'MTP_messenger'    => $this->_current_messenger->name,
446
-                    'MTP_message_type' => $this->_current_message_type->name,
447
-                ),
448
-            ),
449
-            'GRP_ID',
450
-            true
451
-        );
452
-        return $count_of_message_template_groups === 1;
453
-    }
454
-
455
-
456
-    /**
457
-     * This will get the shared message template group for events that are in the current data handler but ONLY if
458
-     * there's a single shared message template group among all the events.  Otherwise it returns null.
459
-     *
460
-     * @param array $event_ids
461
-     * @return EE_Message_Template_Group|null
462
-     * @throws EE_Error
463
-     * @throws InvalidArgumentException
464
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
465
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
466
-     */
467
-    protected function _get_shared_message_template_for_events(array $event_ids)
468
-    {
469
-        $message_template_group = null;
470
-        if ($this->_queue_shares_same_message_template_group_for_events($event_ids)) {
471
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one(
472
-                array(
473
-                    array(
474
-                        'Event.EVT_ID'           => array('IN', $event_ids),
475
-                        'MTP_messenger'    => $this->_current_messenger->name,
476
-                        'MTP_message_type' => $this->_current_message_type->name,
477
-                        'MTP_is_active'    => true,
478
-                    ),
479
-                    'group_by' => 'GRP_ID',
480
-                )
481
-            );
482
-            // store this in the collection if its valid
483
-            if ($message_template_group instanceof EE_Message_Template_Group) {
484
-                $this->_template_collection->add(
485
-                    $message_template_group,
486
-                    $event_ids
487
-                );
488
-            }
489
-        }
490
-        return $message_template_group;
491
-    }
492
-
493
-
494
-    /**
495
-     * Retrieves the global message template group for the current messenger and message type.
496
-     *
497
-     * @return EE_Message_Template_Group|null
498
-     * @throws EE_Error
499
-     * @throws InvalidArgumentException
500
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
501
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
502
-     */
503
-    protected function _get_global_message_template_group_for_current_messenger_and_message_type()
504
-    {
505
-        // first check the collection (we use an array with 0 in it to represent global groups).
506
-        $global_message_template_group = $this->_template_collection->get_by_key(
507
-            $this->_template_collection->getKey(
508
-                $this->_current_messenger->name,
509
-                $this->_current_message_type->name,
510
-                array(0)
511
-            )
512
-        );
513
-
514
-        // if we don't have a group lets hit the db.
515
-        if (! $global_message_template_group instanceof EE_Message_Template_Group) {
516
-            $global_message_template_group = EEM_Message_Template_Group::instance()->get_one(
517
-                array(
518
-                    array(
519
-                        'MTP_messenger'    => $this->_current_messenger->name,
520
-                        'MTP_message_type' => $this->_current_message_type->name,
521
-                        'MTP_is_active'    => true,
522
-                        'MTP_is_global'    => true,
523
-                    ),
524
-                )
525
-            );
526
-            // if we have a group, add it to the collection.
527
-            if ($global_message_template_group instanceof EE_Message_Template_Group) {
528
-                $this->_template_collection->add(
529
-                    $global_message_template_group,
530
-                    array(0)
531
-                );
532
-            }
533
-        }
534
-        return $global_message_template_group;
535
-    }
536
-
537
-
538
-    /**
539
-     * Returns an array of event ids for all the events within the current data handler.
540
-     *
541
-     * @return array
542
-     */
543
-    protected function _get_event_ids_from_current_data_handler()
544
-    {
545
-        $event_ids = array();
546
-        foreach ($this->_current_data_handler->events as $event) {
547
-            $event_ids[ $event['ID'] ] = $event['ID'];
548
-        }
549
-        return $event_ids;
550
-    }
551
-
552
-
553
-    /**
554
-     *  Retrieves formatted array of template information for each context specific to the given
555
-     *  EE_Message_Template_Group
556
-     *
557
-     * @param EE_Message_Template_Group $message_template_group
558
-     * @return array The returned array is in this structure:
559
-     *                          array(
560
-     *                          'field_name' => array(
561
-     *                          'context' => 'content'
562
-     *                          )
563
-     *                          )
564
-     * @throws EE_Error
565
-     */
566
-    protected function _get_templates(EE_Message_Template_Group $message_template_group)
567
-    {
568
-        $templates         = array();
569
-        $context_templates = $message_template_group->context_templates();
570
-        foreach ($context_templates as $context => $template_fields) {
571
-            foreach ($template_fields as $template_field => $template_obj) {
572
-                if (! $template_obj instanceof EE_Message_Template) {
573
-                    continue;
574
-                }
575
-                $templates[ $template_field ][ $context ] = $template_obj->get('MTP_content');
576
-            }
577
-        }
578
-        return $templates;
579
-    }
580
-
581
-
582
-    /**
583
-     * Assembles new fully generated EE_Message objects and adds to _ready_queue
584
-     *
585
-     * @param array                     $addressees  Array of EE_Messages_Addressee objects indexed by message type
586
-     *                                               context.
587
-     * @param array                     $templates   formatted array of templates used for parsing data.
588
-     * @param EE_Message_Template_Group $message_template_group
589
-     * @return bool true if message generation went a-ok.  false if some sort of exception occurred.  Note: The
590
-     *                                               method will attempt to generate ALL EE_Message objects and add to
591
-     *                                               the _ready_queue.  Successfully generated messages get added to the
592
-     *                                               queue with EEM_Message::status_idle, unsuccessfully generated
593
-     *                                               messages will get added to the queue as EEM_Message::status_failed.
594
-     *                                               Very rarely should "false" be returned from this method.
595
-     * @throws EE_Error
596
-     */
597
-    protected function _assemble_messages($addressees, $templates, EE_Message_Template_Group $message_template_group)
598
-    {
599
-
600
-        // if templates are empty then get out because we can't generate anything.
601
-        if (! $templates) {
602
-            $this->_error_msg[] = esc_html__(
603
-                'Unable to assemble messages because there are no templates retrieved for generating the messages with',
604
-                'event_espresso'
605
-            );
606
-            return false;
607
-        }
608
-
609
-        // We use this as the counter for generated messages because don't forget we may be executing this inside of a
610
-        // generation_queue.  So _ready_queue may have generated EE_Message objects already.
611
-        $generated_count = 0;
612
-        foreach ($addressees as $context => $recipients) {
613
-            foreach ($recipients as $recipient) {
614
-                $message = $this->_setup_message_object($context, $recipient, $templates, $message_template_group);
615
-                if ($message instanceof EE_Message) {
616
-                    $this->_ready_queue->add(
617
-                        $message,
618
-                        array(),
619
-                        $this->_generation_queue->get_message_repository()->is_preview(),
620
-                        $this->_generation_queue->get_message_repository()->is_test_send()
621
-                    );
622
-                    $generated_count++;
623
-                }
624
-
625
-                // if the current MSG being generated is for a test send then we'll only use ONE message in the
626
-                // generation.
627
-                if ($this->_generation_queue->get_message_repository()->is_test_send()) {
628
-                    break 2;
629
-                }
630
-            }
631
-        }
632
-
633
-        // if there are no generated messages then something else fatal went wrong.
634
-        return $generated_count > 0;
635
-    }
636
-
637
-
638
-    /**
639
-     * @param string                    $context   The context for the generated message.
640
-     * @param EE_Messages_Addressee     $recipient
641
-     * @param array                     $templates formatted array of templates used for parsing data.
642
-     * @param EE_Message_Template_Group $message_template_group
643
-     * @return bool|EE_Message
644
-     * @throws EE_Error
645
-     */
646
-    protected function _setup_message_object(
647
-        $context,
648
-        EE_Messages_Addressee $recipient,
649
-        $templates,
650
-        EE_Message_Template_Group $message_template_group
651
-    ) {
652
-        // stuff we already know
653
-        $transaction_id = $recipient->txn instanceof EE_Transaction ? $recipient->txn->ID() : 0;
654
-        $transaction_id = empty($transaction_id) && $this->_current_data_handler->txn instanceof EE_Transaction
655
-            ? $this->_current_data_handler->txn->ID()
656
-            : $transaction_id;
657
-        $message_fields = array(
658
-            'GRP_ID'           => $message_template_group->ID(),
659
-            'TXN_ID'           => $transaction_id,
660
-            'MSG_messenger'    => $this->_current_messenger->name,
661
-            'MSG_message_type' => $this->_current_message_type->name,
662
-            'MSG_context'      => $context,
663
-        );
664
-
665
-        // recipient id and type should be on the EE_Messages_Addressee object but if this is empty, let's try to grab
666
-        // the info from the att_obj found in the EE_Messages_Addressee object.
667
-        if (empty($recipient->recipient_id) || empty($recipient->recipient_type)) {
668
-            $message_fields['MSG_recipient_ID']   = $recipient->att_obj instanceof EE_Attendee
669
-                ? $recipient->att_obj->ID()
670
-                : 0;
671
-            $message_fields['MSG_recipient_type'] = 'Attendee';
672
-        } else {
673
-            $message_fields['MSG_recipient_ID']   = $recipient->recipient_id;
674
-            $message_fields['MSG_recipient_type'] = $recipient->recipient_type;
675
-        }
676
-        $message = EE_Message_Factory::create($message_fields);
677
-
678
-        // grab valid shortcodes for shortcode parser
679
-        $mt_shortcodes = $this->_current_message_type->get_valid_shortcodes();
680
-        $m_shortcodes  = $this->_current_messenger->get_valid_shortcodes();
681
-
682
-        // if the 'to' field is empty or the context is inactive we skip EXCEPT if we're previewing
683
-        if ((
684
-                (
685
-                    empty($templates['to'][ $context ])
686
-                    && ! $this->_current_messenger->allow_empty_to_field()
687
-                )
688
-                || ! $message_template_group->is_context_active($context)
689
-            )
690
-            && ! $this->_generation_queue->get_message_repository()->is_preview()
691
-        ) {
692
-            // we silently exit here and do NOT record a fail because the message is "turned off" by having no "to"
693
-            // field.
694
-            return false;
695
-        }
696
-        $error_msg = array();
697
-        foreach ($templates as $field => $field_context) {
698
-            $error_msg = array();
699
-            // let's setup the valid shortcodes for the incoming context.
700
-            $valid_shortcodes = $mt_shortcodes[ $context ];
701
-            // merge in valid shortcodes for the field.
702
-            $shortcodes = isset($m_shortcodes[ $field ]) ? $m_shortcodes[ $field ] : $valid_shortcodes;
703
-            if (isset($templates[ $field ][ $context ])) {
704
-                // prefix field.
705
-                $column_name = 'MSG_' . $field;
706
-                try {
707
-                    $content = $this->_shortcode_parser->parse_message_template(
708
-                        $templates[ $field ][ $context ],
709
-                        $recipient,
710
-                        $shortcodes,
711
-                        $this->_current_message_type,
712
-                        $this->_current_messenger,
713
-                        $message
714
-                    );
715
-                    // the model field removes slashes when setting (usually necessary when the input is from the
716
-                    // request) but this value is from another model and has no slashes. So add them so it matchces
717
-                    // what the field expected (otherwise slashes will have been stripped from this an extra time)
718
-                    $message->set_field_or_extra_meta($column_name, addslashes($content));
719
-                } catch (EE_Error $e) {
720
-                    $error_msg[] = sprintf(
721
-                        esc_html__(
722
-                            'There was a problem generating the content for the field %s: %s',
723
-                            'event_espresso'
724
-                        ),
725
-                        $field,
726
-                        $e->getMessage()
727
-                    );
728
-                    $message->set_STS_ID(EEM_Message::status_failed);
729
-                }
730
-            }
731
-        }
732
-
733
-        if ($message->STS_ID() === EEM_Message::status_failed) {
734
-            $error_msg = esc_html__('There were problems generating this message:', 'event_espresso')
735
-                         . "\n"
736
-                         . implode("\n", $error_msg);
737
-            $message->set_error_message($error_msg);
738
-        } else {
739
-            $message->set_STS_ID(EEM_Message::status_idle);
740
-        }
741
-        return $message;
742
-    }
743
-
744
-
745
-    /**
746
-     * This verifies that the incoming array has a EE_messenger object and a EE_message_type object and sets appropriate
747
-     * error message if either is missing.
748
-     *
749
-     * @return bool true means there were no errors, false means there were errors.
750
-     * @throws EE_Error
751
-     * @throws ReflectionException
752
-     */
753
-    protected function _verify()
754
-    {
755
-        // reset error message to an empty array.
756
-        $this->_error_msg = array();
757
-        $valid            = true;
758
-        $valid            = $valid ? $this->_validate_messenger_and_message_type() : $valid;
759
-        $valid            = $valid ? $this->_validate_and_setup_data() : $valid;
760
-
761
-        // set the verified flag so we know everything has been validated.
762
-        $this->_verified = $valid;
763
-
764
-        return $valid;
765
-    }
766
-
767
-
768
-    /**
769
-     * This accepts an array and validates that it is an array indexed by context with each value being an array of
770
-     * EE_Messages_Addressee objects.
771
-     *
772
-     * @param array $addressees Keys correspond to contexts for the message type and values are EE_Messages_Addressee[]
773
-     * @return bool
774
-     */
775
-    protected function _valid_addressees($addressees)
776
-    {
777
-        if (! $addressees || ! is_array($addressees)) {
778
-            return false;
779
-        }
780
-
781
-        foreach ($addressees as $addressee_array) {
782
-            foreach ($addressee_array as $addressee) {
783
-                if (! $addressee instanceof EE_Messages_Addressee) {
784
-                    return false;
785
-                }
786
-            }
787
-        }
788
-        return true;
789
-    }
790
-
791
-
792
-    /**
793
-     * This validates the messenger, message type, and presences of generation data for the current EE_Message in the
794
-     * queue. This process sets error messages if something is wrong.
795
-     *
796
-     * @return bool   true is if there are no errors.  false is if there is.
797
-     */
798
-    protected function _validate_messenger_and_message_type()
799
-    {
800
-
801
-        // first are there any existing error messages?  If so then return.
802
-        if ($this->_error_msg) {
803
-            return false;
804
-        }
805
-        /** @type EE_Message $message */
806
-        $message = $this->_generation_queue->get_message_repository()->current();
807
-        try {
808
-            $this->_current_messenger = $message->valid_messenger(true)
809
-                ? $message->messenger_object()
810
-                : null;
811
-        } catch (Exception $e) {
812
-            $this->_error_msg[] = $e->getMessage();
813
-        }
814
-        try {
815
-            $this->_current_message_type = $message->valid_message_type(true)
816
-                ? $message->message_type_object()
817
-                : null;
818
-        } catch (Exception $e) {
819
-            $this->_error_msg[] = $e->getMessage();
820
-        }
821
-
822
-        /**
823
-         * Check if there is any generation data, but only if this is not for a preview.
824
-         */
825
-        if (! $this->_generation_queue->get_message_repository()->get_generation_data()
826
-            && (
827
-                ! $this->_generation_queue->get_message_repository()->is_preview()
828
-                && $this->_generation_queue->get_message_repository()->get_data_handler()
829
-                   !== 'EE_Messages_Preview_incoming_data'
830
-            )
831
-        ) {
832
-            $this->_error_msg[] = esc_html__(
833
-                'There is no generation data for this message. Unable to generate.',
834
-                'event_espresso'
835
-            );
836
-        }
837
-
838
-        return empty($this->_error_msg);
839
-    }
840
-
841
-
842
-    /**
843
-     * This method retrieves the expected data handler for the message type and validates the generation data for that
844
-     * data handler.
845
-     *
846
-     * @return bool true means there are no errors.  false means there were errors (and handler did not get setup).
847
-     * @throws EE_Error
848
-     * @throws ReflectionException
849
-     */
850
-    protected function _validate_and_setup_data()
851
-    {
852
-
853
-        // First, are there any existing error messages?  If so, return because if there were errors elsewhere this can't
854
-        // be used anyways.
855
-        if ($this->_error_msg) {
856
-            return false;
857
-        }
858
-
859
-        $generation_data = $this->_generation_queue->get_message_repository()->get_generation_data();
860
-
861
-        /** @type EE_Messages_incoming_data $data_handler_class_name - well not really... just the class name actually*/
862
-        $data_handler_class_name = $this->_generation_queue->get_message_repository()->get_data_handler()
863
-            ? $this->_generation_queue->get_message_repository()->get_data_handler()
864
-            : 'EE_Messages_' . $this->_current_message_type->get_data_handler($generation_data) . '_incoming_data';
865
-
866
-        // If this EE_Message is for a preview, then let's switch out to the preview data handler.
867
-        if ($this->_generation_queue->get_message_repository()->is_preview()) {
868
-            $data_handler_class_name = 'EE_Messages_Preview_incoming_data';
869
-        }
870
-
871
-        // First get the class name for the data handler (and also verifies it exists.
872
-        if (! class_exists($data_handler_class_name)) {
873
-            $this->_error_msg[] = sprintf(
874
-                esc_html__(
875
-                    'The included data handler class name does not match any valid, accessible, "%1$s" classes.  Looking for %2$s.',
876
-                    'event_espresso'
877
-                ),
878
-                'EE_Messages_incoming_data',
879
-                $data_handler_class_name
880
-            );
881
-            return false;
882
-        }
883
-
884
-        // convert generation_data for data_handler_instantiation.
885
-        $generation_data = $data_handler_class_name::convert_data_from_persistent_storage($generation_data);
886
-
887
-        // note, this may set error messages as well.
888
-        $this->_set_data_handler($generation_data, $data_handler_class_name);
889
-
890
-        return empty($this->_error_msg);
891
-    }
892
-
893
-
894
-    /**
895
-     * Sets the $_current_data_handler property that is used for generating the current EE_Message in the queue, and
896
-     * adds it to the _data repository.
897
-     *
898
-     * @param mixed  $generating_data           This is data expected by the instantiated data handler.
899
-     * @param string $data_handler_class_name   This is the reference string indicating what data handler is being
900
-     *                                          instantiated.
901
-     * @return void .
902
-     * @throws EE_Error
903
-     * @throws ReflectionException
904
-     */
905
-    protected function _set_data_handler($generating_data, $data_handler_class_name)
906
-    {
907
-        // valid classname for the data handler.  Now let's setup the key for the data handler repository to see if there
908
-        // is already a ready data handler in the repository.
909
-        $this->_current_data_handler = $this->_data_handler_collection->get_by_key(
910
-            $this->_data_handler_collection->get_key(
911
-                $data_handler_class_name,
912
-                $generating_data
913
-            )
914
-        );
915
-        if (! $this->_current_data_handler instanceof EE_Messages_incoming_data) {
916
-            // no saved data_handler in the repo so let's set one up and add it to the repo.
917
-            try {
918
-                $this->_current_data_handler = new $data_handler_class_name($generating_data);
919
-                $this->_data_handler_collection->add($this->_current_data_handler, $generating_data);
920
-            } catch (EE_Error $e) {
921
-                $this->_error_msg[] = $e->get_error();
922
-            }
923
-        }
924
-    }
925
-
926
-
927
-    /**
928
-     * The queued EE_Message for generation does not save the data used for generation as objects
929
-     * because serialization of those objects could be problematic if the data is saved to the db.
930
-     * So this method calls the static method on the associated data_handler for the given message_type
931
-     * and that preps the data for later instantiation when generating.
932
-     *
933
-     * @param EE_Message_To_Generate $message_to_generate
934
-     * @param bool                   $preview Indicate whether this is being used for a preview or not.
935
-     * @return mixed Prepped data for persisting to the queue.  false is returned if unable to prep data.
936
-     */
937
-    protected function _prepare_data_for_queue(EE_Message_To_Generate $message_to_generate, $preview)
938
-    {
939
-        /** @type EE_Messages_incoming_data $data_handler - well not really... just the class name actually */
940
-        $data_handler = $message_to_generate->get_data_handler_class_name($preview);
941
-        if (! $message_to_generate->valid()) {
942
-            return false; // unable to get the data because the info in the EE_Message_To_Generate class is invalid.
943
-        }
944
-        return $data_handler::convert_data_for_persistent_storage($message_to_generate->data());
945
-    }
946
-
947
-
948
-    /**
949
-     * This sets up a EEM_Message::status_incomplete EE_Message object and adds it to the generation queue.
950
-     *
951
-     * @param EE_Message_To_Generate $message_to_generate
952
-     * @param bool                   $test_send Whether this is just a test send or not.  Typically used for previews.
953
-     * @throws InvalidArgumentException
954
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
955
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
956
-     */
957
-    public function create_and_add_message_to_queue(EE_Message_To_Generate $message_to_generate, $test_send = false)
958
-    {
959
-        // prep data
960
-        $data = $this->_prepare_data_for_queue($message_to_generate, $message_to_generate->preview());
961
-
962
-        $message = $message_to_generate->get_EE_Message();
963
-
964
-        // is there a GRP_ID in the request?
965
-        if ($GRP_ID = EE_Registry::instance()->REQ->get('GRP_ID')) {
966
-            $message->set_GRP_ID($GRP_ID);
967
-        }
968
-
969
-        if ($data === false) {
970
-            $message->set_STS_ID(EEM_Message::status_failed);
971
-            $message->set_error_message(
972
-                esc_html__(
973
-                    'Unable to prepare data for persistence to the database.',
974
-                    'event_espresso'
975
-                )
976
-            );
977
-        } else {
978
-            // make sure that the data handler is cached on the message as well
979
-            $data['data_handler_class_name'] = $message_to_generate->get_data_handler_class_name();
980
-        }
981
-
982
-        $this->_generation_queue->add($message, $data, $message_to_generate->preview(), $test_send);
983
-    }
15
+	/**
16
+	 * @type EE_Messages_Data_Handler_Collection
17
+	 */
18
+	protected $_data_handler_collection;
19
+
20
+	/**
21
+	 * @type  EE_Message_Template_Group_Collection
22
+	 */
23
+	protected $_template_collection;
24
+
25
+	/**
26
+	 * This will hold the data handler for the current EE_Message being generated.
27
+	 *
28
+	 * @type EE_Messages_incoming_data
29
+	 */
30
+	protected $_current_data_handler;
31
+
32
+	/**
33
+	 * This holds the EE_Messages_Queue that contains the messages to generate.
34
+	 *
35
+	 * @type EE_Messages_Queue
36
+	 */
37
+	protected $_generation_queue;
38
+
39
+	/**
40
+	 * This holds the EE_Messages_Queue that will store the generated EE_Message objects.
41
+	 *
42
+	 * @type EE_Messages_Queue
43
+	 */
44
+	protected $_ready_queue;
45
+
46
+	/**
47
+	 * This is a container for any error messages that get created through the generation
48
+	 * process.
49
+	 *
50
+	 * @type array
51
+	 */
52
+	protected $_error_msg = array();
53
+
54
+	/**
55
+	 * Flag used to set when the current EE_Message in the generation queue has been verified.
56
+	 *
57
+	 * @type bool
58
+	 */
59
+	protected $_verified = false;
60
+
61
+	/**
62
+	 * This will hold the current messenger object corresponding with the current EE_Message in the generation queue.
63
+	 *
64
+	 * @type EE_messenger
65
+	 */
66
+	protected $_current_messenger;
67
+
68
+	/**
69
+	 * This will hold the current message type object corresponding with the current EE_Message in the generation queue.
70
+	 *
71
+	 * @type EE_message_type
72
+	 */
73
+	protected $_current_message_type;
74
+
75
+	/**
76
+	 * @type EEH_Parse_Shortcodes
77
+	 */
78
+	protected $_shortcode_parser;
79
+
80
+
81
+	/**
82
+	 * @param EE_Messages_Queue                     $generation_queue
83
+	 * @param \EE_Messages_Queue                    $ready_queue
84
+	 * @param \EE_Messages_Data_Handler_Collection  $data_handler_collection
85
+	 * @param \EE_Message_Template_Group_Collection $template_collection
86
+	 * @param \EEH_Parse_Shortcodes                 $shortcode_parser
87
+	 */
88
+	public function __construct(
89
+		EE_Messages_Queue $generation_queue,
90
+		EE_Messages_Queue $ready_queue,
91
+		EE_Messages_Data_Handler_Collection $data_handler_collection,
92
+		EE_Message_Template_Group_Collection $template_collection,
93
+		EEH_Parse_Shortcodes $shortcode_parser
94
+	) {
95
+		$this->_generation_queue        = $generation_queue;
96
+		$this->_ready_queue             = $ready_queue;
97
+		$this->_data_handler_collection = $data_handler_collection;
98
+		$this->_template_collection     = $template_collection;
99
+		$this->_shortcode_parser        = $shortcode_parser;
100
+	}
101
+
102
+
103
+	/**
104
+	 * @return EE_Messages_Queue
105
+	 */
106
+	public function generation_queue()
107
+	{
108
+		return $this->_generation_queue;
109
+	}
110
+
111
+
112
+	/**
113
+	 *  This iterates through the provided queue and generates the EE_Message objects.
114
+	 *  When iterating through the queue, the queued item that served as the base for generating other EE_Message
115
+	 *  objects gets removed and the new EE_Message objects get added to a NEW queue.  The NEW queue is then returned
116
+	 *  for the caller to decide what to do with it.
117
+	 *
118
+	 * @param   bool $save Whether to save the EE_Message objects in the new queue or just return.
119
+	 * @return EE_Messages_Queue The new queue for holding generated EE_Message objects.
120
+	 * @throws EE_Error
121
+	 * @throws ReflectionException
122
+	 */
123
+	public function generate($save = true)
124
+	{
125
+		// iterate through the messages in the queue, generate, and add to new queue.
126
+		$this->_generation_queue->get_message_repository()->rewind();
127
+		while ($this->_generation_queue->get_message_repository()->valid()) {
128
+			// reset "current" properties
129
+			$this->_reset_current_properties();
130
+
131
+			/** @type EE_Message $msg */
132
+			$msg = $this->_generation_queue->get_message_repository()->current();
133
+
134
+			/**
135
+			 * need to get the next object and capture it for setting manually after deletes.  The reason is that when
136
+			 * an object is removed from the repo then valid for the next object will fail.
137
+			 */
138
+			$this->_generation_queue->get_message_repository()->next();
139
+			$next_msg = $this->_generation_queue->get_message_repository()->current();
140
+			// restore pointer to current item
141
+			$this->_generation_queue->get_message_repository()->set_current($msg);
142
+
143
+			// skip and delete if the current $msg is NOT incomplete (queued for generation)
144
+			if ($msg->STS_ID() !== EEM_Message::status_incomplete) {
145
+				// we keep this item in the db just remove from the repo.
146
+				$this->_generation_queue->get_message_repository()->remove($msg);
147
+				// next item
148
+				$this->_generation_queue->get_message_repository()->set_current($next_msg);
149
+				continue;
150
+			}
151
+
152
+			if ($this->_verify()) {
153
+				// let's get generating!
154
+				$this->_generate();
155
+			}
156
+
157
+			// don't persist debug_only messages if the messages system is not in debug mode.
158
+			if ($msg->STS_ID() === EEM_Message::status_debug_only
159
+				&& ! EEM_Message::debug()
160
+			) {
161
+				do_action(
162
+					'AHEE__EE_Messages_Generator__generate__before_debug_delete',
163
+					$msg,
164
+					$this->_error_msg,
165
+					$this->_current_messenger,
166
+					$this->_current_message_type,
167
+					$this->_current_data_handler
168
+				);
169
+				$this->_generation_queue->get_message_repository()->delete();
170
+				$this->_generation_queue->get_message_repository()->set_current($next_msg);
171
+				continue;
172
+			}
173
+
174
+			// if there are error messages then let's set the status and the error message.
175
+			if ($this->_error_msg) {
176
+				// if the status is already debug only, then let's leave it at that.
177
+				if ($msg->STS_ID() !== EEM_Message::status_debug_only) {
178
+					$msg->set_STS_ID(EEM_Message::status_failed);
179
+				}
180
+				do_action(
181
+					'AHEE__EE_Messages_Generator__generate__processing_failed_message',
182
+					$msg,
183
+					$this->_error_msg,
184
+					$this->_current_messenger,
185
+					$this->_current_message_type,
186
+					$this->_current_data_handler
187
+				);
188
+				$msg->set_error_message(
189
+					esc_html__('Message failed to generate for the following reasons: ', 'event_espresso')
190
+					. "\n"
191
+					. implode("\n", $this->_error_msg)
192
+				);
193
+				$msg->set_modified(time());
194
+			} else {
195
+				do_action(
196
+					'AHEE__EE_Messages_Generator__generate__before_successful_generated_message_delete',
197
+					$msg,
198
+					$this->_error_msg,
199
+					$this->_current_messenger,
200
+					$this->_current_message_type,
201
+					$this->_current_data_handler
202
+				);
203
+				// remove from db
204
+				$this->_generation_queue->get_message_repository()->delete();
205
+			}
206
+			// next item
207
+			$this->_generation_queue->get_message_repository()->set_current($next_msg);
208
+		}
209
+
210
+		// generation queue is ALWAYS saved to record any errors in the generation process.
211
+		$this->_generation_queue->save();
212
+
213
+		/**
214
+		 * save _ready_queue if flag set.
215
+		 * Note: The EE_Message objects have values set via the EE_Base_Class::set_field_or_extra_meta() method.  This
216
+		 * means if a field was added that is not a valid database column.  The EE_Message was already saved to the db
217
+		 * so a EE_Extra_Meta entry could be created and attached to the EE_Message.  In those cases the save flag is
218
+		 * irrelevant.
219
+		 */
220
+		if ($save) {
221
+			$this->_ready_queue->save();
222
+		}
223
+
224
+		// final reset of properties
225
+		$this->_reset_current_properties();
226
+
227
+		return $this->_ready_queue;
228
+	}
229
+
230
+
231
+	/**
232
+	 * This resets all the properties used for holding "current" values corresponding to the current EE_Message object
233
+	 * in the generation queue.
234
+	 */
235
+	protected function _reset_current_properties()
236
+	{
237
+		$this->_verified = false;
238
+		// make sure any _data value in the current message type is reset
239
+		if ($this->_current_message_type instanceof EE_message_type) {
240
+			$this->_current_message_type->reset_data();
241
+		}
242
+		$this->_current_messenger = $this->_current_message_type = $this->_current_data_handler = null;
243
+	}
244
+
245
+
246
+	/**
247
+	 * This proceeds with the actual generation of a message.  By the time this is called, there should already be a
248
+	 * $_current_data_handler set and all incoming information should be validated for the current EE_Message in the
249
+	 * _generating_queue.
250
+	 *
251
+	 * @return bool Whether the message was successfully generated or not.
252
+	 * @throws EE_Error
253
+	 * @throws InvalidArgumentException
254
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
255
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
256
+	 */
257
+	protected function _generate()
258
+	{
259
+		// double check verification has run and that everything is ready to work with (saves us having to validate
260
+		// everything again).
261
+		if (! $this->_verified) {
262
+			return false; // get out because we don't have a valid setup to work with.
263
+		}
264
+
265
+
266
+		try {
267
+			$addressees = $this->_current_message_type->get_addressees(
268
+				$this->_current_data_handler,
269
+				$this->_generation_queue->get_message_repository()->current()->context()
270
+			);
271
+		} catch (EE_Error $e) {
272
+			$this->_error_msg[] = $e->getMessage();
273
+			return false;
274
+		}
275
+
276
+
277
+		// if no addressees then get out because there is nothing to generation (possible bad data).
278
+		if (! $this->_valid_addressees($addressees)) {
279
+			do_action(
280
+				'AHEE__EE_Messages_Generator___generate__invalid_addressees',
281
+				$this->_generation_queue->get_message_repository()->current(),
282
+				$addressees,
283
+				$this->_current_messenger,
284
+				$this->_current_message_type,
285
+				$this->_current_data_handler
286
+			);
287
+			$this->_generation_queue->get_message_repository()->current()->set_STS_ID(
288
+				EEM_Message::status_debug_only
289
+			);
290
+			$this->_error_msg[] = esc_html__(
291
+				'This is not a critical error but an informational notice. Unable to generate messages EE_Messages_Addressee objects.  There were no attendees prepared by the data handler. Sometimes this is because messages only get generated for certain registration statuses. For example, the ticket notice message type only goes to approved registrations.',
292
+				'event_espresso'
293
+			);
294
+			return false;
295
+		}
296
+
297
+		$message_template_group = $this->_get_message_template_group();
298
+
299
+		// in the unlikely event there is no EE_Message_Template_Group available, get out!
300
+		if (! $message_template_group instanceof EE_Message_Template_Group) {
301
+			$this->_error_msg[] = esc_html__(
302
+				'Unable to get the Message Templates for the Message being generated.  No message template group accessible.',
303
+				'event_espresso'
304
+			);
305
+			return false;
306
+		}
307
+
308
+		// get formatted templates for using to parse and setup EE_Message objects.
309
+		$templates = $this->_get_templates($message_template_group);
310
+
311
+
312
+		// setup new EE_Message objects (and add to _ready_queue)
313
+		return $this->_assemble_messages($addressees, $templates, $message_template_group);
314
+	}
315
+
316
+
317
+	/**
318
+	 * Retrieves the message template group being used for generating messages.
319
+	 * Note: this also utilizes the EE_Message_Template_Group_Collection to avoid having to hit the db multiple times.
320
+	 *
321
+	 * @return EE_Message_Template_Group|null
322
+	 * @throws EE_Error
323
+	 * @throws InvalidArgumentException
324
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
325
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
326
+	 */
327
+	protected function _get_message_template_group()
328
+	{
329
+		// first see if there is a specific message template group requested (current message in the queue has a specific
330
+		// GRP_ID
331
+		$message_template_group = $this->_specific_message_template_group_from_queue();
332
+		if ($message_template_group instanceof EE_Message_Template_Group) {
333
+			return $message_template_group;
334
+		}
335
+
336
+		// get event_ids from the datahandler so we can check to see if there's already a message template group for them
337
+		// in the collection.
338
+		$event_ids              = $this->_get_event_ids_from_current_data_handler();
339
+		$message_template_group = $this->_template_collection->get_by_key(
340
+			$this->_template_collection->getKey(
341
+				$this->_current_messenger->name,
342
+				$this->_current_message_type->name,
343
+				$event_ids
344
+			)
345
+		);
346
+
347
+		// if we have a message template group then no need to hit the database, just return it.
348
+		if ($message_template_group instanceof EE_Message_Template_Group) {
349
+			return $message_template_group;
350
+		}
351
+
352
+		// okay made it here, so let's get the global group first for this messenger and message type to ensure
353
+		// there is no override set.
354
+		$global_message_template_group =
355
+			$this->_get_global_message_template_group_for_current_messenger_and_message_type();
356
+
357
+		if ($global_message_template_group instanceof EE_Message_Template_Group
358
+			&& $global_message_template_group->get('MTP_is_override')
359
+		) {
360
+			return $global_message_template_group;
361
+		}
362
+
363
+		// if we're still here, that means there was no message template group for the events in the collection and
364
+		// the global message template group for the messenger and message type is not set for override.  So next step is
365
+		// to see if there is a common shared custom message template group for this set of events.
366
+		$message_template_group = $this->_get_shared_message_template_for_events($event_ids);
367
+		if ($message_template_group instanceof EE_Message_Template_Group) {
368
+			return $message_template_group;
369
+		}
370
+
371
+		// STILL here?  Okay that means the fallback is to just use the global message template group for this event set.
372
+		// So we'll cache the global group for this event set (so this logic doesn't have to be repeated in this request)
373
+		// and return it.
374
+		if ($global_message_template_group instanceof EE_Message_Template_Group) {
375
+			$this->_template_collection->add(
376
+				$global_message_template_group,
377
+				$event_ids
378
+			);
379
+			return $global_message_template_group;
380
+		}
381
+
382
+		// if we land here that means there's NO active message template group for this set.
383
+		// TODO this will be a good target for some optimization down the road.  Whenever there is no active message
384
+		// template group for a given event set then cache that result so we don't repeat the logic.  However, for now,
385
+		// this should likely bit hit rarely enough that it's not a significant issue.
386
+		return null;
387
+	}
388
+
389
+
390
+	/**
391
+	 * This checks the current message in the queue and determines if there is a specific Message Template Group
392
+	 * requested for that message.
393
+	 *
394
+	 * @return EE_Message_Template_Group|null
395
+	 * @throws EE_Error
396
+	 * @throws InvalidArgumentException
397
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
398
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
399
+	 */
400
+	protected function _specific_message_template_group_from_queue()
401
+	{
402
+		// is there a GRP_ID already on the EE_Message object?  If there is, then a specific template has been requested
403
+		// so let's use that.
404
+		$GRP_ID = $this->_generation_queue->get_message_repository()->current()->GRP_ID();
405
+
406
+		if ($GRP_ID) {
407
+			// attempt to retrieve from repo first
408
+			$message_template_group = $this->_template_collection->get_by_ID($GRP_ID);
409
+			if ($message_template_group instanceof EE_Message_Template_Group) {
410
+				return $message_template_group;  // got it!
411
+			}
412
+
413
+			// nope don't have it yet.  Get from DB then add to repo if its not here, then that means the current GRP_ID
414
+			// is not valid, so we'll continue on in the code assuming there's NO GRP_ID.
415
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
416
+			if ($message_template_group instanceof EE_Message_Template_Group) {
417
+				$this->_template_collection->add($message_template_group);
418
+				return $message_template_group;
419
+			}
420
+		}
421
+		return null;
422
+	}
423
+
424
+
425
+	/**
426
+	 * Returns whether the event ids passed in all share the same message template group for the current message type
427
+	 * and messenger.
428
+	 *
429
+	 * @param array $event_ids
430
+	 * @return bool true means they DO share the same message template group, false means they don't.
431
+	 * @throws EE_Error
432
+	 * @throws InvalidArgumentException
433
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
434
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
435
+	 */
436
+	protected function _queue_shares_same_message_template_group_for_events(array $event_ids)
437
+	{
438
+		foreach ($this->_current_data_handler->events as $event) {
439
+			$event_ids[ $event['ID'] ] = $event['ID'];
440
+		}
441
+		$count_of_message_template_groups = EEM_Message_Template_Group::instance()->count(
442
+			array(
443
+				array(
444
+					'Event.EVT_ID'           => array('IN', $event_ids),
445
+					'MTP_messenger'    => $this->_current_messenger->name,
446
+					'MTP_message_type' => $this->_current_message_type->name,
447
+				),
448
+			),
449
+			'GRP_ID',
450
+			true
451
+		);
452
+		return $count_of_message_template_groups === 1;
453
+	}
454
+
455
+
456
+	/**
457
+	 * This will get the shared message template group for events that are in the current data handler but ONLY if
458
+	 * there's a single shared message template group among all the events.  Otherwise it returns null.
459
+	 *
460
+	 * @param array $event_ids
461
+	 * @return EE_Message_Template_Group|null
462
+	 * @throws EE_Error
463
+	 * @throws InvalidArgumentException
464
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
465
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
466
+	 */
467
+	protected function _get_shared_message_template_for_events(array $event_ids)
468
+	{
469
+		$message_template_group = null;
470
+		if ($this->_queue_shares_same_message_template_group_for_events($event_ids)) {
471
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one(
472
+				array(
473
+					array(
474
+						'Event.EVT_ID'           => array('IN', $event_ids),
475
+						'MTP_messenger'    => $this->_current_messenger->name,
476
+						'MTP_message_type' => $this->_current_message_type->name,
477
+						'MTP_is_active'    => true,
478
+					),
479
+					'group_by' => 'GRP_ID',
480
+				)
481
+			);
482
+			// store this in the collection if its valid
483
+			if ($message_template_group instanceof EE_Message_Template_Group) {
484
+				$this->_template_collection->add(
485
+					$message_template_group,
486
+					$event_ids
487
+				);
488
+			}
489
+		}
490
+		return $message_template_group;
491
+	}
492
+
493
+
494
+	/**
495
+	 * Retrieves the global message template group for the current messenger and message type.
496
+	 *
497
+	 * @return EE_Message_Template_Group|null
498
+	 * @throws EE_Error
499
+	 * @throws InvalidArgumentException
500
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
501
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
502
+	 */
503
+	protected function _get_global_message_template_group_for_current_messenger_and_message_type()
504
+	{
505
+		// first check the collection (we use an array with 0 in it to represent global groups).
506
+		$global_message_template_group = $this->_template_collection->get_by_key(
507
+			$this->_template_collection->getKey(
508
+				$this->_current_messenger->name,
509
+				$this->_current_message_type->name,
510
+				array(0)
511
+			)
512
+		);
513
+
514
+		// if we don't have a group lets hit the db.
515
+		if (! $global_message_template_group instanceof EE_Message_Template_Group) {
516
+			$global_message_template_group = EEM_Message_Template_Group::instance()->get_one(
517
+				array(
518
+					array(
519
+						'MTP_messenger'    => $this->_current_messenger->name,
520
+						'MTP_message_type' => $this->_current_message_type->name,
521
+						'MTP_is_active'    => true,
522
+						'MTP_is_global'    => true,
523
+					),
524
+				)
525
+			);
526
+			// if we have a group, add it to the collection.
527
+			if ($global_message_template_group instanceof EE_Message_Template_Group) {
528
+				$this->_template_collection->add(
529
+					$global_message_template_group,
530
+					array(0)
531
+				);
532
+			}
533
+		}
534
+		return $global_message_template_group;
535
+	}
536
+
537
+
538
+	/**
539
+	 * Returns an array of event ids for all the events within the current data handler.
540
+	 *
541
+	 * @return array
542
+	 */
543
+	protected function _get_event_ids_from_current_data_handler()
544
+	{
545
+		$event_ids = array();
546
+		foreach ($this->_current_data_handler->events as $event) {
547
+			$event_ids[ $event['ID'] ] = $event['ID'];
548
+		}
549
+		return $event_ids;
550
+	}
551
+
552
+
553
+	/**
554
+	 *  Retrieves formatted array of template information for each context specific to the given
555
+	 *  EE_Message_Template_Group
556
+	 *
557
+	 * @param EE_Message_Template_Group $message_template_group
558
+	 * @return array The returned array is in this structure:
559
+	 *                          array(
560
+	 *                          'field_name' => array(
561
+	 *                          'context' => 'content'
562
+	 *                          )
563
+	 *                          )
564
+	 * @throws EE_Error
565
+	 */
566
+	protected function _get_templates(EE_Message_Template_Group $message_template_group)
567
+	{
568
+		$templates         = array();
569
+		$context_templates = $message_template_group->context_templates();
570
+		foreach ($context_templates as $context => $template_fields) {
571
+			foreach ($template_fields as $template_field => $template_obj) {
572
+				if (! $template_obj instanceof EE_Message_Template) {
573
+					continue;
574
+				}
575
+				$templates[ $template_field ][ $context ] = $template_obj->get('MTP_content');
576
+			}
577
+		}
578
+		return $templates;
579
+	}
580
+
581
+
582
+	/**
583
+	 * Assembles new fully generated EE_Message objects and adds to _ready_queue
584
+	 *
585
+	 * @param array                     $addressees  Array of EE_Messages_Addressee objects indexed by message type
586
+	 *                                               context.
587
+	 * @param array                     $templates   formatted array of templates used for parsing data.
588
+	 * @param EE_Message_Template_Group $message_template_group
589
+	 * @return bool true if message generation went a-ok.  false if some sort of exception occurred.  Note: The
590
+	 *                                               method will attempt to generate ALL EE_Message objects and add to
591
+	 *                                               the _ready_queue.  Successfully generated messages get added to the
592
+	 *                                               queue with EEM_Message::status_idle, unsuccessfully generated
593
+	 *                                               messages will get added to the queue as EEM_Message::status_failed.
594
+	 *                                               Very rarely should "false" be returned from this method.
595
+	 * @throws EE_Error
596
+	 */
597
+	protected function _assemble_messages($addressees, $templates, EE_Message_Template_Group $message_template_group)
598
+	{
599
+
600
+		// if templates are empty then get out because we can't generate anything.
601
+		if (! $templates) {
602
+			$this->_error_msg[] = esc_html__(
603
+				'Unable to assemble messages because there are no templates retrieved for generating the messages with',
604
+				'event_espresso'
605
+			);
606
+			return false;
607
+		}
608
+
609
+		// We use this as the counter for generated messages because don't forget we may be executing this inside of a
610
+		// generation_queue.  So _ready_queue may have generated EE_Message objects already.
611
+		$generated_count = 0;
612
+		foreach ($addressees as $context => $recipients) {
613
+			foreach ($recipients as $recipient) {
614
+				$message = $this->_setup_message_object($context, $recipient, $templates, $message_template_group);
615
+				if ($message instanceof EE_Message) {
616
+					$this->_ready_queue->add(
617
+						$message,
618
+						array(),
619
+						$this->_generation_queue->get_message_repository()->is_preview(),
620
+						$this->_generation_queue->get_message_repository()->is_test_send()
621
+					);
622
+					$generated_count++;
623
+				}
624
+
625
+				// if the current MSG being generated is for a test send then we'll only use ONE message in the
626
+				// generation.
627
+				if ($this->_generation_queue->get_message_repository()->is_test_send()) {
628
+					break 2;
629
+				}
630
+			}
631
+		}
632
+
633
+		// if there are no generated messages then something else fatal went wrong.
634
+		return $generated_count > 0;
635
+	}
636
+
637
+
638
+	/**
639
+	 * @param string                    $context   The context for the generated message.
640
+	 * @param EE_Messages_Addressee     $recipient
641
+	 * @param array                     $templates formatted array of templates used for parsing data.
642
+	 * @param EE_Message_Template_Group $message_template_group
643
+	 * @return bool|EE_Message
644
+	 * @throws EE_Error
645
+	 */
646
+	protected function _setup_message_object(
647
+		$context,
648
+		EE_Messages_Addressee $recipient,
649
+		$templates,
650
+		EE_Message_Template_Group $message_template_group
651
+	) {
652
+		// stuff we already know
653
+		$transaction_id = $recipient->txn instanceof EE_Transaction ? $recipient->txn->ID() : 0;
654
+		$transaction_id = empty($transaction_id) && $this->_current_data_handler->txn instanceof EE_Transaction
655
+			? $this->_current_data_handler->txn->ID()
656
+			: $transaction_id;
657
+		$message_fields = array(
658
+			'GRP_ID'           => $message_template_group->ID(),
659
+			'TXN_ID'           => $transaction_id,
660
+			'MSG_messenger'    => $this->_current_messenger->name,
661
+			'MSG_message_type' => $this->_current_message_type->name,
662
+			'MSG_context'      => $context,
663
+		);
664
+
665
+		// recipient id and type should be on the EE_Messages_Addressee object but if this is empty, let's try to grab
666
+		// the info from the att_obj found in the EE_Messages_Addressee object.
667
+		if (empty($recipient->recipient_id) || empty($recipient->recipient_type)) {
668
+			$message_fields['MSG_recipient_ID']   = $recipient->att_obj instanceof EE_Attendee
669
+				? $recipient->att_obj->ID()
670
+				: 0;
671
+			$message_fields['MSG_recipient_type'] = 'Attendee';
672
+		} else {
673
+			$message_fields['MSG_recipient_ID']   = $recipient->recipient_id;
674
+			$message_fields['MSG_recipient_type'] = $recipient->recipient_type;
675
+		}
676
+		$message = EE_Message_Factory::create($message_fields);
677
+
678
+		// grab valid shortcodes for shortcode parser
679
+		$mt_shortcodes = $this->_current_message_type->get_valid_shortcodes();
680
+		$m_shortcodes  = $this->_current_messenger->get_valid_shortcodes();
681
+
682
+		// if the 'to' field is empty or the context is inactive we skip EXCEPT if we're previewing
683
+		if ((
684
+				(
685
+					empty($templates['to'][ $context ])
686
+					&& ! $this->_current_messenger->allow_empty_to_field()
687
+				)
688
+				|| ! $message_template_group->is_context_active($context)
689
+			)
690
+			&& ! $this->_generation_queue->get_message_repository()->is_preview()
691
+		) {
692
+			// we silently exit here and do NOT record a fail because the message is "turned off" by having no "to"
693
+			// field.
694
+			return false;
695
+		}
696
+		$error_msg = array();
697
+		foreach ($templates as $field => $field_context) {
698
+			$error_msg = array();
699
+			// let's setup the valid shortcodes for the incoming context.
700
+			$valid_shortcodes = $mt_shortcodes[ $context ];
701
+			// merge in valid shortcodes for the field.
702
+			$shortcodes = isset($m_shortcodes[ $field ]) ? $m_shortcodes[ $field ] : $valid_shortcodes;
703
+			if (isset($templates[ $field ][ $context ])) {
704
+				// prefix field.
705
+				$column_name = 'MSG_' . $field;
706
+				try {
707
+					$content = $this->_shortcode_parser->parse_message_template(
708
+						$templates[ $field ][ $context ],
709
+						$recipient,
710
+						$shortcodes,
711
+						$this->_current_message_type,
712
+						$this->_current_messenger,
713
+						$message
714
+					);
715
+					// the model field removes slashes when setting (usually necessary when the input is from the
716
+					// request) but this value is from another model and has no slashes. So add them so it matchces
717
+					// what the field expected (otherwise slashes will have been stripped from this an extra time)
718
+					$message->set_field_or_extra_meta($column_name, addslashes($content));
719
+				} catch (EE_Error $e) {
720
+					$error_msg[] = sprintf(
721
+						esc_html__(
722
+							'There was a problem generating the content for the field %s: %s',
723
+							'event_espresso'
724
+						),
725
+						$field,
726
+						$e->getMessage()
727
+					);
728
+					$message->set_STS_ID(EEM_Message::status_failed);
729
+				}
730
+			}
731
+		}
732
+
733
+		if ($message->STS_ID() === EEM_Message::status_failed) {
734
+			$error_msg = esc_html__('There were problems generating this message:', 'event_espresso')
735
+						 . "\n"
736
+						 . implode("\n", $error_msg);
737
+			$message->set_error_message($error_msg);
738
+		} else {
739
+			$message->set_STS_ID(EEM_Message::status_idle);
740
+		}
741
+		return $message;
742
+	}
743
+
744
+
745
+	/**
746
+	 * This verifies that the incoming array has a EE_messenger object and a EE_message_type object and sets appropriate
747
+	 * error message if either is missing.
748
+	 *
749
+	 * @return bool true means there were no errors, false means there were errors.
750
+	 * @throws EE_Error
751
+	 * @throws ReflectionException
752
+	 */
753
+	protected function _verify()
754
+	{
755
+		// reset error message to an empty array.
756
+		$this->_error_msg = array();
757
+		$valid            = true;
758
+		$valid            = $valid ? $this->_validate_messenger_and_message_type() : $valid;
759
+		$valid            = $valid ? $this->_validate_and_setup_data() : $valid;
760
+
761
+		// set the verified flag so we know everything has been validated.
762
+		$this->_verified = $valid;
763
+
764
+		return $valid;
765
+	}
766
+
767
+
768
+	/**
769
+	 * This accepts an array and validates that it is an array indexed by context with each value being an array of
770
+	 * EE_Messages_Addressee objects.
771
+	 *
772
+	 * @param array $addressees Keys correspond to contexts for the message type and values are EE_Messages_Addressee[]
773
+	 * @return bool
774
+	 */
775
+	protected function _valid_addressees($addressees)
776
+	{
777
+		if (! $addressees || ! is_array($addressees)) {
778
+			return false;
779
+		}
780
+
781
+		foreach ($addressees as $addressee_array) {
782
+			foreach ($addressee_array as $addressee) {
783
+				if (! $addressee instanceof EE_Messages_Addressee) {
784
+					return false;
785
+				}
786
+			}
787
+		}
788
+		return true;
789
+	}
790
+
791
+
792
+	/**
793
+	 * This validates the messenger, message type, and presences of generation data for the current EE_Message in the
794
+	 * queue. This process sets error messages if something is wrong.
795
+	 *
796
+	 * @return bool   true is if there are no errors.  false is if there is.
797
+	 */
798
+	protected function _validate_messenger_and_message_type()
799
+	{
800
+
801
+		// first are there any existing error messages?  If so then return.
802
+		if ($this->_error_msg) {
803
+			return false;
804
+		}
805
+		/** @type EE_Message $message */
806
+		$message = $this->_generation_queue->get_message_repository()->current();
807
+		try {
808
+			$this->_current_messenger = $message->valid_messenger(true)
809
+				? $message->messenger_object()
810
+				: null;
811
+		} catch (Exception $e) {
812
+			$this->_error_msg[] = $e->getMessage();
813
+		}
814
+		try {
815
+			$this->_current_message_type = $message->valid_message_type(true)
816
+				? $message->message_type_object()
817
+				: null;
818
+		} catch (Exception $e) {
819
+			$this->_error_msg[] = $e->getMessage();
820
+		}
821
+
822
+		/**
823
+		 * Check if there is any generation data, but only if this is not for a preview.
824
+		 */
825
+		if (! $this->_generation_queue->get_message_repository()->get_generation_data()
826
+			&& (
827
+				! $this->_generation_queue->get_message_repository()->is_preview()
828
+				&& $this->_generation_queue->get_message_repository()->get_data_handler()
829
+				   !== 'EE_Messages_Preview_incoming_data'
830
+			)
831
+		) {
832
+			$this->_error_msg[] = esc_html__(
833
+				'There is no generation data for this message. Unable to generate.',
834
+				'event_espresso'
835
+			);
836
+		}
837
+
838
+		return empty($this->_error_msg);
839
+	}
840
+
841
+
842
+	/**
843
+	 * This method retrieves the expected data handler for the message type and validates the generation data for that
844
+	 * data handler.
845
+	 *
846
+	 * @return bool true means there are no errors.  false means there were errors (and handler did not get setup).
847
+	 * @throws EE_Error
848
+	 * @throws ReflectionException
849
+	 */
850
+	protected function _validate_and_setup_data()
851
+	{
852
+
853
+		// First, are there any existing error messages?  If so, return because if there were errors elsewhere this can't
854
+		// be used anyways.
855
+		if ($this->_error_msg) {
856
+			return false;
857
+		}
858
+
859
+		$generation_data = $this->_generation_queue->get_message_repository()->get_generation_data();
860
+
861
+		/** @type EE_Messages_incoming_data $data_handler_class_name - well not really... just the class name actually*/
862
+		$data_handler_class_name = $this->_generation_queue->get_message_repository()->get_data_handler()
863
+			? $this->_generation_queue->get_message_repository()->get_data_handler()
864
+			: 'EE_Messages_' . $this->_current_message_type->get_data_handler($generation_data) . '_incoming_data';
865
+
866
+		// If this EE_Message is for a preview, then let's switch out to the preview data handler.
867
+		if ($this->_generation_queue->get_message_repository()->is_preview()) {
868
+			$data_handler_class_name = 'EE_Messages_Preview_incoming_data';
869
+		}
870
+
871
+		// First get the class name for the data handler (and also verifies it exists.
872
+		if (! class_exists($data_handler_class_name)) {
873
+			$this->_error_msg[] = sprintf(
874
+				esc_html__(
875
+					'The included data handler class name does not match any valid, accessible, "%1$s" classes.  Looking for %2$s.',
876
+					'event_espresso'
877
+				),
878
+				'EE_Messages_incoming_data',
879
+				$data_handler_class_name
880
+			);
881
+			return false;
882
+		}
883
+
884
+		// convert generation_data for data_handler_instantiation.
885
+		$generation_data = $data_handler_class_name::convert_data_from_persistent_storage($generation_data);
886
+
887
+		// note, this may set error messages as well.
888
+		$this->_set_data_handler($generation_data, $data_handler_class_name);
889
+
890
+		return empty($this->_error_msg);
891
+	}
892
+
893
+
894
+	/**
895
+	 * Sets the $_current_data_handler property that is used for generating the current EE_Message in the queue, and
896
+	 * adds it to the _data repository.
897
+	 *
898
+	 * @param mixed  $generating_data           This is data expected by the instantiated data handler.
899
+	 * @param string $data_handler_class_name   This is the reference string indicating what data handler is being
900
+	 *                                          instantiated.
901
+	 * @return void .
902
+	 * @throws EE_Error
903
+	 * @throws ReflectionException
904
+	 */
905
+	protected function _set_data_handler($generating_data, $data_handler_class_name)
906
+	{
907
+		// valid classname for the data handler.  Now let's setup the key for the data handler repository to see if there
908
+		// is already a ready data handler in the repository.
909
+		$this->_current_data_handler = $this->_data_handler_collection->get_by_key(
910
+			$this->_data_handler_collection->get_key(
911
+				$data_handler_class_name,
912
+				$generating_data
913
+			)
914
+		);
915
+		if (! $this->_current_data_handler instanceof EE_Messages_incoming_data) {
916
+			// no saved data_handler in the repo so let's set one up and add it to the repo.
917
+			try {
918
+				$this->_current_data_handler = new $data_handler_class_name($generating_data);
919
+				$this->_data_handler_collection->add($this->_current_data_handler, $generating_data);
920
+			} catch (EE_Error $e) {
921
+				$this->_error_msg[] = $e->get_error();
922
+			}
923
+		}
924
+	}
925
+
926
+
927
+	/**
928
+	 * The queued EE_Message for generation does not save the data used for generation as objects
929
+	 * because serialization of those objects could be problematic if the data is saved to the db.
930
+	 * So this method calls the static method on the associated data_handler for the given message_type
931
+	 * and that preps the data for later instantiation when generating.
932
+	 *
933
+	 * @param EE_Message_To_Generate $message_to_generate
934
+	 * @param bool                   $preview Indicate whether this is being used for a preview or not.
935
+	 * @return mixed Prepped data for persisting to the queue.  false is returned if unable to prep data.
936
+	 */
937
+	protected function _prepare_data_for_queue(EE_Message_To_Generate $message_to_generate, $preview)
938
+	{
939
+		/** @type EE_Messages_incoming_data $data_handler - well not really... just the class name actually */
940
+		$data_handler = $message_to_generate->get_data_handler_class_name($preview);
941
+		if (! $message_to_generate->valid()) {
942
+			return false; // unable to get the data because the info in the EE_Message_To_Generate class is invalid.
943
+		}
944
+		return $data_handler::convert_data_for_persistent_storage($message_to_generate->data());
945
+	}
946
+
947
+
948
+	/**
949
+	 * This sets up a EEM_Message::status_incomplete EE_Message object and adds it to the generation queue.
950
+	 *
951
+	 * @param EE_Message_To_Generate $message_to_generate
952
+	 * @param bool                   $test_send Whether this is just a test send or not.  Typically used for previews.
953
+	 * @throws InvalidArgumentException
954
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
955
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
956
+	 */
957
+	public function create_and_add_message_to_queue(EE_Message_To_Generate $message_to_generate, $test_send = false)
958
+	{
959
+		// prep data
960
+		$data = $this->_prepare_data_for_queue($message_to_generate, $message_to_generate->preview());
961
+
962
+		$message = $message_to_generate->get_EE_Message();
963
+
964
+		// is there a GRP_ID in the request?
965
+		if ($GRP_ID = EE_Registry::instance()->REQ->get('GRP_ID')) {
966
+			$message->set_GRP_ID($GRP_ID);
967
+		}
968
+
969
+		if ($data === false) {
970
+			$message->set_STS_ID(EEM_Message::status_failed);
971
+			$message->set_error_message(
972
+				esc_html__(
973
+					'Unable to prepare data for persistence to the database.',
974
+					'event_espresso'
975
+				)
976
+			);
977
+		} else {
978
+			// make sure that the data handler is cached on the message as well
979
+			$data['data_handler_class_name'] = $message_to_generate->get_data_handler_class_name();
980
+		}
981
+
982
+		$this->_generation_queue->add($message, $data, $message_to_generate->preview(), $test_send);
983
+	}
984 984
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
     {
259 259
         // double check verification has run and that everything is ready to work with (saves us having to validate
260 260
         // everything again).
261
-        if (! $this->_verified) {
261
+        if ( ! $this->_verified) {
262 262
             return false; // get out because we don't have a valid setup to work with.
263 263
         }
264 264
 
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 
276 276
 
277 277
         // if no addressees then get out because there is nothing to generation (possible bad data).
278
-        if (! $this->_valid_addressees($addressees)) {
278
+        if ( ! $this->_valid_addressees($addressees)) {
279 279
             do_action(
280 280
                 'AHEE__EE_Messages_Generator___generate__invalid_addressees',
281 281
                 $this->_generation_queue->get_message_repository()->current(),
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
         $message_template_group = $this->_get_message_template_group();
298 298
 
299 299
         // in the unlikely event there is no EE_Message_Template_Group available, get out!
300
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
300
+        if ( ! $message_template_group instanceof EE_Message_Template_Group) {
301 301
             $this->_error_msg[] = esc_html__(
302 302
                 'Unable to get the Message Templates for the Message being generated.  No message template group accessible.',
303 303
                 'event_espresso'
@@ -407,7 +407,7 @@  discard block
 block discarded – undo
407 407
             // attempt to retrieve from repo first
408 408
             $message_template_group = $this->_template_collection->get_by_ID($GRP_ID);
409 409
             if ($message_template_group instanceof EE_Message_Template_Group) {
410
-                return $message_template_group;  // got it!
410
+                return $message_template_group; // got it!
411 411
             }
412 412
 
413 413
             // nope don't have it yet.  Get from DB then add to repo if its not here, then that means the current GRP_ID
@@ -436,7 +436,7 @@  discard block
 block discarded – undo
436 436
     protected function _queue_shares_same_message_template_group_for_events(array $event_ids)
437 437
     {
438 438
         foreach ($this->_current_data_handler->events as $event) {
439
-            $event_ids[ $event['ID'] ] = $event['ID'];
439
+            $event_ids[$event['ID']] = $event['ID'];
440 440
         }
441 441
         $count_of_message_template_groups = EEM_Message_Template_Group::instance()->count(
442 442
             array(
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
         );
513 513
 
514 514
         // if we don't have a group lets hit the db.
515
-        if (! $global_message_template_group instanceof EE_Message_Template_Group) {
515
+        if ( ! $global_message_template_group instanceof EE_Message_Template_Group) {
516 516
             $global_message_template_group = EEM_Message_Template_Group::instance()->get_one(
517 517
                 array(
518 518
                     array(
@@ -544,7 +544,7 @@  discard block
 block discarded – undo
544 544
     {
545 545
         $event_ids = array();
546 546
         foreach ($this->_current_data_handler->events as $event) {
547
-            $event_ids[ $event['ID'] ] = $event['ID'];
547
+            $event_ids[$event['ID']] = $event['ID'];
548 548
         }
549 549
         return $event_ids;
550 550
     }
@@ -569,10 +569,10 @@  discard block
 block discarded – undo
569 569
         $context_templates = $message_template_group->context_templates();
570 570
         foreach ($context_templates as $context => $template_fields) {
571 571
             foreach ($template_fields as $template_field => $template_obj) {
572
-                if (! $template_obj instanceof EE_Message_Template) {
572
+                if ( ! $template_obj instanceof EE_Message_Template) {
573 573
                     continue;
574 574
                 }
575
-                $templates[ $template_field ][ $context ] = $template_obj->get('MTP_content');
575
+                $templates[$template_field][$context] = $template_obj->get('MTP_content');
576 576
             }
577 577
         }
578 578
         return $templates;
@@ -598,7 +598,7 @@  discard block
 block discarded – undo
598 598
     {
599 599
 
600 600
         // if templates are empty then get out because we can't generate anything.
601
-        if (! $templates) {
601
+        if ( ! $templates) {
602 602
             $this->_error_msg[] = esc_html__(
603 603
                 'Unable to assemble messages because there are no templates retrieved for generating the messages with',
604 604
                 'event_espresso'
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
         // if the 'to' field is empty or the context is inactive we skip EXCEPT if we're previewing
683 683
         if ((
684 684
                 (
685
-                    empty($templates['to'][ $context ])
685
+                    empty($templates['to'][$context])
686 686
                     && ! $this->_current_messenger->allow_empty_to_field()
687 687
                 )
688 688
                 || ! $message_template_group->is_context_active($context)
@@ -697,15 +697,15 @@  discard block
 block discarded – undo
697 697
         foreach ($templates as $field => $field_context) {
698 698
             $error_msg = array();
699 699
             // let's setup the valid shortcodes for the incoming context.
700
-            $valid_shortcodes = $mt_shortcodes[ $context ];
700
+            $valid_shortcodes = $mt_shortcodes[$context];
701 701
             // merge in valid shortcodes for the field.
702
-            $shortcodes = isset($m_shortcodes[ $field ]) ? $m_shortcodes[ $field ] : $valid_shortcodes;
703
-            if (isset($templates[ $field ][ $context ])) {
702
+            $shortcodes = isset($m_shortcodes[$field]) ? $m_shortcodes[$field] : $valid_shortcodes;
703
+            if (isset($templates[$field][$context])) {
704 704
                 // prefix field.
705
-                $column_name = 'MSG_' . $field;
705
+                $column_name = 'MSG_'.$field;
706 706
                 try {
707 707
                     $content = $this->_shortcode_parser->parse_message_template(
708
-                        $templates[ $field ][ $context ],
708
+                        $templates[$field][$context],
709 709
                         $recipient,
710 710
                         $shortcodes,
711 711
                         $this->_current_message_type,
@@ -774,13 +774,13 @@  discard block
 block discarded – undo
774 774
      */
775 775
     protected function _valid_addressees($addressees)
776 776
     {
777
-        if (! $addressees || ! is_array($addressees)) {
777
+        if ( ! $addressees || ! is_array($addressees)) {
778 778
             return false;
779 779
         }
780 780
 
781 781
         foreach ($addressees as $addressee_array) {
782 782
             foreach ($addressee_array as $addressee) {
783
-                if (! $addressee instanceof EE_Messages_Addressee) {
783
+                if ( ! $addressee instanceof EE_Messages_Addressee) {
784 784
                     return false;
785 785
                 }
786 786
             }
@@ -822,7 +822,7 @@  discard block
 block discarded – undo
822 822
         /**
823 823
          * Check if there is any generation data, but only if this is not for a preview.
824 824
          */
825
-        if (! $this->_generation_queue->get_message_repository()->get_generation_data()
825
+        if ( ! $this->_generation_queue->get_message_repository()->get_generation_data()
826 826
             && (
827 827
                 ! $this->_generation_queue->get_message_repository()->is_preview()
828 828
                 && $this->_generation_queue->get_message_repository()->get_data_handler()
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
         /** @type EE_Messages_incoming_data $data_handler_class_name - well not really... just the class name actually*/
862 862
         $data_handler_class_name = $this->_generation_queue->get_message_repository()->get_data_handler()
863 863
             ? $this->_generation_queue->get_message_repository()->get_data_handler()
864
-            : 'EE_Messages_' . $this->_current_message_type->get_data_handler($generation_data) . '_incoming_data';
864
+            : 'EE_Messages_'.$this->_current_message_type->get_data_handler($generation_data).'_incoming_data';
865 865
 
866 866
         // If this EE_Message is for a preview, then let's switch out to the preview data handler.
867 867
         if ($this->_generation_queue->get_message_repository()->is_preview()) {
@@ -869,7 +869,7 @@  discard block
 block discarded – undo
869 869
         }
870 870
 
871 871
         // First get the class name for the data handler (and also verifies it exists.
872
-        if (! class_exists($data_handler_class_name)) {
872
+        if ( ! class_exists($data_handler_class_name)) {
873 873
             $this->_error_msg[] = sprintf(
874 874
                 esc_html__(
875 875
                     'The included data handler class name does not match any valid, accessible, "%1$s" classes.  Looking for %2$s.',
@@ -912,7 +912,7 @@  discard block
 block discarded – undo
912 912
                 $generating_data
913 913
             )
914 914
         );
915
-        if (! $this->_current_data_handler instanceof EE_Messages_incoming_data) {
915
+        if ( ! $this->_current_data_handler instanceof EE_Messages_incoming_data) {
916 916
             // no saved data_handler in the repo so let's set one up and add it to the repo.
917 917
             try {
918 918
                 $this->_current_data_handler = new $data_handler_class_name($generating_data);
@@ -938,7 +938,7 @@  discard block
 block discarded – undo
938 938
     {
939 939
         /** @type EE_Messages_incoming_data $data_handler - well not really... just the class name actually */
940 940
         $data_handler = $message_to_generate->get_data_handler_class_name($preview);
941
-        if (! $message_to_generate->valid()) {
941
+        if ( ! $message_to_generate->valid()) {
942 942
             return false; // unable to get the data because the info in the EE_Message_To_Generate class is invalid.
943 943
         }
944 944
         return $data_handler::convert_data_for_persistent_storage($message_to_generate->data());
Please login to merge, or discard this patch.
messages/templates/ee_msg_editor_active_context_element.template.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -10,22 +10,22 @@  discard block
 block discarded – undo
10 10
  * @var int    $message_template_group_id The ID for the message template group this context belongs to.
11 11
  */
12 12
 $active_message = sprintf(
13
-    esc_html__(
14
-        'The template for %1$s is currently %2$sactive%3$s.',
15
-        'event_espresso'
16
-    ),
17
-    $context_label,
18
-    '<strong>',
19
-    '</strong>'
13
+	esc_html__(
14
+		'The template for %1$s is currently %2$sactive%3$s.',
15
+		'event_espresso'
16
+	),
17
+	$context_label,
18
+	'<strong>',
19
+	'</strong>'
20 20
 );
21 21
 $inactive_message = sprintf(
22
-    esc_html__(
23
-        'The template for %1$s is currently %2$sinactive%3$s.',
24
-        'event_espresso'
25
-    ),
26
-    $context_label,
27
-    '<strong>',
28
-    '</strong>'
22
+	esc_html__(
23
+		'The template for %1$s is currently %2$sinactive%3$s.',
24
+		'event_espresso'
25
+	),
26
+	$context_label,
27
+	'<strong>',
28
+	'</strong>'
29 29
 );
30 30
 ?>
31 31
 <div class="context-active-control-container">
@@ -34,8 +34,8 @@  discard block
 block discarded – undo
34 34
         <span id="on-off-nonce-<?php echo $context; ?>" class="hidden"><?php echo $nonce; ?></span>
35 35
         <span class="ee-on-off-toggle-label">
36 36
             <?php
37
-            echo $is_active ? $active_message : $inactive_message;
38
-            ?>
37
+			echo $is_active ? $active_message : $inactive_message;
38
+			?>
39 39
         </span>
40 40
         <div class="hidden js-data">
41 41
             <span class="ee-active-message"><?php echo $active_message; ?></span>
@@ -43,8 +43,8 @@  discard block
 block discarded – undo
43 43
         </div>
44 44
         <div class="switch">
45 45
             <?php
46
-            $checked = $is_active ? ' checked="checked"' : '';
47
-            ?>
46
+			$checked = $is_active ? ' checked="checked"' : '';
47
+			?>
48 48
             <input data-grpid="<?php echo $message_template_group_id; ?>" id="ee-on-off-toggle-<?php echo $context; ?>" type="checkbox" class="ee-on-off-toggle ee-toggle-round-flat"<?php echo $checked; ?> value="<?php echo $on_off_action; ?>">
49 49
             <label for="ee-on-off-toggle-<?php echo $context; ?>"></label>
50 50
         </div>
Please login to merge, or discard this patch.
acceptance_tests/tests/e-TestContextActivationToggleCept.php 1 patch
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -8,8 +8,8 @@  discard block
 block discarded – undo
8 8
 $event_label = 'Testing Context Deactivation';
9 9
 
10 10
 $I->wantTo(
11
-    'Test that the context activation toggle for turning on or off specific contexts for message sending works as'
12
-    . ' expected'
11
+	'Test that the context activation toggle for turning on or off specific contexts for message sending works as'
12
+	. ' expected'
13 13
 );
14 14
 
15 15
 $I->loginAsAdmin();
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
 $I->see('The template for Primary Registrant Recipient is currently inactive.');
35 35
 
36 36
 $I->amGoingTo(
37
-    'Trigger Registration Approved Messages and verify primary registrant context is excluded from sent messages.'
37
+	'Trigger Registration Approved Messages and verify primary registrant context is excluded from sent messages.'
38 38
 );
39 39
 $I->amOnDefaultEventsListTablePage();
40 40
 $I->click(EventsAdmin::ADD_NEW_EVENT_BUTTON_SELECTOR);
@@ -44,9 +44,9 @@  discard block
 block discarded – undo
44 44
 $event_link = $I->observeLinkUrlAt(EventsAdmin::EVENT_EDITOR_VIEW_LINK_AFTER_PUBLISH_SELECTOR);
45 45
 $event_id = $I->observeValueFromInputAt(EventsAdmin::EVENT_EDITOR_EVT_ID_SELECTOR);
46 46
 $test_registration_details = array(
47
-    'fname' => 'ContextTestGuy',
48
-    'lname' => 'ContextTestDude',
49
-    'email' => '[email protected]',
47
+	'fname' => 'ContextTestGuy',
48
+	'lname' => 'ContextTestDude',
49
+	'email' => '[email protected]',
50 50
 );
51 51
 $I->logOut();
52 52
 $I->amOnUrl($event_link);
@@ -63,48 +63,48 @@  discard block
 block discarded – undo
63 63
 $I->amOnMessagesActivityListTablePage();
64 64
 //verify registrant context
65 65
 $I->see(
66
-    $test_registration_details['email'],
67
-    MessagesAdmin::messagesActivityListTableCellSelectorFor(
68
-        'to',
69
-        'Registration Approved',
70
-        MessagesAdmin::MESSAGE_STATUS_SENT,
71
-        '',
72
-        'Registrant'
73
-    )
66
+	$test_registration_details['email'],
67
+	MessagesAdmin::messagesActivityListTableCellSelectorFor(
68
+		'to',
69
+		'Registration Approved',
70
+		MessagesAdmin::MESSAGE_STATUS_SENT,
71
+		'',
72
+		'Registrant'
73
+	)
74 74
 );
75 75
 $I->deleteMessageInMessagesListTableFor(
76
-    'Registration Approved',
77
-    MessagesAdmin::MESSAGE_STATUS_SENT,
78
-    'Email',
79
-    'Registrant'
76
+	'Registration Approved',
77
+	MessagesAdmin::MESSAGE_STATUS_SENT,
78
+	'Email',
79
+	'Registrant'
80 80
 );
81 81
 //verify admin context
82 82
 $I->see(
83
-    '[email protected]',
84
-    MessagesAdmin::messagesActivityListTableCellSelectorFor(
85
-        'to',
86
-        'Registration Approved',
87
-        MessagesAdmin::MESSAGE_STATUS_SENT
88
-    )
83
+	'[email protected]',
84
+	MessagesAdmin::messagesActivityListTableCellSelectorFor(
85
+		'to',
86
+		'Registration Approved',
87
+		MessagesAdmin::MESSAGE_STATUS_SENT
88
+	)
89 89
 );
90 90
 $I->deleteMessageInMessagesListTableFor(
91
-    'Registration Approved'
91
+	'Registration Approved'
92 92
 );
93 93
 //verify primary registrant context is NOT present.
94 94
 $I->dontSee(
95
-    $test_registration_details['email'],
96
-    MessagesAdmin::messagesActivityListTableCellSelectorFor(
97
-        'to',
98
-        'Registration Approved',
99
-        MessagesAdmin::MESSAGE_STATUS_SENT,
100
-        '',
101
-        'Primary Registrant'
102
-    )
95
+	$test_registration_details['email'],
96
+	MessagesAdmin::messagesActivityListTableCellSelectorFor(
97
+		'to',
98
+		'Registration Approved',
99
+		MessagesAdmin::MESSAGE_STATUS_SENT,
100
+		'',
101
+		'Primary Registrant'
102
+	)
103 103
 );
104 104
 
105 105
 $I->amGoingTo(
106
-    'Deactivate primary registrant context for Registration Approved Message Templates and restore the "To"'
107
-    . ' field to an empty string to verify the message does not send for that context.'
106
+	'Deactivate primary registrant context for Registration Approved Message Templates and restore the "To"'
107
+	. ' field to an empty string to verify the message does not send for that context.'
108 108
 );
109 109
 $I->amOnDefaultMessageTemplateListTablePage();
110 110
 $I->clickToEditMessageTemplateByMessageType('registration', 'primary_attendee');
@@ -128,41 +128,41 @@  discard block
 block discarded – undo
128 128
 $I->amOnMessagesActivityListTablePage();
129 129
 //verify registrant context
130 130
 $I->see(
131
-    $test_registration_details['email'],
132
-    MessagesAdmin::messagesActivityListTableCellSelectorFor(
133
-        'to',
134
-        'Registration Approved',
135
-        MessagesAdmin::MESSAGE_STATUS_SENT,
136
-        '',
137
-        'Registrant'
138
-    )
131
+	$test_registration_details['email'],
132
+	MessagesAdmin::messagesActivityListTableCellSelectorFor(
133
+		'to',
134
+		'Registration Approved',
135
+		MessagesAdmin::MESSAGE_STATUS_SENT,
136
+		'',
137
+		'Registrant'
138
+	)
139 139
 );
140 140
 $I->deleteMessageInMessagesListTableFor(
141
-    'Registration Approved',
142
-    MessagesAdmin::MESSAGE_STATUS_SENT,
143
-    'Email',
144
-    'Registrant'
141
+	'Registration Approved',
142
+	MessagesAdmin::MESSAGE_STATUS_SENT,
143
+	'Email',
144
+	'Registrant'
145 145
 );
146 146
 //verify admin context
147 147
 $I->see(
148
-    '[email protected]',
149
-    MessagesAdmin::messagesActivityListTableCellSelectorFor(
150
-        'to',
151
-        'Registration Approved',
152
-        MessagesAdmin::MESSAGE_STATUS_SENT
153
-    )
148
+	'[email protected]',
149
+	MessagesAdmin::messagesActivityListTableCellSelectorFor(
150
+		'to',
151
+		'Registration Approved',
152
+		MessagesAdmin::MESSAGE_STATUS_SENT
153
+	)
154 154
 );
155 155
 $I->deleteMessageInMessagesListTableFor(
156
-    'Registration Approved'
156
+	'Registration Approved'
157 157
 );
158 158
 //verify primary registrant context is NOT present.
159 159
 $I->dontSee(
160
-    $test_registration_details['email'],
161
-    MessagesAdmin::messagesActivityListTableCellSelectorFor(
162
-        'to',
163
-        'Registration Approved',
164
-        MessagesAdmin::MESSAGE_STATUS_SENT,
165
-        '',
166
-        'Primary Registrant'
167
-    )
160
+	$test_registration_details['email'],
161
+	MessagesAdmin::messagesActivityListTableCellSelectorFor(
162
+		'to',
163
+		'Registration Approved',
164
+		MessagesAdmin::MESSAGE_STATUS_SENT,
165
+		'',
166
+		'Primary Registrant'
167
+	)
168 168
 );
169 169
\ No newline at end of file
Please login to merge, or discard this patch.