Completed
Branch master (44537d)
by
unknown
14:30 queued 10:03
created
core/db_models/EEM_Registration_Payment.model.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -12,60 +12,60 @@
 block discarded – undo
12 12
  */
13 13
 class EEM_Registration_Payment extends EEM_Base
14 14
 {
15
-    // private instance
16
-    protected static $_instance = null;
15
+	// private instance
16
+	protected static $_instance = null;
17 17
 
18 18
 
19
-    /**
20
-     * @param string|null $timezone
21
-     * @throws EE_Error
22
-     */
23
-    protected function __construct(?string $timezone = '')
24
-    {
25
-        $this->singular_item = esc_html__('Registration Payment', 'event_espresso');
26
-        $this->plural_item   = esc_html__('Registration Payments', 'event_espresso');
19
+	/**
20
+	 * @param string|null $timezone
21
+	 * @throws EE_Error
22
+	 */
23
+	protected function __construct(?string $timezone = '')
24
+	{
25
+		$this->singular_item = esc_html__('Registration Payment', 'event_espresso');
26
+		$this->plural_item   = esc_html__('Registration Payments', 'event_espresso');
27 27
 
28
-        $this->_tables = [
29
-            'Registration_Payment' => new EE_Primary_Table('esp_registration_payment', 'RPY_ID'),
30
-        ];
28
+		$this->_tables = [
29
+			'Registration_Payment' => new EE_Primary_Table('esp_registration_payment', 'RPY_ID'),
30
+		];
31 31
 
32
-        $this->_fields = [
33
-            'Registration_Payment' => [
34
-                'RPY_ID'     => new EE_Primary_Key_Int_Field(
35
-                    'RPY_ID',
36
-                    esc_html__('Registration Payment ID', 'event_espresso')
37
-                ),
38
-                'REG_ID'     => new EE_Foreign_Key_Int_Field(
39
-                    'REG_ID',
40
-                    esc_html__('Registration ID', 'event_espresso'),
41
-                    false,
42
-                    0,
43
-                    'Registration'
44
-                ),
45
-                'PAY_ID'     => new EE_Foreign_Key_Int_Field(
46
-                    'PAY_ID',
47
-                    esc_html__('Payment ID', 'event_espresso'),
48
-                    true,
49
-                    null,
50
-                    'Payment'
51
-                ),
52
-                'RPY_amount' => new EE_Money_Field(
53
-                    'RPY_amount',
54
-                    esc_html__(
55
-                        'Amount attributed to the registration',
56
-                        'event_espresso'
57
-                    ),
58
-                    false,
59
-                    0
60
-                ),
61
-            ],
62
-        ];
32
+		$this->_fields = [
33
+			'Registration_Payment' => [
34
+				'RPY_ID'     => new EE_Primary_Key_Int_Field(
35
+					'RPY_ID',
36
+					esc_html__('Registration Payment ID', 'event_espresso')
37
+				),
38
+				'REG_ID'     => new EE_Foreign_Key_Int_Field(
39
+					'REG_ID',
40
+					esc_html__('Registration ID', 'event_espresso'),
41
+					false,
42
+					0,
43
+					'Registration'
44
+				),
45
+				'PAY_ID'     => new EE_Foreign_Key_Int_Field(
46
+					'PAY_ID',
47
+					esc_html__('Payment ID', 'event_espresso'),
48
+					true,
49
+					null,
50
+					'Payment'
51
+				),
52
+				'RPY_amount' => new EE_Money_Field(
53
+					'RPY_amount',
54
+					esc_html__(
55
+						'Amount attributed to the registration',
56
+						'event_espresso'
57
+					),
58
+					false,
59
+					0
60
+				),
61
+			],
62
+		];
63 63
 
64
-        $this->_model_relations = [
65
-            'Registration' => new EE_Belongs_To_Relation(),
66
-            'Payment'      => new EE_Belongs_To_Relation(),
67
-        ];
64
+		$this->_model_relations = [
65
+			'Registration' => new EE_Belongs_To_Relation(),
66
+			'Payment'      => new EE_Belongs_To_Relation(),
67
+		];
68 68
 
69
-        parent::__construct($timezone);
70
-    }
69
+		parent::__construct($timezone);
70
+	}
71 71
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Question_Group.model.php 1 patch
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -9,137 +9,137 @@
 block discarded – undo
9 9
  */
10 10
 class EEM_Question_Group extends EEM_Soft_Delete_Base
11 11
 {
12
-    const system_personal = 1;
12
+	const system_personal = 1;
13 13
 
14
-    const system_address  = 2;
14
+	const system_address  = 2;
15 15
 
16
-    /**
17
-     * private instance of the EEM_Question_Group object
18
-     *
19
-     * @var EEM_Question_Group
20
-     */
21
-    protected static $_instance = null;
16
+	/**
17
+	 * private instance of the EEM_Question_Group object
18
+	 *
19
+	 * @var EEM_Question_Group
20
+	 */
21
+	protected static $_instance = null;
22 22
 
23 23
 
24
-    /**
25
-     * EEM_Question_Group constructor.
26
-     *
27
-     * @param string|null $timezone
28
-     * @throws EE_Error
29
-     */
30
-    protected function __construct(?string $timezone = '')
31
-    {
32
-        $this->singular_item = esc_html__('Question Group', 'event_espresso');
33
-        $this->plural_item   = esc_html__('Question Groups', 'event_espresso');
24
+	/**
25
+	 * EEM_Question_Group constructor.
26
+	 *
27
+	 * @param string|null $timezone
28
+	 * @throws EE_Error
29
+	 */
30
+	protected function __construct(?string $timezone = '')
31
+	{
32
+		$this->singular_item = esc_html__('Question Group', 'event_espresso');
33
+		$this->plural_item   = esc_html__('Question Groups', 'event_espresso');
34 34
 
35
-        $this->_tables          = [
36
-            'Question_Group' => new EE_Primary_Table('esp_question_group', 'QSG_ID'),
37
-        ];
38
-        $this->_fields          = [
39
-            'Question_Group' => [
40
-                'QSG_ID'              => new EE_Primary_Key_Int_Field(
41
-                    'QSG_ID',
42
-                    esc_html__('Question Group ID', 'event_espresso')
43
-                ),
44
-                'QSG_deleted'         => new EE_Trashed_Flag_Field(
45
-                    'QSG_deleted',
46
-                    esc_html__('Flag indicating this question group was deleted', 'event_espresso'),
47
-                    false,
48
-                    false
49
-                ),
50
-                'QSG_desc'            => new EE_Post_Content_Field(
51
-                    'QSG_desc',
52
-                    esc_html__('Description of Question Group', 'event_espresso'),
53
-                    true,
54
-                    ''
55
-                ),
56
-                'QSG_identifier'      => new EE_Plain_Text_Field(
57
-                    'QSG_identifier',
58
-                    esc_html__('Text ID for question Group', 'event_espresso'),
59
-                    false,
60
-                    ''
61
-                ),
62
-                'QSG_name'            => new EE_Plain_Text_Field(
63
-                    'QSG_name',
64
-                    esc_html__('Question Group Name', 'event_espresso'),
65
-                    false,
66
-                    ''
67
-                ),
68
-                'QSG_order'           => new EE_Integer_Field(
69
-                    'QSG_order',
70
-                    esc_html__('Order in which to show the question group', 'event_espresso'),
71
-                    true,
72
-                    0
73
-                ),
74
-                'QSG_show_group_desc' => new EE_Boolean_Field(
75
-                    'QSG_show_group_desc',
76
-                    esc_html__(
77
-                        'Flag indicating whether to show the group\s description on the registration page',
78
-                        'event_espresso'
79
-                    ),
80
-                    false,
81
-                    false
82
-                ),
83
-                'QSG_show_group_name' => new EE_Boolean_Field(
84
-                    'QSG_show_group_name',
85
-                    esc_html__(
86
-                        'Flag indicating whether to show the group\'s name on the registration page',
87
-                        'event_espresso'
88
-                    ),
89
-                    false,
90
-                    true
91
-                ),
92
-                'QSG_system'          => new EE_Integer_Field(
93
-                    'QSG_system',
94
-                    esc_html__(
95
-                        'Indicate IF this is a system group and if it is what system group it corresponds to.',
96
-                        'event_espresso'
97
-                    ),
98
-                    false,
99
-                    0
100
-                ),
101
-                'QSG_wp_user'         => new EE_WP_User_Field(
102
-                    'QSG_wp_user',
103
-                    esc_html__('Question Group Creator ID', 'event_espresso'),
104
-                    false
105
-                ),
106
-            ],
107
-        ];
108
-        $this->_model_relations = [
109
-            'Event'                => new EE_HABTM_Relation('Event_Question_Group'),
110
-            'Event_Question_Group' => new EE_Has_Many_Relation(),
111
-            'Question'             => new EE_HABTM_Relation('Question_Group_Question'),
112
-            'WP_User'              => new EE_Belongs_To_Relation(),
113
-        ];
114
-        // this model is generally available for reading
115
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ]       =
116
-            new EE_Restriction_Generator_Public();
117
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
118
-            new EE_Restriction_Generator_Reg_Form('QSG_system');
119
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
120
-            new EE_Restriction_Generator_Reg_Form('QSG_system');
121
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
122
-            new EE_Restriction_Generator_Reg_Form('QSG_system');
35
+		$this->_tables          = [
36
+			'Question_Group' => new EE_Primary_Table('esp_question_group', 'QSG_ID'),
37
+		];
38
+		$this->_fields          = [
39
+			'Question_Group' => [
40
+				'QSG_ID'              => new EE_Primary_Key_Int_Field(
41
+					'QSG_ID',
42
+					esc_html__('Question Group ID', 'event_espresso')
43
+				),
44
+				'QSG_deleted'         => new EE_Trashed_Flag_Field(
45
+					'QSG_deleted',
46
+					esc_html__('Flag indicating this question group was deleted', 'event_espresso'),
47
+					false,
48
+					false
49
+				),
50
+				'QSG_desc'            => new EE_Post_Content_Field(
51
+					'QSG_desc',
52
+					esc_html__('Description of Question Group', 'event_espresso'),
53
+					true,
54
+					''
55
+				),
56
+				'QSG_identifier'      => new EE_Plain_Text_Field(
57
+					'QSG_identifier',
58
+					esc_html__('Text ID for question Group', 'event_espresso'),
59
+					false,
60
+					''
61
+				),
62
+				'QSG_name'            => new EE_Plain_Text_Field(
63
+					'QSG_name',
64
+					esc_html__('Question Group Name', 'event_espresso'),
65
+					false,
66
+					''
67
+				),
68
+				'QSG_order'           => new EE_Integer_Field(
69
+					'QSG_order',
70
+					esc_html__('Order in which to show the question group', 'event_espresso'),
71
+					true,
72
+					0
73
+				),
74
+				'QSG_show_group_desc' => new EE_Boolean_Field(
75
+					'QSG_show_group_desc',
76
+					esc_html__(
77
+						'Flag indicating whether to show the group\s description on the registration page',
78
+						'event_espresso'
79
+					),
80
+					false,
81
+					false
82
+				),
83
+				'QSG_show_group_name' => new EE_Boolean_Field(
84
+					'QSG_show_group_name',
85
+					esc_html__(
86
+						'Flag indicating whether to show the group\'s name on the registration page',
87
+						'event_espresso'
88
+					),
89
+					false,
90
+					true
91
+				),
92
+				'QSG_system'          => new EE_Integer_Field(
93
+					'QSG_system',
94
+					esc_html__(
95
+						'Indicate IF this is a system group and if it is what system group it corresponds to.',
96
+						'event_espresso'
97
+					),
98
+					false,
99
+					0
100
+				),
101
+				'QSG_wp_user'         => new EE_WP_User_Field(
102
+					'QSG_wp_user',
103
+					esc_html__('Question Group Creator ID', 'event_espresso'),
104
+					false
105
+				),
106
+			],
107
+		];
108
+		$this->_model_relations = [
109
+			'Event'                => new EE_HABTM_Relation('Event_Question_Group'),
110
+			'Event_Question_Group' => new EE_Has_Many_Relation(),
111
+			'Question'             => new EE_HABTM_Relation('Question_Group_Question'),
112
+			'WP_User'              => new EE_Belongs_To_Relation(),
113
+		];
114
+		// this model is generally available for reading
115
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ]       =
116
+			new EE_Restriction_Generator_Public();
117
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
118
+			new EE_Restriction_Generator_Reg_Form('QSG_system');
119
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
120
+			new EE_Restriction_Generator_Reg_Form('QSG_system');
121
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
122
+			new EE_Restriction_Generator_Reg_Form('QSG_system');
123 123
 
124
-        parent::__construct($timezone);
125
-    }
124
+		parent::__construct($timezone);
125
+	}
126 126
 
127 127
 
128
-    /**
129
-     * searches the db for the question group with the latest question order and returns that value.
130
-     *
131
-     * @return int
132
-     * @throws EE_Error
133
-     */
134
-    public function get_latest_question_group_order(): int
135
-    {
136
-        $max = $this->_get_all_wpdb_results(
137
-            [],
138
-            ARRAY_A,
139
-            [
140
-                'max_order' => ["MAX(QSG_order)", "%d"],
141
-            ]
142
-        );
143
-        return $max[0]['max_order'];
144
-    }
128
+	/**
129
+	 * searches the db for the question group with the latest question order and returns that value.
130
+	 *
131
+	 * @return int
132
+	 * @throws EE_Error
133
+	 */
134
+	public function get_latest_question_group_order(): int
135
+	{
136
+		$max = $this->_get_all_wpdb_results(
137
+			[],
138
+			ARRAY_A,
139
+			[
140
+				'max_order' => ["MAX(QSG_order)", "%d"],
141
+			]
142
+		);
143
+		return $max[0]['max_order'];
144
+	}
145 145
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Attendee.model.php 2 patches
Indentation   +409 added lines, -409 removed lines patch added patch discarded remove patch
@@ -12,421 +12,421 @@
 block discarded – undo
12 12
  */
13 13
 class EEM_Attendee extends EEM_CPT_Base
14 14
 {
15
-    // private instance of the Attendee object
16
-    protected static $_instance = null;
15
+	// private instance of the Attendee object
16
+	protected static $_instance = null;
17 17
 
18
-    /**
19
-     * QST_system for questions are strings not integers now,
20
-     * so these constants are deprecated.
21
-     * Please instead use the EEM_Attendee::system_question_* constants
22
-     *
23
-     * @deprecated
24
-     */
25
-    const fname_question_id = 1;
18
+	/**
19
+	 * QST_system for questions are strings not integers now,
20
+	 * so these constants are deprecated.
21
+	 * Please instead use the EEM_Attendee::system_question_* constants
22
+	 *
23
+	 * @deprecated
24
+	 */
25
+	const fname_question_id = 1;
26 26
 
27
-    /**
28
-     * @deprecated
29
-     */
30
-    const lname_question_id = 2;
27
+	/**
28
+	 * @deprecated
29
+	 */
30
+	const lname_question_id = 2;
31 31
 
32 32
 
33
-    /**
34
-     * @deprecated
35
-     */
36
-    const email_question_id = 3;
33
+	/**
34
+	 * @deprecated
35
+	 */
36
+	const email_question_id = 3;
37 37
 
38 38
 
39
-    /**
40
-     * @deprecated
41
-     */
42
-    const address_question_id = 4;
39
+	/**
40
+	 * @deprecated
41
+	 */
42
+	const address_question_id = 4;
43 43
 
44 44
 
45
-    /**
46
-     * @deprecated
47
-     */
48
-    const address2_question_id = 5;
49
-
50
-
51
-    /**
52
-     * @deprecated
53
-     */
54
-    const city_question_id = 6;
55
-
56
-
57
-    /**
58
-     * @deprecated
59
-     */
60
-    const state_question_id = 7;
61
-
62
-
63
-    /**
64
-     * @deprecated
65
-     */
66
-    const country_question_id = 8;
67
-
68
-
69
-    /**
70
-     * @deprecated
71
-     */
72
-    const zip_question_id = 9;
73
-
74
-
75
-    /**
76
-     * @deprecated
77
-     */
78
-    const phone_question_id = 10;
79
-
80
-    /**
81
-     * When looking for questions that correspond to attendee fields,
82
-     * look for the question with this QST_system value.
83
-     * These replace the old constants like EEM_Attendee::*_question_id
84
-     */
85
-    const system_question_fname         = 'fname';
86
-
87
-    const system_question_lname         = 'lname';
88
-
89
-    const system_question_email         = 'email';
90
-
91
-    const system_question_email_confirm = 'email_confirm';
92
-
93
-    const system_question_address       = 'address';
94
-
95
-    const system_question_address2      = 'address2';
96
-
97
-    const system_question_city          = 'city';
98
-
99
-    const system_question_state         = 'state';
100
-
101
-    const system_question_country       = 'country';
102
-
103
-    const system_question_zip           = 'zip';
104
-
105
-    const system_question_phone         = 'phone';
106
-
107
-    /**
108
-     * Keys are all the EEM_Attendee::system_question_* constants, which are
109
-     * also all the values of QST_system in the questions table, and values
110
-     * are their corresponding Attendee field names
111
-     *
112
-     * @var array
113
-     */
114
-    protected $_system_question_to_attendee_field_name = [
115
-        EEM_Attendee::system_question_fname    => 'ATT_fname',
116
-        EEM_Attendee::system_question_lname    => 'ATT_lname',
117
-        EEM_Attendee::system_question_email    => 'ATT_email',
118
-        EEM_Attendee::system_question_address  => 'ATT_address',
119
-        EEM_Attendee::system_question_address2 => 'ATT_address2',
120
-        EEM_Attendee::system_question_city     => 'ATT_city',
121
-        EEM_Attendee::system_question_state    => 'STA_ID',
122
-        EEM_Attendee::system_question_country  => 'CNT_ISO',
123
-        EEM_Attendee::system_question_zip      => 'ATT_zip',
124
-        EEM_Attendee::system_question_phone    => 'ATT_phone',
125
-    ];
126
-
127
-
128
-    /**
129
-     * @param string|null            $timezone
130
-     * @param ModelFieldFactory|null $model_field_factory
131
-     * @throws EE_Error
132
-     */
133
-    protected function __construct(?string $timezone = '', ModelFieldFactory $model_field_factory = null)
134
-    {
135
-        $this->singular_item           = esc_html__('Attendee', 'event_espresso');
136
-        $this->plural_item             = esc_html__('Attendees', 'event_espresso');
137
-        $this->_tables                 = [
138
-            'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
139
-            'Attendee_Meta' => new EE_Secondary_Table(
140
-                'esp_attendee_meta',
141
-                'ATTM_ID',
142
-                'ATT_ID'
143
-            ),
144
-        ];
145
-        $this->_fields                 = [
146
-            'Attendee_CPT'  => [
147
-                'ATT_ID'        => $model_field_factory->createPrimaryKeyIntField(
148
-                    'ID',
149
-                    esc_html__('Attendee ID', 'event_espresso')
150
-                ),
151
-                'ATT_full_name' => $model_field_factory->createPlainTextField(
152
-                    'post_title',
153
-                    esc_html__('Attendee Full Name', 'event_espresso'),
154
-                    false,
155
-                    esc_html__('Unknown', 'event_espresso')
156
-                ),
157
-                'ATT_bio'       => $model_field_factory->createPostContentField(
158
-                    'post_content',
159
-                    esc_html__('Attendee Biography', 'event_espresso'),
160
-                    false,
161
-                    esc_html__('No Biography Provided', 'event_espresso')
162
-                ),
163
-                'ATT_slug'      => $model_field_factory->createSlugField(
164
-                    'post_name',
165
-                    esc_html__('Attendee URL Slug', 'event_espresso')
166
-                ),
167
-                'ATT_created'   => $model_field_factory->createDatetimeField(
168
-                    'post_date',
169
-                    esc_html__('Time Attendee Created', 'event_espresso')
170
-                ),
171
-                'ATT_short_bio' => $model_field_factory->createSimpleHtmlField(
172
-                    'post_excerpt',
173
-                    esc_html__('Attendee Short Biography', 'event_espresso'),
174
-                    true,
175
-                    esc_html__('No Biography Provided', 'event_espresso')
176
-                ),
177
-                'ATT_modified'  => $model_field_factory->createDatetimeField(
178
-                    'post_modified',
179
-                    esc_html__('Time Attendee Last Modified', 'event_espresso')
180
-                ),
181
-                'ATT_author'    => $model_field_factory->createWpUserField(
182
-                    'post_author',
183
-                    esc_html__('Creator ID of the first Event attended', 'event_espresso'),
184
-                    false
185
-                ),
186
-                'ATT_parent'    => $model_field_factory->createDbOnlyIntField(
187
-                    'post_parent',
188
-                    esc_html__('Parent Attendee (unused)', 'event_espresso'),
189
-                    false,
190
-                    0
191
-                ),
192
-                'post_type'     => $model_field_factory->createWpPostTypeField('espresso_attendees'),
193
-                'status'        => $model_field_factory->createWpPostStatusField(
194
-                    'post_status',
195
-                    esc_html__('Attendee Status', 'event_espresso'),
196
-                    false,
197
-                    'publish'
198
-                ),
199
-                'password'      => new EE_Password_Field(
200
-                    'post_password',
201
-                    esc_html__('Password', 'event_espresso'),
202
-                    false,
203
-                    '',
204
-                    [
205
-                        'ATT_bio',
206
-                        'ATT_short_bio',
207
-                        'ATT_address',
208
-                        'ATT_address2',
209
-                        'ATT_city',
210
-                        'STA_ID',
211
-                        'CNT_ISO',
212
-                        'ATT_zip',
213
-                        'ATT_email',
214
-                        'ATT_phone',
215
-                    ]
216
-                ),
217
-            ],
218
-            'Attendee_Meta' => [
219
-                'ATTM_ID'      => $model_field_factory->createDbOnlyIntField(
220
-                    'ATTM_ID',
221
-                    esc_html__('Attendee Meta Row ID', 'event_espresso'),
222
-                    false
223
-                ),
224
-                'ATT_ID_fk'    => $model_field_factory->createDbOnlyIntField(
225
-                    'ATT_ID',
226
-                    esc_html__('Foreign Key to Attendee in Post Table', 'event_espresso'),
227
-                    false
228
-                ),
229
-                'ATT_fname'    => $model_field_factory->createPlainTextField(
230
-                    'ATT_fname',
231
-                    esc_html__('First Name', 'event_espresso')
232
-                ),
233
-                'ATT_lname'    => $model_field_factory->createPlainTextField(
234
-                    'ATT_lname',
235
-                    esc_html__('Last Name', 'event_espresso')
236
-                ),
237
-                'ATT_address'  => $model_field_factory->createPlainTextField(
238
-                    'ATT_address',
239
-                    esc_html__('Address Part 1', 'event_espresso')
240
-                ),
241
-                'ATT_address2' => $model_field_factory->createPlainTextField(
242
-                    'ATT_address2',
243
-                    esc_html__('Address Part 2', 'event_espresso')
244
-                ),
245
-                'ATT_city'     => $model_field_factory->createPlainTextField(
246
-                    'ATT_city',
247
-                    esc_html__('City', 'event_espresso')
248
-                ),
249
-                'STA_ID'       => $model_field_factory->createForeignKeyIntField(
250
-                    'STA_ID',
251
-                    esc_html__('State', 'event_espresso'),
252
-                    true,
253
-                    0,
254
-                    'State'
255
-                ),
256
-                'CNT_ISO'      => $model_field_factory->createForeignKeyStringField(
257
-                    'CNT_ISO',
258
-                    esc_html__('Country', 'event_espresso'),
259
-                    true,
260
-                    '',
261
-                    'Country'
262
-                ),
263
-                'ATT_zip'      => $model_field_factory->createPlainTextField(
264
-                    'ATT_zip',
265
-                    esc_html__('ZIP/Postal Code', 'event_espresso')
266
-                ),
267
-                'ATT_email'    => $model_field_factory->createEmailField(
268
-                    'ATT_email',
269
-                    esc_html__('Email Address', 'event_espresso')
270
-                ),
271
-                'ATT_phone'    => $model_field_factory->createPlainTextField(
272
-                    'ATT_phone',
273
-                    esc_html__('Phone', 'event_espresso')
274
-                ),
275
-            ],
276
-        ];
277
-        $this->_model_relations        = [
278
-            'Registration'      => new EE_Has_Many_Relation(),
279
-            'State'             => new EE_Belongs_To_Relation(),
280
-            'Country'           => new EE_Belongs_To_Relation(),
281
-            'Event'             => new EE_HABTM_Relation('Registration', false),
282
-            'WP_User'           => new EE_Belongs_To_Relation(),
283
-            'Message'           => new EE_Has_Many_Any_Relation(false),
284
-            // allow deletion of attendees even if they have messages in the queue for them.
285
-            'Term_Relationship' => new EE_Has_Many_Relation(),
286
-            'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
287
-        ];
288
-        $this->_caps_slug              = 'contacts';
289
-        $this->model_chain_to_password = '';
290
-        parent::__construct($timezone);
291
-    }
292
-
293
-
294
-    /**
295
-     * Gets the name of the field on the attendee model corresponding to the system question string
296
-     * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
297
-     *
298
-     * @param string $system_question_string
299
-     * @return string|null if not found
300
-     */
301
-    public function get_attendee_field_for_system_question($system_question_string)
302
-    {
303
-        return isset($this->_system_question_to_attendee_field_name[ $system_question_string ])
304
-            ? $this->_system_question_to_attendee_field_name[ $system_question_string ]
305
-            : null;
306
-    }
307
-
308
-
309
-    /**
310
-     * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
311
-     *
312
-     * @return array
313
-     */
314
-    public function system_question_to_attendee_field_mapping()
315
-    {
316
-        return $this->_system_question_to_attendee_field_name;
317
-    }
318
-
319
-
320
-    /**
321
-     * Gets all the attendees for a transaction (by using the esp_registration as a join table)
322
-     *
323
-     * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
324
-     * @return EE_Attendee[]|EE_Base_Class[]
325
-     * @throws EE_Error
326
-     */
327
-    public function get_attendees_for_transaction($transaction_id_or_obj)
328
-    {
329
-        return $this->get_all(
330
-            [
331
-                [
332
-                    'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
333
-                        ? $transaction_id_or_obj->ID()
334
-                        : $transaction_id_or_obj,
335
-                ],
336
-            ]
337
-        );
338
-    }
339
-
340
-
341
-    /**
342
-     * retrieve  a single attendee from db via their ID
343
-     *
344
-     * @param $ATT_ID
345
-     * @return mixed array on success, FALSE on fail
346
-     * @deprecated
347
-     */
348
-    public function get_attendee_by_ID($ATT_ID = false)
349
-    {
350
-        // retrieve a particular EE_Attendee
351
-        return $this->get_one_by_ID($ATT_ID);
352
-    }
353
-
354
-
355
-    /**
356
-     * retrieve  a single attendee from db via their ID
357
-     *
358
-     * @param array $where_cols_n_values
359
-     * @return mixed array on success, FALSE on fail
360
-     * @throws EE_Error
361
-     */
362
-    public function get_attendee($where_cols_n_values = [])
363
-    {
364
-        if (empty($where_cols_n_values)) {
365
-            return false;
366
-        }
367
-        $attendee = $this->get_all([$where_cols_n_values]);
368
-        if (! empty($attendee)) {
369
-            return array_shift($attendee);
370
-        }
371
-        return false;
372
-    }
373
-
374
-
375
-    /**
376
-     * Search for an existing Attendee record in the DB
377
-     *
378
-     * @param array $where_cols_n_values
379
-     * @return bool|mixed
380
-     * @throws EE_Error
381
-     */
382
-    public function find_existing_attendee($where_cols_n_values = null)
383
-    {
384
-        // search by combo of first and last names plus the email address
385
-        $attendee_data_keys = [
386
-            'ATT_fname' => $this->_ATT_fname,
387
-            'ATT_lname' => $this->_ATT_lname,
388
-            'ATT_email' => $this->_ATT_email,
389
-        ];
390
-        // no search params means attendee object already exists.
391
-        $where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values)
392
-            ? $where_cols_n_values
393
-            : $attendee_data_keys;
394
-        $valid_data          = true;
395
-        // check for required values
396
-        $valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
397
-            ? $valid_data
398
-            : false;
399
-        $valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
400
-            ? $valid_data
401
-            : false;
402
-        $valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
403
-            ? $valid_data
404
-            : false;
405
-        if ($valid_data) {
406
-            $attendee = $this->get_attendee($where_cols_n_values);
407
-            if ($attendee instanceof EE_Attendee) {
408
-                return $attendee;
409
-            }
410
-        }
411
-        return false;
412
-    }
413
-
414
-
415
-    /**
416
-     * Takes an incoming array of EE_Registration ids
417
-     * and sends back a list of corresponding non duplicate EE_Attendee objects.
418
-     *
419
-     * @param array $ids array of EE_Registration ids
420
-     * @return EE_Attendee[]|EE_Base_Class[]
421
-     * @throws EE_Error
422
-     * @since  4.3.0
423
-     */
424
-    public function get_array_of_contacts_from_reg_ids($ids)
425
-    {
426
-        $ids    = (array) $ids;
427
-        $_where = [
428
-            'Registration.REG_ID' => ['in', $ids],
429
-        ];
430
-        return $this->get_all([$_where]);
431
-    }
45
+	/**
46
+	 * @deprecated
47
+	 */
48
+	const address2_question_id = 5;
49
+
50
+
51
+	/**
52
+	 * @deprecated
53
+	 */
54
+	const city_question_id = 6;
55
+
56
+
57
+	/**
58
+	 * @deprecated
59
+	 */
60
+	const state_question_id = 7;
61
+
62
+
63
+	/**
64
+	 * @deprecated
65
+	 */
66
+	const country_question_id = 8;
67
+
68
+
69
+	/**
70
+	 * @deprecated
71
+	 */
72
+	const zip_question_id = 9;
73
+
74
+
75
+	/**
76
+	 * @deprecated
77
+	 */
78
+	const phone_question_id = 10;
79
+
80
+	/**
81
+	 * When looking for questions that correspond to attendee fields,
82
+	 * look for the question with this QST_system value.
83
+	 * These replace the old constants like EEM_Attendee::*_question_id
84
+	 */
85
+	const system_question_fname         = 'fname';
86
+
87
+	const system_question_lname         = 'lname';
88
+
89
+	const system_question_email         = 'email';
90
+
91
+	const system_question_email_confirm = 'email_confirm';
92
+
93
+	const system_question_address       = 'address';
94
+
95
+	const system_question_address2      = 'address2';
96
+
97
+	const system_question_city          = 'city';
98
+
99
+	const system_question_state         = 'state';
100
+
101
+	const system_question_country       = 'country';
102
+
103
+	const system_question_zip           = 'zip';
104
+
105
+	const system_question_phone         = 'phone';
106
+
107
+	/**
108
+	 * Keys are all the EEM_Attendee::system_question_* constants, which are
109
+	 * also all the values of QST_system in the questions table, and values
110
+	 * are their corresponding Attendee field names
111
+	 *
112
+	 * @var array
113
+	 */
114
+	protected $_system_question_to_attendee_field_name = [
115
+		EEM_Attendee::system_question_fname    => 'ATT_fname',
116
+		EEM_Attendee::system_question_lname    => 'ATT_lname',
117
+		EEM_Attendee::system_question_email    => 'ATT_email',
118
+		EEM_Attendee::system_question_address  => 'ATT_address',
119
+		EEM_Attendee::system_question_address2 => 'ATT_address2',
120
+		EEM_Attendee::system_question_city     => 'ATT_city',
121
+		EEM_Attendee::system_question_state    => 'STA_ID',
122
+		EEM_Attendee::system_question_country  => 'CNT_ISO',
123
+		EEM_Attendee::system_question_zip      => 'ATT_zip',
124
+		EEM_Attendee::system_question_phone    => 'ATT_phone',
125
+	];
126
+
127
+
128
+	/**
129
+	 * @param string|null            $timezone
130
+	 * @param ModelFieldFactory|null $model_field_factory
131
+	 * @throws EE_Error
132
+	 */
133
+	protected function __construct(?string $timezone = '', ModelFieldFactory $model_field_factory = null)
134
+	{
135
+		$this->singular_item           = esc_html__('Attendee', 'event_espresso');
136
+		$this->plural_item             = esc_html__('Attendees', 'event_espresso');
137
+		$this->_tables                 = [
138
+			'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
139
+			'Attendee_Meta' => new EE_Secondary_Table(
140
+				'esp_attendee_meta',
141
+				'ATTM_ID',
142
+				'ATT_ID'
143
+			),
144
+		];
145
+		$this->_fields                 = [
146
+			'Attendee_CPT'  => [
147
+				'ATT_ID'        => $model_field_factory->createPrimaryKeyIntField(
148
+					'ID',
149
+					esc_html__('Attendee ID', 'event_espresso')
150
+				),
151
+				'ATT_full_name' => $model_field_factory->createPlainTextField(
152
+					'post_title',
153
+					esc_html__('Attendee Full Name', 'event_espresso'),
154
+					false,
155
+					esc_html__('Unknown', 'event_espresso')
156
+				),
157
+				'ATT_bio'       => $model_field_factory->createPostContentField(
158
+					'post_content',
159
+					esc_html__('Attendee Biography', 'event_espresso'),
160
+					false,
161
+					esc_html__('No Biography Provided', 'event_espresso')
162
+				),
163
+				'ATT_slug'      => $model_field_factory->createSlugField(
164
+					'post_name',
165
+					esc_html__('Attendee URL Slug', 'event_espresso')
166
+				),
167
+				'ATT_created'   => $model_field_factory->createDatetimeField(
168
+					'post_date',
169
+					esc_html__('Time Attendee Created', 'event_espresso')
170
+				),
171
+				'ATT_short_bio' => $model_field_factory->createSimpleHtmlField(
172
+					'post_excerpt',
173
+					esc_html__('Attendee Short Biography', 'event_espresso'),
174
+					true,
175
+					esc_html__('No Biography Provided', 'event_espresso')
176
+				),
177
+				'ATT_modified'  => $model_field_factory->createDatetimeField(
178
+					'post_modified',
179
+					esc_html__('Time Attendee Last Modified', 'event_espresso')
180
+				),
181
+				'ATT_author'    => $model_field_factory->createWpUserField(
182
+					'post_author',
183
+					esc_html__('Creator ID of the first Event attended', 'event_espresso'),
184
+					false
185
+				),
186
+				'ATT_parent'    => $model_field_factory->createDbOnlyIntField(
187
+					'post_parent',
188
+					esc_html__('Parent Attendee (unused)', 'event_espresso'),
189
+					false,
190
+					0
191
+				),
192
+				'post_type'     => $model_field_factory->createWpPostTypeField('espresso_attendees'),
193
+				'status'        => $model_field_factory->createWpPostStatusField(
194
+					'post_status',
195
+					esc_html__('Attendee Status', 'event_espresso'),
196
+					false,
197
+					'publish'
198
+				),
199
+				'password'      => new EE_Password_Field(
200
+					'post_password',
201
+					esc_html__('Password', 'event_espresso'),
202
+					false,
203
+					'',
204
+					[
205
+						'ATT_bio',
206
+						'ATT_short_bio',
207
+						'ATT_address',
208
+						'ATT_address2',
209
+						'ATT_city',
210
+						'STA_ID',
211
+						'CNT_ISO',
212
+						'ATT_zip',
213
+						'ATT_email',
214
+						'ATT_phone',
215
+					]
216
+				),
217
+			],
218
+			'Attendee_Meta' => [
219
+				'ATTM_ID'      => $model_field_factory->createDbOnlyIntField(
220
+					'ATTM_ID',
221
+					esc_html__('Attendee Meta Row ID', 'event_espresso'),
222
+					false
223
+				),
224
+				'ATT_ID_fk'    => $model_field_factory->createDbOnlyIntField(
225
+					'ATT_ID',
226
+					esc_html__('Foreign Key to Attendee in Post Table', 'event_espresso'),
227
+					false
228
+				),
229
+				'ATT_fname'    => $model_field_factory->createPlainTextField(
230
+					'ATT_fname',
231
+					esc_html__('First Name', 'event_espresso')
232
+				),
233
+				'ATT_lname'    => $model_field_factory->createPlainTextField(
234
+					'ATT_lname',
235
+					esc_html__('Last Name', 'event_espresso')
236
+				),
237
+				'ATT_address'  => $model_field_factory->createPlainTextField(
238
+					'ATT_address',
239
+					esc_html__('Address Part 1', 'event_espresso')
240
+				),
241
+				'ATT_address2' => $model_field_factory->createPlainTextField(
242
+					'ATT_address2',
243
+					esc_html__('Address Part 2', 'event_espresso')
244
+				),
245
+				'ATT_city'     => $model_field_factory->createPlainTextField(
246
+					'ATT_city',
247
+					esc_html__('City', 'event_espresso')
248
+				),
249
+				'STA_ID'       => $model_field_factory->createForeignKeyIntField(
250
+					'STA_ID',
251
+					esc_html__('State', 'event_espresso'),
252
+					true,
253
+					0,
254
+					'State'
255
+				),
256
+				'CNT_ISO'      => $model_field_factory->createForeignKeyStringField(
257
+					'CNT_ISO',
258
+					esc_html__('Country', 'event_espresso'),
259
+					true,
260
+					'',
261
+					'Country'
262
+				),
263
+				'ATT_zip'      => $model_field_factory->createPlainTextField(
264
+					'ATT_zip',
265
+					esc_html__('ZIP/Postal Code', 'event_espresso')
266
+				),
267
+				'ATT_email'    => $model_field_factory->createEmailField(
268
+					'ATT_email',
269
+					esc_html__('Email Address', 'event_espresso')
270
+				),
271
+				'ATT_phone'    => $model_field_factory->createPlainTextField(
272
+					'ATT_phone',
273
+					esc_html__('Phone', 'event_espresso')
274
+				),
275
+			],
276
+		];
277
+		$this->_model_relations        = [
278
+			'Registration'      => new EE_Has_Many_Relation(),
279
+			'State'             => new EE_Belongs_To_Relation(),
280
+			'Country'           => new EE_Belongs_To_Relation(),
281
+			'Event'             => new EE_HABTM_Relation('Registration', false),
282
+			'WP_User'           => new EE_Belongs_To_Relation(),
283
+			'Message'           => new EE_Has_Many_Any_Relation(false),
284
+			// allow deletion of attendees even if they have messages in the queue for them.
285
+			'Term_Relationship' => new EE_Has_Many_Relation(),
286
+			'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
287
+		];
288
+		$this->_caps_slug              = 'contacts';
289
+		$this->model_chain_to_password = '';
290
+		parent::__construct($timezone);
291
+	}
292
+
293
+
294
+	/**
295
+	 * Gets the name of the field on the attendee model corresponding to the system question string
296
+	 * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
297
+	 *
298
+	 * @param string $system_question_string
299
+	 * @return string|null if not found
300
+	 */
301
+	public function get_attendee_field_for_system_question($system_question_string)
302
+	{
303
+		return isset($this->_system_question_to_attendee_field_name[ $system_question_string ])
304
+			? $this->_system_question_to_attendee_field_name[ $system_question_string ]
305
+			: null;
306
+	}
307
+
308
+
309
+	/**
310
+	 * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
311
+	 *
312
+	 * @return array
313
+	 */
314
+	public function system_question_to_attendee_field_mapping()
315
+	{
316
+		return $this->_system_question_to_attendee_field_name;
317
+	}
318
+
319
+
320
+	/**
321
+	 * Gets all the attendees for a transaction (by using the esp_registration as a join table)
322
+	 *
323
+	 * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
324
+	 * @return EE_Attendee[]|EE_Base_Class[]
325
+	 * @throws EE_Error
326
+	 */
327
+	public function get_attendees_for_transaction($transaction_id_or_obj)
328
+	{
329
+		return $this->get_all(
330
+			[
331
+				[
332
+					'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
333
+						? $transaction_id_or_obj->ID()
334
+						: $transaction_id_or_obj,
335
+				],
336
+			]
337
+		);
338
+	}
339
+
340
+
341
+	/**
342
+	 * retrieve  a single attendee from db via their ID
343
+	 *
344
+	 * @param $ATT_ID
345
+	 * @return mixed array on success, FALSE on fail
346
+	 * @deprecated
347
+	 */
348
+	public function get_attendee_by_ID($ATT_ID = false)
349
+	{
350
+		// retrieve a particular EE_Attendee
351
+		return $this->get_one_by_ID($ATT_ID);
352
+	}
353
+
354
+
355
+	/**
356
+	 * retrieve  a single attendee from db via their ID
357
+	 *
358
+	 * @param array $where_cols_n_values
359
+	 * @return mixed array on success, FALSE on fail
360
+	 * @throws EE_Error
361
+	 */
362
+	public function get_attendee($where_cols_n_values = [])
363
+	{
364
+		if (empty($where_cols_n_values)) {
365
+			return false;
366
+		}
367
+		$attendee = $this->get_all([$where_cols_n_values]);
368
+		if (! empty($attendee)) {
369
+			return array_shift($attendee);
370
+		}
371
+		return false;
372
+	}
373
+
374
+
375
+	/**
376
+	 * Search for an existing Attendee record in the DB
377
+	 *
378
+	 * @param array $where_cols_n_values
379
+	 * @return bool|mixed
380
+	 * @throws EE_Error
381
+	 */
382
+	public function find_existing_attendee($where_cols_n_values = null)
383
+	{
384
+		// search by combo of first and last names plus the email address
385
+		$attendee_data_keys = [
386
+			'ATT_fname' => $this->_ATT_fname,
387
+			'ATT_lname' => $this->_ATT_lname,
388
+			'ATT_email' => $this->_ATT_email,
389
+		];
390
+		// no search params means attendee object already exists.
391
+		$where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values)
392
+			? $where_cols_n_values
393
+			: $attendee_data_keys;
394
+		$valid_data          = true;
395
+		// check for required values
396
+		$valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
397
+			? $valid_data
398
+			: false;
399
+		$valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
400
+			? $valid_data
401
+			: false;
402
+		$valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
403
+			? $valid_data
404
+			: false;
405
+		if ($valid_data) {
406
+			$attendee = $this->get_attendee($where_cols_n_values);
407
+			if ($attendee instanceof EE_Attendee) {
408
+				return $attendee;
409
+			}
410
+		}
411
+		return false;
412
+	}
413
+
414
+
415
+	/**
416
+	 * Takes an incoming array of EE_Registration ids
417
+	 * and sends back a list of corresponding non duplicate EE_Attendee objects.
418
+	 *
419
+	 * @param array $ids array of EE_Registration ids
420
+	 * @return EE_Attendee[]|EE_Base_Class[]
421
+	 * @throws EE_Error
422
+	 * @since  4.3.0
423
+	 */
424
+	public function get_array_of_contacts_from_reg_ids($ids)
425
+	{
426
+		$ids    = (array) $ids;
427
+		$_where = [
428
+			'Registration.REG_ID' => ['in', $ids],
429
+		];
430
+		return $this->get_all([$_where]);
431
+	}
432 432
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
                 'ATT_ID'
143 143
             ),
144 144
         ];
145
-        $this->_fields                 = [
145
+        $this->_fields = [
146 146
             'Attendee_CPT'  => [
147 147
                 'ATT_ID'        => $model_field_factory->createPrimaryKeyIntField(
148 148
                     'ID',
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
                 ),
275 275
             ],
276 276
         ];
277
-        $this->_model_relations        = [
277
+        $this->_model_relations = [
278 278
             'Registration'      => new EE_Has_Many_Relation(),
279 279
             'State'             => new EE_Belongs_To_Relation(),
280 280
             'Country'           => new EE_Belongs_To_Relation(),
@@ -300,8 +300,8 @@  discard block
 block discarded – undo
300 300
      */
301 301
     public function get_attendee_field_for_system_question($system_question_string)
302 302
     {
303
-        return isset($this->_system_question_to_attendee_field_name[ $system_question_string ])
304
-            ? $this->_system_question_to_attendee_field_name[ $system_question_string ]
303
+        return isset($this->_system_question_to_attendee_field_name[$system_question_string])
304
+            ? $this->_system_question_to_attendee_field_name[$system_question_string]
305 305
             : null;
306 306
     }
307 307
 
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
             return false;
366 366
         }
367 367
         $attendee = $this->get_all([$where_cols_n_values]);
368
-        if (! empty($attendee)) {
368
+        if ( ! empty($attendee)) {
369 369
             return array_shift($attendee);
370 370
         }
371 371
         return false;
Please login to merge, or discard this patch.
core/db_models/EEM_Datetime_Ticket.model.php 2 patches
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -10,59 +10,59 @@
 block discarded – undo
10 10
  */
11 11
 class EEM_Datetime_Ticket extends EEM_Base
12 12
 {
13
-    // private instance of the EEM_Datetime_Ticket object
14
-    protected static $_instance = null;
13
+	// private instance of the EEM_Datetime_Ticket object
14
+	protected static $_instance = null;
15 15
 
16 16
 
17
-    /**
18
-     * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings (and
19
-     *                              any incoming timezone data that gets saved).  Note this just sends the timezone
20
-     *                              info to the date time model field objects.  Default is NULL (and will be assumed
21
-     *                              using the set timezone in the 'timezone_string' wp option)
22
-     * @throws EE_Error
23
-     */
24
-    protected function __construct(?string $timezone = '')
25
-    {
26
-        $this->singular_item = esc_html__('Datetime Ticket', 'event_espresso');
27
-        $this->plural_item   = esc_html__('Datetime Tickets', 'event_espresso');
17
+	/**
18
+	 * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings (and
19
+	 *                              any incoming timezone data that gets saved).  Note this just sends the timezone
20
+	 *                              info to the date time model field objects.  Default is NULL (and will be assumed
21
+	 *                              using the set timezone in the 'timezone_string' wp option)
22
+	 * @throws EE_Error
23
+	 */
24
+	protected function __construct(?string $timezone = '')
25
+	{
26
+		$this->singular_item = esc_html__('Datetime Ticket', 'event_espresso');
27
+		$this->plural_item   = esc_html__('Datetime Tickets', 'event_espresso');
28 28
 
29
-        $this->_tables          = [
30
-            'Datetime_Ticket' => new EE_Primary_Table('esp_datetime_ticket', 'DTK_ID'),
31
-        ];
32
-        $this->_fields          = [
33
-            'Datetime_Ticket' => [
34
-                'DTK_ID' => new EE_Primary_Key_Int_Field('DTK_ID', esc_html__('Datetime Ticket ID', 'event_espresso')),
35
-                'DTT_ID' => new EE_Foreign_Key_Int_Field(
36
-                    'DTT_ID',
37
-                    esc_html__('The ID to the Datetime', 'event_espresso'),
38
-                    false,
39
-                    0,
40
-                    'Datetime'
41
-                ),
42
-                'TKT_ID' => new EE_Foreign_Key_Int_Field(
43
-                    'TKT_ID',
44
-                    esc_html__('The ID to the Ticket', 'event_espresso'),
45
-                    false,
46
-                    0,
47
-                    'Ticket'
48
-                ),
49
-            ],
50
-        ];
51
-        $this->_model_relations = [
52
-            'Ticket'   => new EE_Belongs_To_Relation(),
53
-            'Datetime' => new EE_Belongs_To_Relation(),
54
-        ];
55
-        // this model is generally available for reading
56
-        $path_to_event                                                  = 'Datetime.Event';
57
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ]       =
58
-            new EE_Restriction_Generator_Event_Related_Public($path_to_event);
59
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
60
-            new EE_Restriction_Generator_Event_Related_Protected($path_to_event);
61
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
62
-            new EE_Restriction_Generator_Event_Related_Protected($path_to_event);
63
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
64
-            new EE_Restriction_Generator_Event_Related_Protected($path_to_event, EEM_Base::caps_edit);
65
-        $this->model_chain_to_password                                  = $path_to_event;
66
-        parent::__construct($timezone);
67
-    }
29
+		$this->_tables          = [
30
+			'Datetime_Ticket' => new EE_Primary_Table('esp_datetime_ticket', 'DTK_ID'),
31
+		];
32
+		$this->_fields          = [
33
+			'Datetime_Ticket' => [
34
+				'DTK_ID' => new EE_Primary_Key_Int_Field('DTK_ID', esc_html__('Datetime Ticket ID', 'event_espresso')),
35
+				'DTT_ID' => new EE_Foreign_Key_Int_Field(
36
+					'DTT_ID',
37
+					esc_html__('The ID to the Datetime', 'event_espresso'),
38
+					false,
39
+					0,
40
+					'Datetime'
41
+				),
42
+				'TKT_ID' => new EE_Foreign_Key_Int_Field(
43
+					'TKT_ID',
44
+					esc_html__('The ID to the Ticket', 'event_espresso'),
45
+					false,
46
+					0,
47
+					'Ticket'
48
+				),
49
+			],
50
+		];
51
+		$this->_model_relations = [
52
+			'Ticket'   => new EE_Belongs_To_Relation(),
53
+			'Datetime' => new EE_Belongs_To_Relation(),
54
+		];
55
+		// this model is generally available for reading
56
+		$path_to_event                                                  = 'Datetime.Event';
57
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ]       =
58
+			new EE_Restriction_Generator_Event_Related_Public($path_to_event);
59
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
60
+			new EE_Restriction_Generator_Event_Related_Protected($path_to_event);
61
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
62
+			new EE_Restriction_Generator_Event_Related_Protected($path_to_event);
63
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
64
+			new EE_Restriction_Generator_Event_Related_Protected($path_to_event, EEM_Base::caps_edit);
65
+		$this->model_chain_to_password                                  = $path_to_event;
66
+		parent::__construct($timezone);
67
+	}
68 68
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -54,13 +54,13 @@
 block discarded – undo
54 54
         ];
55 55
         // this model is generally available for reading
56 56
         $path_to_event                                                  = 'Datetime.Event';
57
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ]       =
57
+        $this->_cap_restriction_generators[EEM_Base::caps_read]       =
58 58
             new EE_Restriction_Generator_Event_Related_Public($path_to_event);
59
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
59
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] =
60 60
             new EE_Restriction_Generator_Event_Related_Protected($path_to_event);
61
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
61
+        $this->_cap_restriction_generators[EEM_Base::caps_edit]       =
62 62
             new EE_Restriction_Generator_Event_Related_Protected($path_to_event);
63
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
63
+        $this->_cap_restriction_generators[EEM_Base::caps_delete]     =
64 64
             new EE_Restriction_Generator_Event_Related_Protected($path_to_event, EEM_Base::caps_edit);
65 65
         $this->model_chain_to_password                                  = $path_to_event;
66 66
         parent::__construct($timezone);
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6672 added lines, -6672 removed lines patch added patch discarded remove patch
@@ -37,6678 +37,6678 @@
 block discarded – undo
37 37
  */
38 38
 abstract class EEM_Base extends EE_Base implements ResettableInterface
39 39
 {
40
-    /**
41
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
42
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
43
-     * They almost always WILL NOT, but it's not necessarily a requirement.
44
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
45
-     *
46
-     * @var boolean
47
-     */
48
-    private $_values_already_prepared_by_model_object = 0;
49
-
50
-    /**
51
-     * when $_values_already_prepared_by_model_object equals this, we assume
52
-     * the data is just like form input that needs to have the model fields'
53
-     * prepare_for_set and prepare_for_use_in_db called on it
54
-     */
55
-    const not_prepared_by_model_object = 0;
56
-
57
-    /**
58
-     * when $_values_already_prepared_by_model_object equals this, we
59
-     * assume this value is coming from a model object and doesn't need to have
60
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
61
-     */
62
-    const prepared_by_model_object = 1;
63
-
64
-    /**
65
-     * when $_values_already_prepared_by_model_object equals this, we assume
66
-     * the values are already to be used in the database (ie no processing is done
67
-     * on them by the model's fields)
68
-     */
69
-    const prepared_for_use_in_db = 2;
70
-
71
-
72
-    protected $singular_item = 'Item';
73
-
74
-    protected $plural_item   = 'Items';
75
-
76
-    /**
77
-     * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
78
-     */
79
-    protected $_tables;
80
-
81
-    /**
82
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
83
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
84
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
85
-     *
86
-     * @var EE_Model_Field_Base[][] $_fields
87
-     */
88
-    protected $_fields;
89
-
90
-    /**
91
-     * array of different kinds of relations
92
-     *
93
-     * @var EE_Model_Relation_Base[] $_model_relations
94
-     */
95
-    protected $_model_relations = [];
96
-
97
-    /**
98
-     * @var EE_Index[] $_indexes
99
-     */
100
-    protected $_indexes = [];
101
-
102
-    /**
103
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
104
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
105
-     * by setting the same columns as used in these queries in the query yourself.
106
-     *
107
-     * @var EE_Default_Where_Conditions
108
-     */
109
-    protected $_default_where_conditions_strategy;
110
-
111
-    /**
112
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
113
-     * This is particularly useful when you want something between 'none' and 'default'
114
-     *
115
-     * @var EE_Default_Where_Conditions
116
-     */
117
-    protected $_minimum_where_conditions_strategy;
118
-
119
-    /**
120
-     * String describing how to find the "owner" of this model's objects.
121
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
122
-     * But when there isn't, this indicates which related model, or transiently-related model,
123
-     * has the foreign key to the wp_users table.
124
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
125
-     * related to events, and events have a foreign key to wp_users.
126
-     * On EEM_Transaction, this would be 'Transaction.Event'
127
-     *
128
-     * @var string
129
-     */
130
-    protected $_model_chain_to_wp_user = '';
131
-
132
-    /**
133
-     * String describing how to find the model with a password controlling access to this model. This property has the
134
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
135
-     * This value is the path of models to follow to arrive at the model with the password field.
136
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
137
-     * model with a password that should affect reading this on the front-end.
138
-     * Eg this is an empty string for the Event model because it has a password.
139
-     * This is null for the Registration model, because its event's password has no bearing on whether
140
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
141
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
142
-     * should hide tickets for datetimes for events that have a password set.
143
-     *
144
-     * @var string |null
145
-     */
146
-    protected $model_chain_to_password = null;
147
-
148
-    /**
149
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
150
-     * don't need it (particularly CPT models)
151
-     *
152
-     * @var bool
153
-     */
154
-    protected $_ignore_where_strategy = false;
155
-
156
-    /**
157
-     * String used in caps relating to this model. Eg, if the caps relating to this
158
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
159
-     *
160
-     * @var string. If null it hasn't been initialized yet. If false then we
161
-     * have indicated capabilities don't apply to this
162
-     */
163
-    protected $_caps_slug = null;
164
-
165
-    /**
166
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
167
-     * and next-level keys are capability names, and each's value is a
168
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
169
-     * they specify which context to use (ie, frontend, backend, edit or delete)
170
-     * and then each capability in the corresponding sub-array that they're missing
171
-     * adds the where conditions onto the query.
172
-     *
173
-     * @var array
174
-     */
175
-    protected $_cap_restrictions = [
176
-        self::caps_read       => [],
177
-        self::caps_read_admin => [],
178
-        self::caps_edit       => [],
179
-        self::caps_delete     => [],
180
-    ];
181
-
182
-    /**
183
-     * Array defining which cap restriction generators to use to create default
184
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
185
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
186
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
187
-     * automatically set this to false (not just null).
188
-     *
189
-     * @var EE_Restriction_Generator_Base[]
190
-     */
191
-    protected $_cap_restriction_generators = [];
192
-
193
-    /**
194
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
195
-     */
196
-    const caps_read       = 'read';
197
-
198
-    const caps_read_admin = 'read_admin';
199
-
200
-    const caps_edit       = 'edit';
201
-
202
-    const caps_delete     = 'delete';
203
-
204
-    /**
205
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
206
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
207
-     * maps to 'read' because when looking for relevant permissions we're going to use
208
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
209
-     *
210
-     * @var array
211
-     */
212
-    protected $_cap_contexts_to_cap_action_map = [
213
-        self::caps_read       => 'read',
214
-        self::caps_read_admin => 'read',
215
-        self::caps_edit       => 'edit',
216
-        self::caps_delete     => 'delete',
217
-    ];
218
-
219
-    /**
220
-     * Timezone
221
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
222
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
223
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
224
-     * EE_Datetime_Field data type will have access to it.
225
-     *
226
-     * @var string
227
-     */
228
-    protected $_timezone;
229
-
230
-
231
-    /**
232
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
233
-     * multisite.
234
-     *
235
-     * @var int
236
-     */
237
-    protected static $_model_query_blog_id;
238
-
239
-    /**
240
-     * A copy of _fields, except the array keys are the model names pointed to by
241
-     * the field
242
-     *
243
-     * @var EE_Model_Field_Base[]
244
-     */
245
-    private $_cache_foreign_key_to_fields = [];
246
-
247
-    /**
248
-     * Cached list of all the fields on the model, indexed by their name
249
-     *
250
-     * @var EE_Model_Field_Base[]
251
-     */
252
-    private $_cached_fields = null;
253
-
254
-    /**
255
-     * Cached list of all the fields on the model, except those that are
256
-     * marked as only pertinent to the database
257
-     *
258
-     * @var EE_Model_Field_Base[]
259
-     */
260
-    private $_cached_fields_non_db_only = null;
261
-
262
-    /**
263
-     * A cached reference to the primary key for quick lookup
264
-     *
265
-     * @var EE_Model_Field_Base
266
-     */
267
-    private $_primary_key_field = null;
268
-
269
-    /**
270
-     * Flag indicating whether this model has a primary key or not
271
-     *
272
-     * @var boolean
273
-     */
274
-    protected $_has_primary_key_field = null;
275
-
276
-    /**
277
-     * array in the format:  [ FK alias => full PK ]
278
-     * where keys are local column name aliases for foreign keys
279
-     * and values are the fully qualified column name for the primary key they represent
280
-     *  ex:
281
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
282
-     *
283
-     * @var array $foreign_key_aliases
284
-     */
285
-    protected $foreign_key_aliases = [];
286
-
287
-    /**
288
-     * Whether or not this model is based off a table in WP core only (CPTs should set
289
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
290
-     * This should be true for models that deal with data that should exist independent of EE.
291
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
292
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
293
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
294
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
295
-     *
296
-     * @var boolean
297
-     */
298
-    protected $_wp_core_model = false;
299
-
300
-    /**
301
-     * @var bool stores whether this model has a password field or not.
302
-     * null until initialized by hasPasswordField()
303
-     */
304
-    protected $has_password_field;
305
-
306
-    /**
307
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
308
-     */
309
-    protected $password_field;
310
-
311
-    /**
312
-     *    List of valid operators that can be used for querying.
313
-     * The keys are all operators we'll accept, the values are the real SQL
314
-     * operators used
315
-     *
316
-     * @var array
317
-     */
318
-    protected $_valid_operators = [
319
-        '='           => '=',
320
-        '<='          => '<=',
321
-        '<'           => '<',
322
-        '>='          => '>=',
323
-        '>'           => '>',
324
-        '!='          => '!=',
325
-        'LIKE'        => 'LIKE',
326
-        'like'        => 'LIKE',
327
-        'NOT_LIKE'    => 'NOT LIKE',
328
-        'not_like'    => 'NOT LIKE',
329
-        'NOT LIKE'    => 'NOT LIKE',
330
-        'not like'    => 'NOT LIKE',
331
-        'IN'          => 'IN',
332
-        'in'          => 'IN',
333
-        'NOT_IN'      => 'NOT IN',
334
-        'not_in'      => 'NOT IN',
335
-        'NOT IN'      => 'NOT IN',
336
-        'not in'      => 'NOT IN',
337
-        'between'     => 'BETWEEN',
338
-        'BETWEEN'     => 'BETWEEN',
339
-        'IS_NOT_NULL' => 'IS NOT NULL',
340
-        'is_not_null' => 'IS NOT NULL',
341
-        'IS NOT NULL' => 'IS NOT NULL',
342
-        'is not null' => 'IS NOT NULL',
343
-        'IS_NULL'     => 'IS NULL',
344
-        'is_null'     => 'IS NULL',
345
-        'IS NULL'     => 'IS NULL',
346
-        'is null'     => 'IS NULL',
347
-        'REGEXP'      => 'REGEXP',
348
-        'regexp'      => 'REGEXP',
349
-        'NOT_REGEXP'  => 'NOT REGEXP',
350
-        'not_regexp'  => 'NOT REGEXP',
351
-        'NOT REGEXP'  => 'NOT REGEXP',
352
-        'not regexp'  => 'NOT REGEXP',
353
-    ];
354
-
355
-    /**
356
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
357
-     *
358
-     * @var array
359
-     */
360
-    protected $_in_style_operators = ['IN', 'NOT IN'];
361
-
362
-    /**
363
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
364
-     * '12-31-2012'"
365
-     *
366
-     * @var array
367
-     */
368
-    protected $_between_style_operators = ['BETWEEN'];
369
-
370
-    /**
371
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
372
-     *
373
-     * @var array
374
-     */
375
-    protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
376
-
377
-    /**
378
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
379
-     * on a join table.
380
-     *
381
-     * @var array
382
-     */
383
-    protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
384
-
385
-    /**
386
-     * Allowed values for $query_params['order'] for ordering in queries
387
-     *
388
-     * @var array
389
-     */
390
-    protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
391
-
392
-    /**
393
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
394
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
395
-     *
396
-     * @var array
397
-     */
398
-    private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
399
-
400
-    /**
401
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
402
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
403
-     *
404
-     * @var array
405
-     */
406
-    private $_allowed_query_params = [
407
-        0,
408
-        'limit',
409
-        'order_by',
410
-        'group_by',
411
-        'having',
412
-        'force_join',
413
-        'order',
414
-        'on_join_limit',
415
-        'default_where_conditions',
416
-        'caps',
417
-        'extra_selects',
418
-        'exclude_protected',
419
-    ];
420
-
421
-    /**
422
-     * All the data types that can be used in $wpdb->prepare statements.
423
-     *
424
-     * @var array
425
-     */
426
-    private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
427
-
428
-    /**
429
-     * @var EE_Registry $EE
430
-     */
431
-    protected $EE = null;
432
-
433
-
434
-    /**
435
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
436
-     *
437
-     * @var int
438
-     */
439
-    protected $_show_next_x_db_queries = 0;
440
-
441
-    /**
442
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
443
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
444
-     * WHERE, GROUP_BY, etc.
445
-     *
446
-     * @var CustomSelects
447
-     */
448
-    protected $_custom_selections = [];
449
-
450
-    /**
451
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
452
-     * caches every model object we've fetched from the DB on this request
453
-     *
454
-     * @var array
455
-     */
456
-    protected $_entity_map;
457
-
458
-    /**
459
-     * @var LoaderInterface
460
-     */
461
-    protected static $loader;
462
-
463
-    /**
464
-     * @var Mirror
465
-     */
466
-    private static $mirror;
467
-
468
-
469
-    /**
470
-     * constant used to show EEM_Base has not yet verified the db on this http request
471
-     */
472
-    const db_verified_none = 0;
473
-
474
-    /**
475
-     * constant used to show EEM_Base has verified the EE core db on this http request,
476
-     * but not the addons' dbs
477
-     */
478
-    const db_verified_core = 1;
479
-
480
-    /**
481
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
482
-     * the EE core db too)
483
-     */
484
-    const db_verified_addons = 2;
485
-
486
-    /**
487
-     * indicates whether an EEM_Base child has already re-verified the DB
488
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
489
-     * looking like EEM_Base::db_verified_*
490
-     *
491
-     * @var int - 0 = none, 1 = core, 2 = addons
492
-     */
493
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
494
-
495
-    /**
496
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
497
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
498
-     *        registrations for non-trashed tickets for non-trashed datetimes)
499
-     */
500
-    const default_where_conditions_all = 'all';
501
-
502
-    /**
503
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
504
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
505
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
506
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
507
-     *        models which share tables with other models, this can return data for the wrong model.
508
-     */
509
-    const default_where_conditions_this_only = 'this_model_only';
510
-
511
-    /**
512
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
513
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
514
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
515
-     */
516
-    const default_where_conditions_others_only = 'other_models_only';
517
-
518
-    /**
519
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
520
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
521
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
522
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
523
-     *        (regardless of whether those events and venues are trashed)
524
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
525
-     *        events.
526
-     */
527
-    const default_where_conditions_minimum_all = 'minimum';
528
-
529
-    /**
530
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
531
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
532
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
533
-     *        not)
534
-     */
535
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
536
-
537
-    /**
538
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
539
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
540
-     *        it's possible it will return table entries for other models. You should use
541
-     *        EEM_Base::default_where_conditions_minimum_all instead.
542
-     */
543
-    const default_where_conditions_none = 'none';
544
-
545
-
546
-    /**
547
-     * About all child constructors:
548
-     * they should define the _tables, _fields and _model_relations arrays.
549
-     * Should ALWAYS be called after child constructor.
550
-     * In order to make the child constructors to be as simple as possible, this parent constructor
551
-     * finalizes constructing all the object's attributes.
552
-     * Generally, rather than requiring a child to code
553
-     * $this->_tables = array(
554
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
555
-     *        ...);
556
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
557
-     * each EE_Table has a function to set the table's alias after the constructor, using
558
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
559
-     * do something similar.
560
-     *
561
-     * @param string|null $timezone
562
-     * @throws EE_Error
563
-     * @throws Exception
564
-     */
565
-    protected function __construct($timezone = '')
566
-    {
567
-        // check that the model has not been loaded too soon
568
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
569
-            throw new EE_Error(
570
-                sprintf(
571
-                    esc_html__(
572
-                        '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.',
573
-                        'event_espresso'
574
-                    ),
575
-                    get_class($this)
576
-                )
577
-            );
578
-        }
579
-        /**
580
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
581
-         */
582
-        if (empty(EEM_Base::$_model_query_blog_id)) {
583
-            EEM_Base::set_model_query_blog_id();
584
-        }
585
-        /**
586
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
587
-         * just use EE_Register_Model_Extension
588
-         *
589
-         * @var EE_Table_Base[] $_tables
590
-         */
591
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
592
-        foreach ($this->_tables as $table_alias => $table_obj) {
593
-            /** @var $table_obj EE_Table_Base */
594
-            $table_obj->_construct_finalize_with_alias($table_alias);
595
-            if ($table_obj instanceof EE_Secondary_Table) {
596
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
597
-            }
598
-        }
599
-        /**
600
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
601
-         * EE_Register_Model_Extension
602
-         *
603
-         * @param EE_Model_Field_Base[] $_fields
604
-         */
605
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
606
-        $this->_invalidate_field_caches();
607
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
608
-            if (! array_key_exists($table_alias, $this->_tables)) {
609
-                throw new EE_Error(
610
-                    sprintf(
611
-                        esc_html__(
612
-                            "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
613
-                            'event_espresso'
614
-                        ),
615
-                        $table_alias,
616
-                        implode(",", $this->_fields)
617
-                    )
618
-                );
619
-            }
620
-            foreach ($fields_for_table as $field_name => $field_obj) {
621
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
622
-                // primary key field base has a slightly different _construct_finalize
623
-                /** @var $field_obj EE_Model_Field_Base */
624
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
625
-            }
626
-        }
627
-        // everything is related to Extra_Meta
628
-        if (get_class($this) !== 'EEM_Extra_Meta') {
629
-            // make extra meta related to everything, but don't block deleting things just
630
-            // because they have related extra meta info. For now just orphan those extra meta
631
-            // in the future we should automatically delete them
632
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
633
-        }
634
-        // and change logs
635
-        if (get_class($this) !== 'EEM_Change_Log') {
636
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
637
-        }
638
-        /**
639
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
640
-         * EE_Register_Model_Extension
641
-         *
642
-         * @param EE_Model_Relation_Base[] $_model_relations
643
-         */
644
-        $this->_model_relations = (array) apply_filters(
645
-            'FHEE__' . get_class($this) . '__construct__model_relations',
646
-            $this->_model_relations
647
-        );
648
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
649
-            /** @var $relation_obj EE_Model_Relation_Base */
650
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
651
-        }
652
-        foreach ($this->_indexes as $index_name => $index_obj) {
653
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
654
-        }
655
-        $this->set_timezone($timezone);
656
-        // finalize default where condition strategy, or set default
657
-        if (! $this->_default_where_conditions_strategy) {
658
-            // nothing was set during child constructor, so set default
659
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
660
-        }
661
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
662
-        if (! $this->_minimum_where_conditions_strategy) {
663
-            // nothing was set during child constructor, so set default
664
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
665
-        }
666
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
667
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
668
-        // to indicate to NOT set it, set it to the logical default
669
-        if ($this->_caps_slug === null) {
670
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
671
-        }
672
-        // initialize the standard cap restriction generators if none were specified by the child constructor
673
-        if (is_array($this->_cap_restriction_generators)) {
674
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
675
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
676
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
677
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
678
-                        new EE_Restriction_Generator_Protected(),
679
-                        $cap_context,
680
-                        $this
681
-                    );
682
-                }
683
-            }
684
-        }
685
-        // if there are cap restriction generators, use them to make the default cap restrictions
686
-        if (is_array($this->_cap_restriction_generators)) {
687
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
688
-                if (! $generator_object) {
689
-                    continue;
690
-                }
691
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
692
-                    throw new EE_Error(
693
-                        sprintf(
694
-                            esc_html__(
695
-                                '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.',
696
-                                'event_espresso'
697
-                            ),
698
-                            $context,
699
-                            $this->get_this_model_name()
700
-                        )
701
-                    );
702
-                }
703
-                $action = $this->cap_action_for_context($context);
704
-                if (! $generator_object->construction_finalized()) {
705
-                    $generator_object->_construct_finalize($this, $action);
706
-                }
707
-            }
708
-        }
709
-        do_action('AHEE__' . get_class($this) . '__construct__end');
710
-    }
711
-
712
-
713
-    /**
714
-     * @return LoaderInterface
715
-     * @throws InvalidArgumentException
716
-     * @throws InvalidDataTypeException
717
-     * @throws InvalidInterfaceException
718
-     */
719
-    protected static function getLoader(): LoaderInterface
720
-    {
721
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
722
-            EEM_Base::$loader = LoaderFactory::getLoader();
723
-        }
724
-        return EEM_Base::$loader;
725
-    }
726
-
727
-
728
-    /**
729
-     * @return Mirror
730
-     * @since   5.0.0.p
731
-     */
732
-    private static function getMirror(): Mirror
733
-    {
734
-        if (! EEM_Base::$mirror instanceof Mirror) {
735
-            EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
736
-        }
737
-        return EEM_Base::$mirror;
738
-    }
739
-
740
-
741
-    /**
742
-     * @param string $model_class_Name
743
-     * @param string $timezone
744
-     * @return array
745
-     * @throws ReflectionException
746
-     * @since   5.0.0.p
747
-     */
748
-    private static function getModelArguments(string $model_class_Name, string $timezone): array
749
-    {
750
-        $arguments = [$timezone];
751
-        $params    = EEM_Base::getMirror()->getParameters($model_class_Name);
752
-        if (count($params) > 1) {
753
-            if ($params[1]->getName() === 'model_field_factory') {
754
-                $arguments = [
755
-                    $timezone,
756
-                    EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
757
-                ];
758
-            } elseif ($model_class_Name === 'EEM_Form_Section') {
759
-                $arguments = [
760
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
761
-                    $timezone,
762
-                ];
763
-            } elseif ($model_class_Name === 'EEM_Form_Element') {
764
-                $arguments = [
765
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
766
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
767
-                    $timezone,
768
-                ];
769
-            }
770
-        }
771
-        return $arguments;
772
-    }
773
-
774
-
775
-    /**
776
-     * This function is a singleton method used to instantiate the Espresso_model object
777
-     *
778
-     * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
779
-     *                                (and any incoming timezone data that gets saved).
780
-     *                                Note this just sends the timezone info to the date time model field objects.
781
-     *                                Default is NULL
782
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
783
-     * @return static (as in the concrete child class)
784
-     * @throws EE_Error
785
-     * @throws ReflectionException
786
-     */
787
-    public static function instance($timezone = '')
788
-    {
789
-        // check if instance of Espresso_model already exists
790
-        if (! static::$_instance instanceof static) {
791
-            $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
792
-            $model     = new static(...$arguments);
793
-            EEM_Base::getLoader()->share(static::class, $model, $arguments);
794
-            static::$_instance = $model;
795
-        }
796
-        // we might have a timezone set, let set_timezone decide what to do with it
797
-        if ($timezone) {
798
-            static::$_instance->set_timezone($timezone);
799
-        }
800
-        // Espresso_model object
801
-        return static::$_instance;
802
-    }
803
-
804
-
805
-    /**
806
-     * resets the model and returns it
807
-     *
808
-     * @param string|null $timezone
809
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
810
-     * all its properties reset; if it wasn't instantiated, returns null)
811
-     * @throws EE_Error
812
-     * @throws ReflectionException
813
-     * @throws InvalidArgumentException
814
-     * @throws InvalidDataTypeException
815
-     * @throws InvalidInterfaceException
816
-     */
817
-    public static function reset($timezone = '')
818
-    {
819
-        if (! static::$_instance instanceof EEM_Base) {
820
-            return null;
821
-        }
822
-        // Let's NOT swap out the current instance for a new one
823
-        // because if someone has a reference to it, we can't remove their reference.
824
-        // It's best to keep using the same reference but change the original object instead,
825
-        // so reset all its properties to their original values as defined in the class.
826
-        $static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
827
-        foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
828
-            // don't set instance to null like it was originally,
829
-            // but it's static anyways, and we're ignoring static properties (for now at least)
830
-            if (! isset($static_properties[ $property ])) {
831
-                static::$_instance->{$property} = $value;
832
-            }
833
-        }
834
-        // and then directly call its constructor again, like we would if we were creating a new one
835
-        $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
836
-        static::$_instance->__construct(...$arguments);
837
-        return self::instance();
838
-    }
839
-
840
-
841
-    /**
842
-     * Used to set the $_model_query_blog_id static property.
843
-     *
844
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
845
-     *                      value for get_current_blog_id() will be used.
846
-     */
847
-    public static function set_model_query_blog_id($blog_id = 0)
848
-    {
849
-        EEM_Base::$_model_query_blog_id = $blog_id > 0
850
-            ? (int) $blog_id
851
-            : get_current_blog_id();
852
-    }
853
-
854
-
855
-    /**
856
-     * Returns whatever is set as the internal $model_query_blog_id.
857
-     *
858
-     * @return int
859
-     */
860
-    public static function get_model_query_blog_id()
861
-    {
862
-        return EEM_Base::$_model_query_blog_id;
863
-    }
864
-
865
-
866
-    /**
867
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
868
-     *
869
-     * @param boolean $translated return localized strings or JUST the array.
870
-     * @return array
871
-     * @throws EE_Error
872
-     * @throws InvalidArgumentException
873
-     * @throws InvalidDataTypeException
874
-     * @throws InvalidInterfaceException
875
-     * @throws ReflectionException
876
-     */
877
-    public function status_array($translated = false)
878
-    {
879
-        if (! array_key_exists('Status', $this->_model_relations)) {
880
-            return [];
881
-        }
882
-        $model_name   = $this->get_this_model_name();
883
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
884
-        $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
885
-        $status_array = [];
886
-        foreach ($stati as $status) {
887
-            $status_array[ $status->ID() ] = $status->get('STS_code');
888
-        }
889
-        return $translated
890
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
891
-            : $status_array;
892
-    }
893
-
894
-
895
-    /**
896
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
897
-     *
898
-     * @param array $query_params             @see
899
-     *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
900
-     *                                        or if you have the development copy of EE you can view this at the path:
901
-     *                                        /docs/G--Model-System/model-query-params.md
902
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
903
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
904
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
905
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
906
-     *                                        EEM_Transaction::instance()->get_all( array( array(
907
-     *                                        'OR'=>array(
908
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
909
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
910
-     *                                        )
911
-     *                                        ),
912
-     *                                        'limit'=>10,
913
-     *                                        'group_by'=>'TXN_ID'
914
-     *                                        ));
915
-     *                                        get all the answers to the question titled "shirt size" for event with id
916
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
917
-     *                                        'Question.QST_display_text'=>'shirt size',
918
-     *                                        'Registration.Event.EVT_ID'=>12
919
-     *                                        ),
920
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
921
-     *                                        ));
922
-     * @throws EE_Error
923
-     * @throws ReflectionException
924
-     */
925
-    public function get_all($query_params = [])
926
-    {
927
-        if (
928
-            isset($query_params['limit'])
929
-            && ! isset($query_params['group_by'])
930
-        ) {
931
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
932
-        }
933
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
934
-    }
935
-
936
-
937
-    /**
938
-     * Modifies the query parameters so we only get back model objects
939
-     * that "belong" to the current user
940
-     *
941
-     * @param array $query_params @see
942
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
943
-     * @return array @see
944
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
945
-     * @throws ReflectionException
946
-     * @throws ReflectionException
947
-     */
948
-    public function alter_query_params_to_only_include_mine($query_params = [])
949
-    {
950
-        $wp_user_field_name = $this->wp_user_field_name();
951
-        if ($wp_user_field_name) {
952
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
953
-        }
954
-        return $query_params;
955
-    }
956
-
957
-
958
-    /**
959
-     * Returns the name of the field's name that points to the WP_User table
960
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
-     * foreign key to the WP_User table)
962
-     *
963
-     * @return string|boolean string on success, boolean false when there is no
964
-     * foreign key to the WP_User table
965
-     * @throws ReflectionException
966
-     * @throws ReflectionException
967
-     */
968
-    public function wp_user_field_name()
969
-    {
970
-        try {
971
-            if (! empty($this->_model_chain_to_wp_user)) {
972
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
973
-                $last_model_name              = end($models_to_follow_to_wp_users);
974
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
975
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
976
-            } else {
977
-                $model_with_fk_to_wp_users = $this;
978
-                $model_chain_to_wp_user    = '';
979
-            }
980
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
981
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
982
-        } catch (EE_Error $e) {
983
-            return false;
984
-        }
985
-    }
986
-
987
-
988
-    /**
989
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
990
-     * (or transiently-related model) has a foreign key to the wp_users table;
991
-     * useful for finding if model objects of this type are 'owned' by the current user.
992
-     * This is an empty string when the foreign key is on this model and when it isn't,
993
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
994
-     * (or transiently-related model)
995
-     *
996
-     * @return string
997
-     */
998
-    public function model_chain_to_wp_user()
999
-    {
1000
-        return $this->_model_chain_to_wp_user;
1001
-    }
1002
-
1003
-
1004
-    /**
1005
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
-     * like how registrations don't have a foreign key to wp_users, but the
1007
-     * events they are for are), or is unrelated to wp users.
1008
-     * generally available
1009
-     *
1010
-     * @return boolean
1011
-     */
1012
-    public function is_owned()
1013
-    {
1014
-        if ($this->model_chain_to_wp_user()) {
1015
-            return true;
1016
-        }
1017
-        try {
1018
-            $this->get_foreign_key_to('WP_User');
1019
-            return true;
1020
-        } catch (EE_Error $e) {
1021
-            return false;
1022
-        }
1023
-    }
1024
-
1025
-
1026
-    /**
1027
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1028
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1029
-     * the model)
1030
-     *
1031
-     * @param array  $query_params      @see
1032
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1033
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1034
-     * @param mixed  $columns_to_select What columns to select. By default, we select all columns specified by the
1035
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1036
-     *                                  override this and set the select to "*", or a specific column name, like
1037
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1038
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1039
-     *                                  the aliases used to refer to this selection, and values are to be
1040
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1041
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1042
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1043
-     * @throws EE_Error
1044
-     * @throws InvalidArgumentException
1045
-     * @throws ReflectionException
1046
-     */
1047
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1048
-    {
1049
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1050
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1051
-        $select_expressions       = $columns_to_select === null
1052
-            ? $this->_construct_default_select_sql($model_query_info)
1053
-            : '';
1054
-        if ($this->_custom_selections instanceof CustomSelects) {
1055
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1056
-            $select_expressions .= $select_expressions
1057
-                ? ', ' . $custom_expressions
1058
-                : $custom_expressions;
1059
-        }
1060
-
1061
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1062
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1063
-    }
1064
-
1065
-
1066
-    /**
1067
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1068
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1069
-     * method of including extra select information.
1070
-     *
1071
-     * @param array             $query_params
1072
-     * @param null|array|string $columns_to_select
1073
-     * @return null|CustomSelects
1074
-     * @throws InvalidArgumentException
1075
-     */
1076
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1077
-    {
1078
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1079
-            return null;
1080
-        }
1081
-        $selects = $query_params['extra_selects'] ?? $columns_to_select;
1082
-        $selects = is_string($selects)
1083
-            ? explode(',', $selects)
1084
-            : $selects;
1085
-        return new CustomSelects($selects);
1086
-    }
1087
-
1088
-
1089
-    /**
1090
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1091
-     * but you can use the model query params to more easily
1092
-     * take care of joins, field preparation etc.
1093
-     *
1094
-     * @param array  $query_params      @see
1095
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1096
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1097
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1098
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1099
-     *                                  override this and set the select to "*", or a specific column name, like
1100
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1101
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1102
-     *                                  the aliases used to refer to this selection, and values are to be
1103
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1104
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1105
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1106
-     * @throws EE_Error
1107
-     * @throws ReflectionException
1108
-     */
1109
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1110
-    {
1111
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1112
-    }
1113
-
1114
-
1115
-    /**
1116
-     * For creating a custom select statement
1117
-     *
1118
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1119
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1120
-     *                                 SQL, and 1=>is the datatype
1121
-     * @return string
1122
-     * @throws EE_Error
1123
-     */
1124
-    private function _construct_select_from_input($columns_to_select)
1125
-    {
1126
-        if (is_array($columns_to_select)) {
1127
-            $select_sql_array = [];
1128
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1129
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1130
-                    throw new EE_Error(
1131
-                        sprintf(
1132
-                            esc_html__(
1133
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1134
-                                'event_espresso'
1135
-                            ),
1136
-                            $selection_and_datatype,
1137
-                            $alias
1138
-                        )
1139
-                    );
1140
-                }
1141
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1142
-                    throw new EE_Error(
1143
-                        sprintf(
1144
-                            esc_html__(
1145
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1146
-                                'event_espresso'
1147
-                            ),
1148
-                            $selection_and_datatype[1],
1149
-                            $selection_and_datatype[0],
1150
-                            $alias,
1151
-                            implode(', ', $this->_valid_wpdb_data_types)
1152
-                        )
1153
-                    );
1154
-                }
1155
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1156
-            }
1157
-            $columns_to_select_string = implode(', ', $select_sql_array);
1158
-        } else {
1159
-            $columns_to_select_string = $columns_to_select;
1160
-        }
1161
-        return $columns_to_select_string;
1162
-    }
1163
-
1164
-
1165
-    /**
1166
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1167
-     *
1168
-     * @return string
1169
-     * @throws EE_Error
1170
-     */
1171
-    public function primary_key_name()
1172
-    {
1173
-        return $this->get_primary_key_field()->get_name();
1174
-    }
1175
-
1176
-
1177
-    /**
1178
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1179
-     * If there is no primary key on this model, $id is treated as primary key string
1180
-     *
1181
-     * @param mixed $id int or string, depending on the type of the model's primary key
1182
-     * @return EE_Base_Class|mixed|null
1183
-     * @throws EE_Error
1184
-     * @throws ReflectionException
1185
-     */
1186
-    public function get_one_by_ID($id)
1187
-    {
1188
-        if ($this->get_from_entity_map($id)) {
1189
-            return $this->get_from_entity_map($id);
1190
-        }
1191
-        $model_object = $this->get_one(
1192
-            $this->alter_query_params_to_restrict_by_ID(
1193
-                $id,
1194
-                ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1195
-            )
1196
-        );
1197
-        $className    = $this->_get_class_name();
1198
-        if ($model_object instanceof $className) {
1199
-            // make sure valid objects get added to the entity map
1200
-            // so that the next call to this method doesn't trigger another trip to the db
1201
-            $this->add_to_entity_map($model_object);
1202
-        }
1203
-        return $model_object;
1204
-    }
1205
-
1206
-
1207
-    /**
1208
-     * Alters query parameters to only get items with this ID are returned.
1209
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1210
-     * or could just be a simple primary key ID
1211
-     *
1212
-     * @param int   $id
1213
-     * @param array $query_params
1214
-     * @return array of normal query params, @see
1215
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1216
-     * @throws EE_Error
1217
-     */
1218
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1219
-    {
1220
-        if (! isset($query_params[0])) {
1221
-            $query_params[0] = [];
1222
-        }
1223
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1224
-        if ($conditions_from_id === null) {
1225
-            $query_params[0][ $this->primary_key_name() ] = $id;
1226
-        } else {
1227
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1228
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1229
-        }
1230
-        return $query_params;
1231
-    }
1232
-
1233
-
1234
-    /**
1235
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1236
-     * array. If no item is found, null is returned.
1237
-     *
1238
-     * @param array $query_params like EEM_Base's $query_params variable.
1239
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1240
-     * @throws EE_Error
1241
-     * @throws ReflectionException
1242
-     */
1243
-    public function get_one($query_params = [])
1244
-    {
1245
-        if (! is_array($query_params)) {
1246
-            EE_Error::doing_it_wrong(
1247
-                'EEM_Base::get_one',
1248
-                sprintf(
1249
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1250
-                    gettype($query_params)
1251
-                ),
1252
-                '4.6.0'
1253
-            );
1254
-            $query_params = [];
1255
-        }
1256
-        $query_params['limit'] = 1;
1257
-        $items                 = $this->get_all($query_params);
1258
-        if (empty($items)) {
1259
-            return null;
1260
-        }
1261
-        return array_shift($items);
1262
-    }
1263
-
1264
-
1265
-    /**
1266
-     * Returns the next x number of items in sequence from the given value as
1267
-     * found in the database matching the given query conditions.
1268
-     *
1269
-     * @param mixed $current_field_value    Value used for the reference point.
1270
-     * @param null  $field_to_order_by      What field is used for the
1271
-     *                                      reference point.
1272
-     * @param int   $limit                  How many to return.
1273
-     * @param array $query_params           Extra conditions on the query.
1274
-     * @param null  $columns_to_select      If left null, then an array of
1275
-     *                                      EE_Base_Class objects is returned,
1276
-     *                                      otherwise you can indicate just the
1277
-     *                                      columns you want returned.
1278
-     * @return EE_Base_Class[]|array
1279
-     * @throws EE_Error
1280
-     * @throws ReflectionException
1281
-     */
1282
-    public function next_x(
1283
-        $current_field_value,
1284
-        $field_to_order_by = null,
1285
-        $limit = 1,
1286
-        $query_params = [],
1287
-        $columns_to_select = null
1288
-    ) {
1289
-        return $this->_get_consecutive(
1290
-            $current_field_value,
1291
-            '>',
1292
-            $field_to_order_by,
1293
-            $limit,
1294
-            $query_params,
1295
-            $columns_to_select
1296
-        );
1297
-    }
1298
-
1299
-
1300
-    /**
1301
-     * Returns the previous x number of items in sequence from the given value
1302
-     * as found in the database matching the given query conditions.
1303
-     *
1304
-     * @param mixed $current_field_value    Value used for the reference point.
1305
-     * @param null  $field_to_order_by      What field is used for the
1306
-     *                                      reference point.
1307
-     * @param int   $limit                  How many to return.
1308
-     * @param array $query_params           Extra conditions on the query.
1309
-     * @param null  $columns_to_select      If left null, then an array of
1310
-     *                                      EE_Base_Class objects is returned,
1311
-     *                                      otherwise you can indicate just the
1312
-     *                                      columns you want returned.
1313
-     * @return EE_Base_Class[]|array
1314
-     * @throws EE_Error
1315
-     * @throws ReflectionException
1316
-     */
1317
-    public function previous_x(
1318
-        $current_field_value,
1319
-        $field_to_order_by = null,
1320
-        $limit = 1,
1321
-        $query_params = [],
1322
-        $columns_to_select = null
1323
-    ) {
1324
-        return $this->_get_consecutive(
1325
-            $current_field_value,
1326
-            '<',
1327
-            $field_to_order_by,
1328
-            $limit,
1329
-            $query_params,
1330
-            $columns_to_select
1331
-        );
1332
-    }
1333
-
1334
-
1335
-    /**
1336
-     * Returns the next item in sequence from the given value as found in the
1337
-     * database matching the given query conditions.
1338
-     *
1339
-     * @param mixed $current_field_value    Value used for the reference point.
1340
-     * @param null  $field_to_order_by      What field is used for the
1341
-     *                                      reference point.
1342
-     * @param array $query_params           Extra conditions on the query.
1343
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1344
-     *                                      object is returned, otherwise you
1345
-     *                                      can indicate just the columns you
1346
-     *                                      want and a single array indexed by
1347
-     *                                      the columns will be returned.
1348
-     * @return EE_Base_Class|null|array()
1349
-     * @throws EE_Error
1350
-     * @throws ReflectionException
1351
-     */
1352
-    public function next(
1353
-        $current_field_value,
1354
-        $field_to_order_by = null,
1355
-        $query_params = [],
1356
-        $columns_to_select = null
1357
-    ) {
1358
-        $results = $this->_get_consecutive(
1359
-            $current_field_value,
1360
-            '>',
1361
-            $field_to_order_by,
1362
-            1,
1363
-            $query_params,
1364
-            $columns_to_select
1365
-        );
1366
-        return empty($results)
1367
-            ? null
1368
-            : reset($results);
1369
-    }
1370
-
1371
-
1372
-    /**
1373
-     * Returns the previous item in sequence from the given value as found in
1374
-     * the database matching the given query conditions.
1375
-     *
1376
-     * @param mixed $current_field_value    Value used for the reference point.
1377
-     * @param null  $field_to_order_by      What field is used for the
1378
-     *                                      reference point.
1379
-     * @param array $query_params           Extra conditions on the query.
1380
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1381
-     *                                      object is returned, otherwise you
1382
-     *                                      can indicate just the columns you
1383
-     *                                      want and a single array indexed by
1384
-     *                                      the columns will be returned.
1385
-     * @return EE_Base_Class|null|array()
1386
-     * @throws EE_Error
1387
-     * @throws ReflectionException
1388
-     */
1389
-    public function previous(
1390
-        $current_field_value,
1391
-        $field_to_order_by = null,
1392
-        $query_params = [],
1393
-        $columns_to_select = null
1394
-    ) {
1395
-        $results = $this->_get_consecutive(
1396
-            $current_field_value,
1397
-            '<',
1398
-            $field_to_order_by,
1399
-            1,
1400
-            $query_params,
1401
-            $columns_to_select
1402
-        );
1403
-        return empty($results)
1404
-            ? null
1405
-            : reset($results);
1406
-    }
1407
-
1408
-
1409
-    /**
1410
-     * Returns the a consecutive number of items in sequence from the given
1411
-     * value as found in the database matching the given query conditions.
1412
-     *
1413
-     * @param mixed  $current_field_value   Value used for the reference point.
1414
-     * @param string $operand               What operand is used for the sequence.
1415
-     * @param string $field_to_order_by     What field is used for the reference point.
1416
-     * @param int    $limit                 How many to return.
1417
-     * @param array  $query_params          Extra conditions on the query.
1418
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1419
-     *                                      otherwise you can indicate just the columns you want returned.
1420
-     * @return EE_Base_Class[]|array
1421
-     * @throws EE_Error
1422
-     * @throws ReflectionException
1423
-     */
1424
-    protected function _get_consecutive(
1425
-        $current_field_value,
1426
-        $operand = '>',
1427
-        $field_to_order_by = null,
1428
-        $limit = 1,
1429
-        $query_params = [],
1430
-        $columns_to_select = null
1431
-    ) {
1432
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1433
-        if (empty($field_to_order_by)) {
1434
-            if ($this->has_primary_key_field()) {
1435
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1436
-            } else {
1437
-                if (WP_DEBUG) {
1438
-                    throw new EE_Error(
1439
-                        esc_html__(
1440
-                            '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).',
1441
-                            'event_espresso'
1442
-                        )
1443
-                    );
1444
-                }
1445
-                EE_Error::add_error(
1446
-                    esc_html__('There was an error with the query.', 'event_espresso'),
1447
-                    __FILE__,
1448
-                    __FUNCTION__,
1449
-                    __LINE__
1450
-                );
1451
-                return [];
1452
-            }
1453
-        }
1454
-        if (! is_array($query_params)) {
1455
-            EE_Error::doing_it_wrong(
1456
-                'EEM_Base::_get_consecutive',
1457
-                sprintf(
1458
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1459
-                    gettype($query_params)
1460
-                ),
1461
-                '4.6.0'
1462
-            );
1463
-            $query_params = [];
1464
-        }
1465
-        // let's add the where query param for consecutive look up.
1466
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1467
-        $query_params['limit']                 = $limit;
1468
-        // set direction
1469
-        $incoming_orderby         = isset($query_params['order_by'])
1470
-            ? (array) $query_params['order_by']
1471
-            : [];
1472
-        $query_params['order_by'] = $operand === '>'
1473
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1474
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1475
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1476
-        if (empty($columns_to_select)) {
1477
-            return $this->get_all($query_params);
1478
-        }
1479
-        // getting just the fields
1480
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1481
-    }
1482
-
1483
-
1484
-    /**
1485
-     * This sets the _timezone property after model object has been instantiated.
1486
-     *
1487
-     * @param string|null $timezone valid PHP DateTimeZone timezone string
1488
-     * @throws Exception
1489
-     */
1490
-    public function set_timezone(?string $timezone = '')
1491
-    {
1492
-        if (! $timezone) {
1493
-            return;
1494
-        }
1495
-        $this->_timezone = $timezone;
1496
-        // note we need to loop through relations and set the timezone on those objects as well.
1497
-        foreach ($this->_model_relations as $relation) {
1498
-            $relation->set_timezone($timezone);
1499
-        }
1500
-        // and finally we do the same for any datetime fields
1501
-        foreach ($this->_fields as $field) {
1502
-            if ($field instanceof EE_Datetime_Field) {
1503
-                $field->set_timezone($timezone);
1504
-            }
1505
-        }
1506
-    }
1507
-
1508
-
1509
-    /**
1510
-     * This just returns whatever is set for the current timezone.
1511
-     *
1512
-     * @access public
1513
-     * @return string
1514
-     * @throws Exception
1515
-     */
1516
-    public function get_timezone()
1517
-    {
1518
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1519
-        if (empty($this->_timezone)) {
1520
-            foreach ($this->_fields as $field) {
1521
-                if ($field instanceof EE_Datetime_Field) {
1522
-                    $this->set_timezone($field->get_timezone());
1523
-                    break;
1524
-                }
1525
-            }
1526
-        }
1527
-        // if timezone STILL empty then return the default timezone for the site.
1528
-        if (empty($this->_timezone)) {
1529
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1530
-        }
1531
-        return $this->_timezone;
1532
-    }
1533
-
1534
-
1535
-    /**
1536
-     * This returns the date formats set for the given field name and also ensures that
1537
-     * $this->_timezone property is set correctly.
1538
-     *
1539
-     * @param string $field_name The name of the field the formats are being retrieved for.
1540
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1541
-     * @return array formats in an array with the date format first, and the time format last.
1542
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1543
-     * @since 4.6.x
1544
-     */
1545
-    public function get_formats_for($field_name, $pretty = false)
1546
-    {
1547
-        $field_settings = $this->field_settings_for($field_name);
1548
-        // if not a valid EE_Datetime_Field then throw error
1549
-        if (! $field_settings instanceof EE_Datetime_Field) {
1550
-            throw new EE_Error(
1551
-                sprintf(
1552
-                    esc_html__(
1553
-                        '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.',
1554
-                        'event_espresso'
1555
-                    ),
1556
-                    $field_name
1557
-                )
1558
-            );
1559
-        }
1560
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1561
-        // the field.
1562
-        $this->_timezone = $field_settings->get_timezone();
1563
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1564
-    }
1565
-
1566
-
1567
-    /**
1568
-     * This returns the current time in a format setup for a query on this model.
1569
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1570
-     * it will return:
1571
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1572
-     *  NOW
1573
-     *  - or a unix timestamp (equivalent to time())
1574
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1575
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1576
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1577
-     *
1578
-     * @param string $field_name       The field the current time is needed for.
1579
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1580
-     *                                 formatted string matching the set format for the field in the set timezone will
1581
-     *                                 be returned.
1582
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1583
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1584
-     *                                 exception is triggered.
1585
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1586
-     * @throws Exception
1587
-     * @since 4.6.x
1588
-     */
1589
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1590
-    {
1591
-        $formats  = $this->get_formats_for($field_name);
1592
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1593
-        if ($timestamp) {
1594
-            return $DateTime->format('U');
1595
-        }
1596
-        // not returning timestamp, so return formatted string in timezone.
1597
-        switch ($what) {
1598
-            case 'time':
1599
-                return $DateTime->format($formats[1]);
1600
-            case 'date':
1601
-                return $DateTime->format($formats[0]);
1602
-            default:
1603
-                return $DateTime->format(implode(' ', $formats));
1604
-        }
1605
-    }
1606
-
1607
-
1608
-    /**
1609
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1610
-     * for the model are.  Returns a DateTime object.
1611
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1612
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1613
-     * ignored.
1614
-     *
1615
-     * @param string      $field_name      The field being setup.
1616
-     * @param string      $timestring      The date time string being used.
1617
-     * @param string      $incoming_format The format for the time string.
1618
-     * @param string|null $timezone        By default, it is assumed the incoming time string is in timezone for
1619
-     *                                     the blog.  If this is not the case, then it can be specified here.  If
1620
-     *                                     incoming format is
1621
-     *                                     'U', this is ignored.
1622
-     * @return DateTime
1623
-     * @throws EE_Error
1624
-     * @throws Exception
1625
-     */
1626
-    public function convert_datetime_for_query(
1627
-        string $field_name,
1628
-        string $timestring,
1629
-        string $incoming_format,
1630
-        ?string $timezone = ''
1631
-    ) {
1632
-        // just using this to ensure the timezone is set correctly internally
1633
-        $this->get_formats_for($field_name);
1634
-        // load EEH_DTT_Helper
1635
-        $set_timezone     = empty($timezone)
1636
-            ? EEH_DTT_Helper::get_timezone()
1637
-            : $timezone;
1638
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1639
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1640
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1641
-    }
1642
-
1643
-
1644
-    /**
1645
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1646
-     *
1647
-     * @return EE_Table_Base[]
1648
-     */
1649
-    public function get_tables()
1650
-    {
1651
-        return $this->_tables;
1652
-    }
1653
-
1654
-
1655
-    /**
1656
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1657
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1658
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1659
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1660
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1661
-     * model object with EVT_ID = 1
1662
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1663
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1664
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1665
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1666
-     * are not specified)
1667
-     *
1668
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1669
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1670
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1671
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1672
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1673
-     *                                         ID=34, we'd use this method as follows:
1674
-     *                                         EEM_Transaction::instance()->update(
1675
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1676
-     *                                         array(array('TXN_ID'=>34)));
1677
-     * @param array   $query_params            @see
1678
-     *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1679
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1680
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1681
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1682
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1683
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1684
-     *                                         TRUE, it is assumed that you've already called
1685
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1686
-     *                                         malicious javascript. However, if
1687
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1688
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1689
-     *                                         and every other field, before insertion. We provide this parameter
1690
-     *                                         because model objects perform their prepare_for_set function on all
1691
-     *                                         their values, and so don't need to be called again (and in many cases,
1692
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1693
-     *                                         prepare_for_set method...)
1694
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1695
-     *                                         in this model's entity map according to $fields_n_values that match
1696
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1697
-     *                                         by setting this to FALSE, but be aware that model objects being used
1698
-     *                                         could get out-of-sync with the database
1699
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1700
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1701
-     *                                         bad)
1702
-     * @throws EE_Error
1703
-     * @throws ReflectionException
1704
-     */
1705
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1706
-    {
1707
-        if (! is_array($query_params)) {
1708
-            EE_Error::doing_it_wrong(
1709
-                'EEM_Base::update',
1710
-                sprintf(
1711
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1712
-                    gettype($query_params)
1713
-                ),
1714
-                '4.6.0'
1715
-            );
1716
-            $query_params = [];
1717
-        }
1718
-        /**
1719
-         * Action called before a model update call has been made.
1720
-         *
1721
-         * @param EEM_Base $model
1722
-         * @param array    $fields_n_values the updated fields and their new values
1723
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1724
-         */
1725
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1726
-        /**
1727
-         * Filters the fields about to be updated given the query parameters. You can provide the
1728
-         * $query_params to $this->get_all() to find exactly which records will be updated
1729
-         *
1730
-         * @param array    $fields_n_values fields and their new values
1731
-         * @param EEM_Base $model           the model being queried
1732
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1733
-         */
1734
-        $fields_n_values = (array) apply_filters(
1735
-            'FHEE__EEM_Base__update__fields_n_values',
1736
-            $fields_n_values,
1737
-            $this,
1738
-            $query_params
1739
-        );
1740
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1741
-        // to do that, for each table, verify that it's PK isn't null.
1742
-        $tables = $this->get_tables();
1743
-        // 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
1744
-        // NOTE: we should make this code more efficient by NOT querying twice
1745
-        // before the real update, but that needs to first go through ALPHA testing
1746
-        // as it's dangerous. says Mike August 8 2014
1747
-        // we want to make sure the default_where strategy is ignored
1748
-        $this->_ignore_where_strategy = true;
1749
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1750
-        foreach ($wpdb_select_results as $wpdb_result) {
1751
-            // type cast stdClass as array
1752
-            $wpdb_result = (array) $wpdb_result;
1753
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1754
-            if ($this->has_primary_key_field()) {
1755
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1756
-            } else {
1757
-                // 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)
1758
-                $main_table_pk_value = null;
1759
-            }
1760
-            // 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
1761
-            // 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
1762
-            if (count($tables) > 1) {
1763
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1764
-                // in that table, and so we'll want to insert one
1765
-                foreach ($tables as $table_obj) {
1766
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1767
-                    // if there is no private key for this table on the results, it means there's no entry
1768
-                    // in this table, right? so insert a row in the current table, using any fields available
1769
-                    if (
1770
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1771
-                           && $wpdb_result[ $this_table_pk_column ])
1772
-                    ) {
1773
-                        $success = $this->_insert_into_specific_table(
1774
-                            $table_obj,
1775
-                            $fields_n_values,
1776
-                            $main_table_pk_value
1777
-                        );
1778
-                        // if we died here, report the error
1779
-                        if (! $success) {
1780
-                            return false;
1781
-                        }
1782
-                    }
1783
-                }
1784
-            }
1785
-            //              //and now check that if we have cached any models by that ID on the model, that
1786
-            //              //they also get updated properly
1787
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1788
-            //              if( $model_object ){
1789
-            //                  foreach( $fields_n_values as $field => $value ){
1790
-            //                      $model_object->set($field, $value);
1791
-            // let's make sure default_where strategy is followed now
1792
-            $this->_ignore_where_strategy = false;
1793
-        }
1794
-        // if we want to keep model objects in sync, AND
1795
-        // if this wasn't called from a model object (to update itself)
1796
-        // then we want to make sure we keep all the existing
1797
-        // model objects in sync with the db
1798
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1799
-            if ($this->has_primary_key_field()) {
1800
-                $model_objs_affected_ids = $this->get_col($query_params);
1801
-            } else {
1802
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1803
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1804
-                $model_objs_affected_ids     = [];
1805
-                foreach ($models_affected_key_columns as $row) {
1806
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1807
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1808
-                }
1809
-            }
1810
-            if (! $model_objs_affected_ids) {
1811
-                // wait wait wait- if nothing was affected let's stop here
1812
-                return 0;
1813
-            }
1814
-            foreach ($model_objs_affected_ids as $id) {
1815
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1816
-                if ($model_obj_in_entity_map) {
1817
-                    foreach ($fields_n_values as $field => $new_value) {
1818
-                        $model_obj_in_entity_map->set($field, $new_value);
1819
-                    }
1820
-                }
1821
-            }
1822
-            // if there is a primary key on this model, we can now do a slight optimization
1823
-            if ($this->has_primary_key_field()) {
1824
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1825
-                $query_params = [
1826
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1827
-                    'limit'                    => count($model_objs_affected_ids),
1828
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1829
-                ];
1830
-            }
1831
-        }
1832
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1833
-
1834
-        // note: the following query doesn't use _construct_2nd_half_of_select_query()
1835
-        // because it doesn't accept LIMIT, ORDER BY, etc.
1836
-        $rows_affected = $this->_do_wpdb_query(
1837
-            'query',
1838
-            [
1839
-                "UPDATE " . $model_query_info->get_full_join_sql()
1840
-                . " SET " . $this->_construct_update_sql($fields_n_values)
1841
-                . $model_query_info->get_where_sql(),
1842
-            ]
1843
-        );
1844
-
1845
-        /**
1846
-         * Action called after a model update call has been made.
1847
-         *
1848
-         * @param EEM_Base $model
1849
-         * @param array    $fields_n_values the updated fields and their new values
1850
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1851
-         * @param int      $rows_affected
1852
-         */
1853
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1854
-        return $rows_affected;// how many supposedly got updated
1855
-    }
1856
-
1857
-
1858
-    /**
1859
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1860
-     * are teh values of the field specified (or by default the primary key field)
1861
-     * that matched the query params. Note that you should pass the name of the
1862
-     * model FIELD, not the database table's column name.
1863
-     *
1864
-     * @param array  $query_params @see
1865
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1866
-     * @param string $field_to_select
1867
-     * @return array just like $wpdb->get_col()
1868
-     * @throws EE_Error
1869
-     * @throws ReflectionException
1870
-     */
1871
-    public function get_col($query_params = [], $field_to_select = null)
1872
-    {
1873
-        if ($field_to_select) {
1874
-            $field = $this->field_settings_for($field_to_select);
1875
-        } elseif ($this->has_primary_key_field()) {
1876
-            $field = $this->get_primary_key_field();
1877
-        } else {
1878
-            $field_settings = $this->field_settings();
1879
-            // no primary key, just grab the first column
1880
-            $field = reset($field_settings);
1881
-            // don't need this array now
1882
-            unset($field_settings);
1883
-        }
1884
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1885
-        $select_expressions = $field->get_qualified_column();
1886
-        $SQL                =
1887
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1888
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1889
-    }
1890
-
1891
-
1892
-    /**
1893
-     * Returns a single column value for a single row from the database
1894
-     *
1895
-     * @param array  $query_params    @see
1896
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1897
-     * @param string $field_to_select @see EEM_Base::get_col()
1898
-     * @return string
1899
-     * @throws EE_Error
1900
-     * @throws ReflectionException
1901
-     */
1902
-    public function get_var($query_params = [], $field_to_select = null)
1903
-    {
1904
-        $query_params['limit'] = 1;
1905
-        $col                   = $this->get_col($query_params, $field_to_select);
1906
-        if (! empty($col)) {
1907
-            return reset($col);
1908
-        }
1909
-        return null;
1910
-    }
1911
-
1912
-
1913
-    /**
1914
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1915
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1916
-     * injection, but currently no further filtering is done
1917
-     *
1918
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1919
-     *                               be updated to in the DB
1920
-     * @return string of SQL
1921
-     * @throws EE_Error
1922
-     * @global      $wpdb
1923
-     */
1924
-    public function _construct_update_sql($fields_n_values)
1925
-    {
1926
-        /** @type WPDB $wpdb */
1927
-        global $wpdb;
1928
-        $cols_n_values = [];
1929
-        foreach ($fields_n_values as $field_name => $value) {
1930
-            $field_obj = $this->field_settings_for($field_name);
1931
-            // if the value is NULL, we want to assign the value to that.
1932
-            // wpdb->prepare doesn't really handle that properly
1933
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1934
-            $value_sql       = $prepared_value === null
1935
-                ? 'NULL'
1936
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1937
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1938
-        }
1939
-        return implode(",", $cols_n_values);
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
-     * Performs a HARD delete, meaning the database row should always be removed,
1946
-     * not just have a flag field on it switched
1947
-     * Wrapper for EEM_Base::delete_permanently()
1948
-     *
1949
-     * @param mixed   $id
1950
-     * @param boolean $allow_blocking
1951
-     * @return int the number of rows deleted
1952
-     * @throws EE_Error
1953
-     * @throws ReflectionException
1954
-     */
1955
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1956
-    {
1957
-        return $this->delete_permanently(
1958
-            [
1959
-                [$this->get_primary_key_field()->get_name() => $id],
1960
-                'limit' => 1,
1961
-            ],
1962
-            $allow_blocking
1963
-        );
1964
-    }
1965
-
1966
-
1967
-    /**
1968
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1969
-     * Wrapper for EEM_Base::delete()
1970
-     *
1971
-     * @param mixed   $id
1972
-     * @param boolean $allow_blocking
1973
-     * @return int the number of rows deleted
1974
-     * @throws EE_Error
1975
-     * @throws ReflectionException
1976
-     */
1977
-    public function delete_by_ID($id, $allow_blocking = true)
1978
-    {
1979
-        return $this->delete(
1980
-            [
1981
-                [$this->get_primary_key_field()->get_name() => $id],
1982
-                'limit' => 1,
1983
-            ],
1984
-            $allow_blocking
1985
-        );
1986
-    }
1987
-
1988
-
1989
-    /**
1990
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1991
-     * meaning if the model has a field that indicates its been "trashed" or
1992
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1993
-     *
1994
-     * @param array   $query_params
1995
-     * @param boolean $allow_blocking
1996
-     * @return int how many rows got deleted
1997
-     * @throws EE_Error
1998
-     * @throws ReflectionException
1999
-     * @see EEM_Base::delete_permanently
2000
-     */
2001
-    public function delete($query_params, $allow_blocking = true)
2002
-    {
2003
-        return $this->delete_permanently($query_params, $allow_blocking);
2004
-    }
2005
-
2006
-
2007
-    /**
2008
-     * Deletes the model objects that meet the query params. Note: this method is overridden
2009
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
2010
-     * as archived, not actually deleted
2011
-     *
2012
-     * @param array   $query_params   @see
2013
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2014
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
2015
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
2016
-     *                                deletes regardless of other objects which may depend on it. Its generally
2017
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
2018
-     *                                DB
2019
-     * @return int how many rows got deleted
2020
-     * @throws EE_Error
2021
-     * @throws ReflectionException
2022
-     */
2023
-    public function delete_permanently($query_params, $allow_blocking = true)
2024
-    {
2025
-        /**
2026
-         * Action called just before performing a real deletion query. You can use the
2027
-         * model and its $query_params to find exactly which items will be deleted
2028
-         *
2029
-         * @param EEM_Base $model
2030
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2031
-         * @param boolean  $allow_blocking whether or not to allow related model objects
2032
-         *                                 to block (prevent) this deletion
2033
-         */
2034
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
2035
-        // some MySQL databases may be running safe mode, which may restrict
2036
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
2037
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
2038
-        // to delete them
2039
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2040
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2041
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2042
-            $columns_and_ids_for_deleting
2043
-        );
2044
-        /**
2045
-         * Allows client code to act on the items being deleted before the query is actually executed.
2046
-         *
2047
-         * @param EEM_Base $this                            The model instance being acted on.
2048
-         * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
2049
-         * @param bool     $allow_blocking                  @see param description in method phpdoc block.
2050
-         * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
2051
-         *                                                  derived from the incoming query parameters.
2052
-         * @see details on the structure of this array in the phpdocs
2053
-         *                                                  for the `_get_ids_for_delete_method`
2054
-         */
2055
-        do_action(
2056
-            'AHEE__EEM_Base__delete__before_query',
2057
-            $this,
2058
-            $query_params,
2059
-            $allow_blocking,
2060
-            $columns_and_ids_for_deleting
2061
-        );
2062
-        if ($deletion_where_query_part) {
2063
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2064
-            $table_aliases    = array_keys($this->_tables);
2065
-            $SQL              = "DELETE "
2066
-                                . implode(", ", $table_aliases)
2067
-                                . " FROM "
2068
-                                . $model_query_info->get_full_join_sql()
2069
-                                . " WHERE "
2070
-                                . $deletion_where_query_part;
2071
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2072
-        } else {
2073
-            $rows_deleted = 0;
2074
-        }
2075
-
2076
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2077
-        // there was no error with the delete query.
2078
-        if (
2079
-            $this->has_primary_key_field()
2080
-            && $rows_deleted !== false
2081
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2082
-        ) {
2083
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2084
-            foreach ($ids_for_removal as $id) {
2085
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2086
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2087
-                }
2088
-            }
2089
-
2090
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2091
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2092
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2093
-            // (although it is possible).
2094
-            // Note this can be skipped by using the provided filter and returning false.
2095
-            if (
2096
-                apply_filters(
2097
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2098
-                    ! $this instanceof EEM_Extra_Meta,
2099
-                    $this
2100
-                )
2101
-            ) {
2102
-                EEM_Extra_Meta::instance()->delete_permanently(
2103
-                    [
2104
-                        0 => [
2105
-                            'EXM_type' => $this->get_this_model_name(),
2106
-                            'OBJ_ID'   => [
2107
-                                'IN',
2108
-                                $ids_for_removal,
2109
-                            ],
2110
-                        ],
2111
-                    ]
2112
-                );
2113
-            }
2114
-        }
2115
-
2116
-        /**
2117
-         * Action called just after performing a real deletion query. Although at this point the
2118
-         * items should have been deleted
2119
-         *
2120
-         * @param EEM_Base $model
2121
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2122
-         * @param int      $rows_deleted
2123
-         */
2124
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2125
-        return $rows_deleted;// how many supposedly got deleted
2126
-    }
2127
-
2128
-
2129
-    /**
2130
-     * Checks all the relations that throw error messages when there are blocking related objects
2131
-     * for related model objects. If there are any related model objects on those relations,
2132
-     * adds an EE_Error, and return true
2133
-     *
2134
-     * @param EE_Base_Class|int $this_model_obj_or_id
2135
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2136
-     *                                                 should be ignored when determining whether there are related
2137
-     *                                                 model objects which block this model object's deletion. Useful
2138
-     *                                                 if you know A is related to B and are considering deleting A,
2139
-     *                                                 but want to see if A has any other objects blocking its deletion
2140
-     *                                                 before removing the relation between A and B
2141
-     * @return boolean
2142
-     * @throws EE_Error
2143
-     * @throws ReflectionException
2144
-     */
2145
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2146
-    {
2147
-        // first, if $ignore_this_model_obj was supplied, get its model
2148
-        $ignored_model = $ignore_this_model_obj instanceof EE_Base_Class
2149
-            ? $ignore_this_model_obj->get_model()
2150
-            : null;
2151
-        // now check all the relations of $this_model_obj_or_id and see if there
2152
-        // are any related model objects blocking it?
2153
-        $is_blocked = false;
2154
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2155
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2156
-                // if $ignore_this_model_obj was supplied, then for the query
2157
-                // on that model needs to be told to ignore $ignore_this_model_obj
2158
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2159
-                    $related_model_objects = $relation_obj->get_all_related(
2160
-                        $this_model_obj_or_id,
2161
-                        [
2162
-                            [
2163
-                                $ignored_model->get_primary_key_field()->get_name() => [
2164
-                                    '!=',
2165
-                                    $ignore_this_model_obj->ID(),
2166
-                                ],
2167
-                            ],
2168
-                        ]
2169
-                    );
2170
-                } else {
2171
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2172
-                }
2173
-                if ($related_model_objects) {
2174
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2175
-                    $is_blocked = true;
2176
-                }
2177
-            }
2178
-        }
2179
-        return $is_blocked;
2180
-    }
2181
-
2182
-
2183
-    /**
2184
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2185
-     *
2186
-     * @param array $row_results_for_deleting
2187
-     * @param bool  $allow_blocking
2188
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2189
-     *                              model DOES have a primary_key_field, then the array will be a simple single
2190
-     *                              dimension array where the key is the fully qualified primary key column and the
2191
-     *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2192
-     *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2193
-     *                              be a two dimensional array where each element is a group of columns and values that
2194
-     *                              get deleted. Example: array(
2195
-     *                              0 => array(
2196
-     *                              'Term_Relationship.object_id' => 1
2197
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2198
-     *                              ),
2199
-     *                              1 => array(
2200
-     *                              'Term_Relationship.object_id' => 1
2201
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2202
-     *                              )
2203
-     *                              )
2204
-     * @throws EE_Error
2205
-     * @throws ReflectionException
2206
-     */
2207
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2208
-    {
2209
-        $ids_to_delete_indexed_by_column = [];
2210
-        if ($this->has_primary_key_field()) {
2211
-            $primary_table = $this->_get_main_table();
2212
-            // following lines are commented out because the variables were not being used
2213
-            // not deleting because unsure if calls were intentionally causing side effects
2214
-            // $primary_table_pk_field          =
2215
-            //     $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2216
-            // $other_tables                    = $this->_get_other_tables();
2217
-            $ids_to_delete_indexed_by_column = $query = [];
2218
-            foreach ($row_results_for_deleting as $item_to_delete) {
2219
-                // before we mark this item for deletion,
2220
-                // make sure there's no related entities blocking its deletion (if we're checking)
2221
-                if (
2222
-                    $allow_blocking
2223
-                    && $this->delete_is_blocked_by_related_models(
2224
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2225
-                    )
2226
-                ) {
2227
-                    continue;
2228
-                }
2229
-                // primary table deletes
2230
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2231
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2232
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2233
-                }
2234
-            }
2235
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2236
-            $fields = $this->get_combined_primary_key_fields();
2237
-            foreach ($row_results_for_deleting as $item_to_delete) {
2238
-                $ids_to_delete_indexed_by_column_for_row = [];
2239
-                foreach ($fields as $cpk_field) {
2240
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2241
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2242
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2243
-                    }
2244
-                }
2245
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2246
-            }
2247
-        } else {
2248
-            // so there's no primary key and no combined key...
2249
-            // sorry, can't help you
2250
-            throw new EE_Error(
2251
-                sprintf(
2252
-                    esc_html__(
2253
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2254
-                        "event_espresso"
2255
-                    ),
2256
-                    get_class($this)
2257
-                )
2258
-            );
2259
-        }
2260
-        return $ids_to_delete_indexed_by_column;
2261
-    }
2262
-
2263
-
2264
-    /**
2265
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2266
-     * the corresponding query_part for the query performing the delete.
2267
-     *
2268
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2269
-     * @return string
2270
-     * @throws EE_Error
2271
-     */
2272
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2273
-    {
2274
-        $query_part = '';
2275
-        if (empty($ids_to_delete_indexed_by_column)) {
2276
-            return $query_part;
2277
-        } elseif ($this->has_primary_key_field()) {
2278
-            $query = [];
2279
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2280
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2281
-            }
2282
-            $query_part = ! empty($query)
2283
-                ? implode(' AND ', $query)
2284
-                : $query_part;
2285
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2286
-            $ways_to_identify_a_row = [];
2287
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2288
-                $values_for_each_combined_primary_key_for_a_row = [];
2289
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2290
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2291
-                }
2292
-                $ways_to_identify_a_row[] = '('
2293
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2294
-                                            . ')';
2295
-            }
2296
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2297
-        }
2298
-        return $query_part;
2299
-    }
2300
-
2301
-
2302
-    /**
2303
-     * Gets the model field by the fully qualified name
2304
-     *
2305
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2306
-     * @return EE_Model_Field_Base
2307
-     * @throws EE_Error
2308
-     * @throws EE_Error
2309
-     */
2310
-    public function get_field_by_column($qualified_column_name)
2311
-    {
2312
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2313
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2314
-                return $field_obj;
2315
-            }
2316
-        }
2317
-        throw new EE_Error(
2318
-            sprintf(
2319
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2320
-                $this->get_this_model_name(),
2321
-                $qualified_column_name
2322
-            )
2323
-        );
2324
-    }
2325
-
2326
-
2327
-    /**
2328
-     * Count all the rows that match criteria the model query params.
2329
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2330
-     * column
2331
-     *
2332
-     * @param array  $query_params   @see
2333
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2334
-     * @param string $field_to_count field on model to count by (not column name)
2335
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2336
-     *                               that by the setting $distinct to TRUE;
2337
-     * @return int
2338
-     * @throws EE_Error
2339
-     * @throws ReflectionException
2340
-     */
2341
-    public function count($query_params = [], $field_to_count = null, $distinct = false)
2342
-    {
2343
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2344
-        if ($field_to_count) {
2345
-            $field_obj       = $this->field_settings_for($field_to_count);
2346
-            $column_to_count = $field_obj->get_qualified_column();
2347
-        } elseif ($this->has_primary_key_field()) {
2348
-            $pk_field_obj    = $this->get_primary_key_field();
2349
-            $column_to_count = $pk_field_obj->get_qualified_column();
2350
-        } else {
2351
-            // there's no primary key
2352
-            // if we're counting distinct items, and there's no primary key,
2353
-            // we need to list out the columns for distinction;
2354
-            // otherwise we can just use star
2355
-            if ($distinct) {
2356
-                $columns_to_use = [];
2357
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2358
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2359
-                }
2360
-                $column_to_count = implode(',', $columns_to_use);
2361
-            } else {
2362
-                $column_to_count = '*';
2363
-            }
2364
-        }
2365
-        $column_to_count = $distinct
2366
-            ? "DISTINCT " . $column_to_count
2367
-            : $column_to_count;
2368
-        $SQL             =
2369
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2370
-        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2371
-    }
2372
-
2373
-
2374
-    /**
2375
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2376
-     *
2377
-     * @param array  $query_params @see
2378
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2379
-     * @param string $field_to_sum name of field (array key in $_fields array)
2380
-     * @return float
2381
-     * @throws EE_Error
2382
-     * @throws ReflectionException
2383
-     */
2384
-    public function sum($query_params, $field_to_sum = null)
2385
-    {
2386
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2387
-        if ($field_to_sum) {
2388
-            $field_obj = $this->field_settings_for($field_to_sum);
2389
-        } else {
2390
-            $field_obj = $this->get_primary_key_field();
2391
-        }
2392
-        $column_to_count = $field_obj->get_qualified_column();
2393
-        $SQL             =
2394
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2395
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2396
-        $data_type       = $field_obj->get_wpdb_data_type();
2397
-        if ($data_type === '%d' || $data_type === '%s') {
2398
-            return (float) $return_value;
2399
-        }
2400
-        // must be %f
2401
-        return (float) $return_value;
2402
-    }
2403
-
2404
-
2405
-    /**
2406
-     * Just calls the specified method on $wpdb with the given arguments
2407
-     * Consolidates a little extra error handling code
2408
-     *
2409
-     * @param string $wpdb_method
2410
-     * @param array  $arguments_to_provide
2411
-     * @return mixed
2412
-     * @throws EE_Error
2413
-     * @global wpdb  $wpdb
2414
-     */
2415
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2416
-    {
2417
-        // if we're in maintenance mode level 2, DON'T run any queries
2418
-        // because level 2 indicates the database needs updating and
2419
-        // is probably out of sync with the code
2420
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2421
-            throw new RuntimeException(
2422
-                esc_html__(
2423
-                    "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.",
2424
-                    "event_espresso"
2425
-                )
2426
-            );
2427
-        }
2428
-        /** @type WPDB $wpdb */
2429
-        global $wpdb;
2430
-        if (! method_exists($wpdb, $wpdb_method)) {
2431
-            throw new DomainException(
2432
-                sprintf(
2433
-                    esc_html__(
2434
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2435
-                        'event_espresso'
2436
-                    ),
2437
-                    $wpdb_method
2438
-                )
2439
-            );
2440
-        }
2441
-        $old_show_errors_value = $wpdb->show_errors;
2442
-        if (WP_DEBUG) {
2443
-            $wpdb->show_errors(false);
2444
-        }
2445
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2446
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2447
-        if (WP_DEBUG) {
2448
-            $wpdb->show_errors($old_show_errors_value);
2449
-            if (! empty($wpdb->last_error)) {
2450
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2451
-            }
2452
-            if ($result === false) {
2453
-                throw new EE_Error(
2454
-                    sprintf(
2455
-                        esc_html__(
2456
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2457
-                            'event_espresso'
2458
-                        ),
2459
-                        $wpdb_method,
2460
-                        var_export($arguments_to_provide, true)
2461
-                    )
2462
-                );
2463
-            }
2464
-        } elseif ($result === false) {
2465
-            EE_Error::add_error(
2466
-                sprintf(
2467
-                    esc_html__(
2468
-                        '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"',
2469
-                        'event_espresso'
2470
-                    ),
2471
-                    $wpdb_method,
2472
-                    var_export($arguments_to_provide, true),
2473
-                    $wpdb->last_error
2474
-                ),
2475
-                __FILE__,
2476
-                __FUNCTION__,
2477
-                __LINE__
2478
-            );
2479
-        }
2480
-        return $result;
2481
-    }
2482
-
2483
-
2484
-    /**
2485
-     * Attempts to run the indicated WPDB method with the provided arguments,
2486
-     * and if there's an error tries to verify the DB is correct. Uses
2487
-     * the static property EEM_Base::$_db_verification_level to determine whether
2488
-     * we should try to fix the EE core db, the addons, or just give up
2489
-     *
2490
-     * @param string $wpdb_method
2491
-     * @param array  $arguments_to_provide
2492
-     * @return mixed
2493
-     */
2494
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2495
-    {
2496
-        /** @type WPDB $wpdb */
2497
-        global $wpdb;
2498
-        $wpdb->last_error = null;
2499
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2500
-        // was there an error running the query? but we don't care on new activations
2501
-        // (we're going to setup the DB anyway on new activations)
2502
-        if (
2503
-            ($result === false || ! empty($wpdb->last_error))
2504
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2505
-        ) {
2506
-            switch (EEM_Base::$_db_verification_level) {
2507
-                case EEM_Base::db_verified_none:
2508
-                    // let's double-check core's DB
2509
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2510
-                    break;
2511
-                case EEM_Base::db_verified_core:
2512
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2513
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2514
-                    break;
2515
-                case EEM_Base::db_verified_addons:
2516
-                    // ummmm... you in trouble
2517
-                    return $result;
2518
-            }
2519
-            if (! empty($error_message)) {
2520
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2521
-                trigger_error($error_message);
2522
-            }
2523
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2524
-        }
2525
-        return $result;
2526
-    }
2527
-
2528
-
2529
-    /**
2530
-     * Verifies the EE core database is up-to-date and records that we've done it on
2531
-     * EEM_Base::$_db_verification_level
2532
-     *
2533
-     * @param string $wpdb_method
2534
-     * @param array  $arguments_to_provide
2535
-     * @return string
2536
-     * @throws EE_Error
2537
-     * @throws ReflectionException
2538
-     */
2539
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2540
-    {
2541
-        /** @type WPDB $wpdb */
2542
-        global $wpdb;
2543
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2544
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2545
-        $error_message                    = sprintf(
2546
-            esc_html__(
2547
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2548
-                'event_espresso'
2549
-            ),
2550
-            $wpdb->last_error,
2551
-            $wpdb_method,
2552
-            wp_json_encode($arguments_to_provide)
2553
-        );
2554
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2555
-        return $error_message;
2556
-    }
2557
-
2558
-
2559
-    /**
2560
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2561
-     * EEM_Base::$_db_verification_level
2562
-     *
2563
-     * @param $wpdb_method
2564
-     * @param $arguments_to_provide
2565
-     * @return string
2566
-     * @throws EE_Error
2567
-     * @throws ReflectionException
2568
-     */
2569
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2570
-    {
2571
-        /** @type WPDB $wpdb */
2572
-        global $wpdb;
2573
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2574
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2575
-        $error_message                    = sprintf(
2576
-            esc_html__(
2577
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2578
-                'event_espresso'
2579
-            ),
2580
-            $wpdb->last_error,
2581
-            $wpdb_method,
2582
-            wp_json_encode($arguments_to_provide)
2583
-        );
2584
-        EE_System::instance()->initialize_addons();
2585
-        return $error_message;
2586
-    }
2587
-
2588
-
2589
-    /**
2590
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2591
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2592
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2593
-     * ..."
2594
-     *
2595
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2596
-     * @return string
2597
-     */
2598
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2599
-    {
2600
-        return " FROM " . $model_query_info->get_full_join_sql() .
2601
-               $model_query_info->get_where_sql() .
2602
-               $model_query_info->get_group_by_sql() .
2603
-               $model_query_info->get_having_sql() .
2604
-               $model_query_info->get_order_by_sql() .
2605
-               $model_query_info->get_limit_sql();
2606
-    }
2607
-
2608
-
2609
-    /**
2610
-     * Set to easily debug the next X queries ran from this model.
2611
-     *
2612
-     * @param int $count
2613
-     */
2614
-    public function show_next_x_db_queries($count = 1)
2615
-    {
2616
-        $this->_show_next_x_db_queries = $count;
2617
-    }
2618
-
2619
-
2620
-    /**
2621
-     * @param $sql_query
2622
-     */
2623
-    public function show_db_query_if_previously_requested($sql_query)
2624
-    {
2625
-        if ($this->_show_next_x_db_queries > 0) {
2626
-            echo esc_html($sql_query);
2627
-            $this->_show_next_x_db_queries--;
2628
-        }
2629
-    }
2630
-
2631
-
2632
-    /**
2633
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2634
-     * There are the 3 cases:
2635
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2636
-     * $otherModelObject has no ID, it is first saved.
2637
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2638
-     * has no ID, it is first saved.
2639
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2640
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2641
-     * join table
2642
-     *
2643
-     * @param EE_Base_Class|int $id_or_obj                        EE_base_Class or ID of $thisModelObject
2644
-     * @param EE_Base_Class|int $other_model_id_or_obj            EE_base_Class or ID of other Model Object
2645
-     * @param string            $relationName                     , key in EEM_Base::_relations
2646
-     *                                                            an attendee to a group, you also want to specify
2647
-     *                                                            which role they will have in that group. So you would
2648
-     *                                                            use this parameter to specify
2649
-     *                                                            array('role-column-name'=>'role-id')
2650
-     * @param array|null        $extra_join_model_fields_n_values This allows you to enter further query params for the
2651
-     *                                                            relation to for relation to methods that allow you to
2652
-     *                                                            further specify extra columns to join by (such as
2653
-     *                                                            HABTM).  Keep in mind that the only acceptable
2654
-     *                                                            query_params is strict "col" => "value" pairs because
2655
-     *                                                            these will be inserted in any new rows created as
2656
-     *                                                            well.
2657
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2658
-     * @throws EE_Error
2659
-     */
2660
-    public function add_relationship_to(
2661
-        $id_or_obj,
2662
-        $other_model_id_or_obj,
2663
-        $relationName,
2664
-        $extra_join_model_fields_n_values = []
2665
-    ) {
2666
-        $relation_obj = $this->related_settings_for($relationName);
2667
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2668
-    }
2669
-
2670
-
2671
-    /**
2672
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2673
-     * There are the 3 cases:
2674
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2675
-     * error
2676
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2677
-     * an error
2678
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2679
-     *
2680
-     * @param EE_Base_Class|int $id_or_obj             EE_base_Class or ID of $thisModelObject
2681
-     * @param EE_Base_Class|int $other_model_id_or_obj EE_base_Class or ID of other Model Object
2682
-     * @param string            $relationName          key in EEM_Base::_relations
2683
-     * @param array|null        $where_query           This allows you to enter further query params for the relation
2684
-     *                                                 to for relation to methods that allow you to further specify
2685
-     *                                                 extra columns to join by (such as HABTM). Keep in mind that the
2686
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2687
-     *                                                 because these will be inserted in any new rows created as well.
2688
-     * @return EE_Base_Class
2689
-     * @throws EE_Error
2690
-     */
2691
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2692
-    {
2693
-        $relation_obj = $this->related_settings_for($relationName);
2694
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2695
-    }
2696
-
2697
-
2698
-    /**
2699
-     * @param mixed       $id_or_obj
2700
-     * @param string      $relationName
2701
-     * @param array|null  $where_query_params
2702
-     * @return EE_Base_Class[]
2703
-     * @throws EE_Error
2704
-     * @throws ReflectionException
2705
-     */
2706
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2707
-    {
2708
-        $relation_obj = $this->related_settings_for($relationName);
2709
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2710
-    }
2711
-
2712
-
2713
-    /**
2714
-     * Gets all the related items of the specified $model_name, using $query_params.
2715
-     * Note: by default, we remove the "default query params"
2716
-     * because we want to get even deleted items etc.
2717
-     *
2718
-     * @param mixed       $id_or_obj    EE_Base_Class child or its ID
2719
-     * @param string      $model_name   like 'Event', 'Registration', etc. always singular
2720
-     * @param array|null  $query_params @see
2721
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2722
-     * @return EE_Base_Class[]
2723
-     * @throws EE_Error
2724
-     * @throws ReflectionException
2725
-     */
2726
-    public function get_all_related($id_or_obj, $model_name, ?array $query_params = [])
2727
-    {
2728
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2729
-        $relation_settings = $this->related_settings_for($model_name);
2730
-        return $relation_settings->get_all_related($model_obj, $query_params);
2731
-    }
2732
-
2733
-
2734
-    /**
2735
-     * Deletes all the model objects across the relation indicated by $model_name
2736
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2737
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2738
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2739
-     *
2740
-     * @param EE_Base_Class|int|string $id_or_obj
2741
-     * @param string                   $model_name
2742
-     * @param array|null               $query_params
2743
-     * @return int how many deleted
2744
-     * @throws EE_Error
2745
-     * @throws ReflectionException
2746
-     */
2747
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2748
-    {
2749
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2750
-        $relation_settings = $this->related_settings_for($model_name);
2751
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2752
-    }
2753
-
2754
-
2755
-    /**
2756
-     * Hard deletes all the model objects across the relation indicated by $model_name
2757
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2758
-     * the model objects can't be hard deleted because of blocking related model objects,
2759
-     * just does a soft-delete on them instead.
2760
-     *
2761
-     * @param EE_Base_Class|int|string $id_or_obj
2762
-     * @param string                   $model_name
2763
-     * @param array|null               $query_params
2764
-     * @return int how many deleted
2765
-     * @throws EE_Error
2766
-     * @throws ReflectionException
2767
-     */
2768
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2769
-    {
2770
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2771
-        $relation_settings = $this->related_settings_for($model_name);
2772
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2773
-    }
2774
-
2775
-
2776
-    /**
2777
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2778
-     * unless otherwise specified in the $query_params
2779
-     *
2780
-     * @param EE_Base_Class|int|string $id_or_obj
2781
-     * @param string                   $model_name     like 'Event', or 'Registration'
2782
-     * @param array|null               $query_params   @see
2783
-     *                                                 https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2784
-     * @param string                   $field_to_count name of field to count by. By default, uses primary key
2785
-     * @param bool                     $distinct       if we want to only count the distinct values for the column then
2786
-     *                                                 you can trigger that by the setting $distinct to TRUE;
2787
-     * @return int
2788
-     * @throws EE_Error
2789
-     * @throws ReflectionException
2790
-     */
2791
-    public function count_related(
2792
-        $id_or_obj,
2793
-        $model_name,
2794
-        $query_params = [],
2795
-        $field_to_count = null,
2796
-        $distinct = false
2797
-    ) {
2798
-        $related_model = $this->get_related_model_obj($model_name);
2799
-        // we're just going to use the query params on the related model's normal get_all query,
2800
-        // except add a condition to say to match the current mod
2801
-        if (! isset($query_params['default_where_conditions'])) {
2802
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2803
-        }
2804
-        $this_model_name                                                 = $this->get_this_model_name();
2805
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2806
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2807
-        return $related_model->count($query_params, $field_to_count, $distinct);
2808
-    }
2809
-
2810
-
2811
-    /**
2812
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2813
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2814
-     *
2815
-     * @param EE_Base_Class|int|string $id_or_obj
2816
-     * @param string                   $model_name   like 'Event', or 'Registration'
2817
-     * @param array|null               $query_params @see
2818
-     *                                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2819
-     * @param string                   $field_to_sum name of field to count by. By default, uses primary key
2820
-     * @return float
2821
-     * @throws EE_Error
2822
-     * @throws ReflectionException
2823
-     */
2824
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2825
-    {
2826
-        $related_model = $this->get_related_model_obj($model_name);
2827
-        if (! is_array($query_params)) {
2828
-            EE_Error::doing_it_wrong(
2829
-                'EEM_Base::sum_related',
2830
-                sprintf(
2831
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2832
-                    gettype($query_params)
2833
-                ),
2834
-                '4.6.0'
2835
-            );
2836
-            $query_params = [];
2837
-        }
2838
-        // we're just going to use the query params on the related model's normal get_all query,
2839
-        // except add a condition to say to match the current mod
2840
-        if (! isset($query_params['default_where_conditions'])) {
2841
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2842
-        }
2843
-        $this_model_name                                                 = $this->get_this_model_name();
2844
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2845
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2846
-        return $related_model->sum($query_params, $field_to_sum);
2847
-    }
2848
-
2849
-
2850
-    /**
2851
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2852
-     * $modelObject
2853
-     *
2854
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2855
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2856
-     * @param array|null          $query_params     @see
2857
-     *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2858
-     * @return EE_Base_Class
2859
-     * @throws EE_Error
2860
-     * @throws ReflectionException
2861
-     */
2862
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2863
-    {
2864
-        $query_params['limit'] = 1;
2865
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2866
-        if ($results) {
2867
-            return array_shift($results);
2868
-        }
2869
-        return null;
2870
-    }
2871
-
2872
-
2873
-    /**
2874
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2875
-     *
2876
-     * @return string
2877
-     */
2878
-    public function get_this_model_name()
2879
-    {
2880
-        return str_replace("EEM_", "", get_class($this));
2881
-    }
2882
-
2883
-
2884
-    /**
2885
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2886
-     *
2887
-     * @return EE_Any_Foreign_Model_Name_Field
2888
-     * @throws EE_Error
2889
-     */
2890
-    public function get_field_containing_related_model_name()
2891
-    {
2892
-        foreach ($this->field_settings(true) as $field) {
2893
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2894
-                $field_with_model_name = $field;
2895
-            }
2896
-        }
2897
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2898
-            throw new EE_Error(
2899
-                sprintf(
2900
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2901
-                    $this->get_this_model_name()
2902
-                )
2903
-            );
2904
-        }
2905
-        return $field_with_model_name;
2906
-    }
2907
-
2908
-
2909
-    /**
2910
-     * Inserts a new entry into the database, for each table.
2911
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2912
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2913
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2914
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2915
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2916
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2917
-     *
2918
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2919
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2920
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2921
-     *                              of EEM_Base)
2922
-     * @return int|string new primary key on main table that got inserted
2923
-     * @throws EE_Error
2924
-     * @throws ReflectionException
2925
-     */
2926
-    public function insert($field_n_values)
2927
-    {
2928
-        /**
2929
-         * Filters the fields and their values before inserting an item using the models
2930
-         *
2931
-         * @param array    $fields_n_values keys are the fields and values are their new values
2932
-         * @param EEM_Base $model           the model used
2933
-         */
2934
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2935
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2936
-            $main_table = $this->_get_main_table();
2937
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2938
-            if ($new_id !== false) {
2939
-                foreach ($this->_get_other_tables() as $other_table) {
2940
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2941
-                }
2942
-            }
2943
-            /**
2944
-             * Done just after attempting to insert a new model object
2945
-             *
2946
-             * @param EEM_Base $model           used
2947
-             * @param array    $fields_n_values fields and their values
2948
-             * @param int|string the              ID of the newly-inserted model object
2949
-             */
2950
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2951
-            return $new_id;
2952
-        }
2953
-        return false;
2954
-    }
2955
-
2956
-
2957
-    /**
2958
-     * Checks that the result would satisfy the unique indexes on this model
2959
-     *
2960
-     * @param array  $field_n_values
2961
-     * @param string $action
2962
-     * @return boolean
2963
-     * @throws EE_Error
2964
-     * @throws ReflectionException
2965
-     */
2966
-    protected function _satisfies_unique_indexes(array $field_n_values, $action = 'insert')
2967
-    {
2968
-        foreach ($this->unique_indexes() as $index_name => $index) {
2969
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2970
-            if ($this->exists([$uniqueness_where_params])) {
2971
-                EE_Error::add_error(
2972
-                    sprintf(
2973
-                        esc_html__(
2974
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2975
-                            "event_espresso"
2976
-                        ),
2977
-                        $action,
2978
-                        $this->_get_class_name(),
2979
-                        $index_name,
2980
-                        implode(",", $index->field_names()),
2981
-                        http_build_query($uniqueness_where_params)
2982
-                    ),
2983
-                    __FILE__,
2984
-                    __FUNCTION__,
2985
-                    __LINE__
2986
-                );
2987
-                return false;
2988
-            }
2989
-        }
2990
-        return true;
2991
-    }
2992
-
2993
-
2994
-    /**
2995
-     * Checks the database for an item that conflicts (ie, if this item were
2996
-     * saved to the DB would break some uniqueness requirement, like a primary key
2997
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2998
-     * can be either an EE_Base_Class or an array of fields n values
2999
-     *
3000
-     * @param EE_Base_Class|array $obj_or_fields_array
3001
-     * @param boolean             $include_primary_key whether to use the model object's primary key
3002
-     *                                                 when looking for conflicts
3003
-     *                                                 (ie, if false, we ignore the model object's primary key
3004
-     *                                                 when finding "conflicts". If true, it's also considered).
3005
-     *                                                 Only works for INT primary key,
3006
-     *                                                 STRING primary keys cannot be ignored
3007
-     * @return EE_Base_Class|array
3008
-     * @throws EE_Error
3009
-     * @throws ReflectionException
3010
-     */
3011
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
3012
-    {
3013
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
3014
-            $fields_n_values = $obj_or_fields_array->model_field_array();
3015
-        } elseif (is_array($obj_or_fields_array)) {
3016
-            $fields_n_values = $obj_or_fields_array;
3017
-        } else {
3018
-            throw new EE_Error(
3019
-                sprintf(
3020
-                    esc_html__(
3021
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
3022
-                        "event_espresso"
3023
-                    ),
3024
-                    get_class($this),
3025
-                    $obj_or_fields_array
3026
-                )
3027
-            );
3028
-        }
3029
-        $query_params = [];
3030
-        if (
3031
-            $this->has_primary_key_field()
3032
-            && ($include_primary_key
3033
-                || $this->get_primary_key_field()
3034
-                   instanceof
3035
-                   EE_Primary_Key_String_Field)
3036
-            && isset($fields_n_values[ $this->primary_key_name() ])
3037
-        ) {
3038
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3039
-        }
3040
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3041
-            $uniqueness_where_params                              =
3042
-                array_intersect_key($fields_n_values, $unique_index->fields());
3043
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3044
-        }
3045
-        // if there is nothing to base this search on, then we shouldn't find anything
3046
-        if (empty($query_params)) {
3047
-            return [];
3048
-        }
3049
-        return $this->get_one($query_params);
3050
-    }
3051
-
3052
-
3053
-    /**
3054
-     * Like count, but is optimized and returns a boolean instead of an int
3055
-     *
3056
-     * @param array $query_params
3057
-     * @return boolean
3058
-     * @throws EE_Error
3059
-     * @throws ReflectionException
3060
-     */
3061
-    public function exists($query_params)
3062
-    {
3063
-        $query_params['limit'] = 1;
3064
-        return $this->count($query_params) > 0;
3065
-    }
3066
-
3067
-
3068
-    /**
3069
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
3070
-     *
3071
-     * @param int|string $id
3072
-     * @return boolean
3073
-     * @throws EE_Error
3074
-     * @throws ReflectionException
3075
-     */
3076
-    public function exists_by_ID($id)
3077
-    {
3078
-        return $this->exists(
3079
-            [
3080
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3081
-                [
3082
-                    $this->primary_key_name() => $id,
3083
-                ],
3084
-            ]
3085
-        );
3086
-    }
3087
-
3088
-
3089
-    /**
3090
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3091
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3092
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3093
-     * on the main table)
3094
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3095
-     * cases where we want to call it directly rather than via insert().
3096
-     *
3097
-     * @access   protected
3098
-     * @param EE_Table_Base $table
3099
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3100
-     *                                       float
3101
-     * @param int           $new_id          for now we assume only int keys
3102
-     * @return int ID of new row inserted, or FALSE on failure
3103
-     * @throws EE_Error
3104
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3105
-     */
3106
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3107
-    {
3108
-        global $wpdb;
3109
-        $insertion_col_n_values = [];
3110
-        $format_for_insertion   = [];
3111
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3112
-        foreach ($fields_on_table as $field_obj) {
3113
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3114
-            if ($field_obj->is_auto_increment()) {
3115
-                continue;
3116
-            }
3117
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3118
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3119
-            if ($prepared_value !== null) {
3120
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3121
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3122
-            }
3123
-        }
3124
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3125
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3126
-            // so add the fk to the main table as a column
3127
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3128
-            $format_for_insertion[]                              =
3129
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3130
-        }
3131
-
3132
-        // insert the new entry
3133
-        $result = $this->_do_wpdb_query(
3134
-            'insert',
3135
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3136
-        );
3137
-        if ($result === false) {
3138
-            return false;
3139
-        }
3140
-        // ok, now what do we return for the ID of the newly-inserted thing?
3141
-        if ($this->has_primary_key_field()) {
3142
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3143
-                return $wpdb->insert_id;
3144
-            }
3145
-            // it's not an auto-increment primary key, so
3146
-            // it must have been supplied
3147
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3148
-        }
3149
-        // we can't return a  primary key because there is none. instead return
3150
-        // a unique string indicating this model
3151
-        return $this->get_index_primary_key_string($fields_n_values);
3152
-    }
3153
-
3154
-
3155
-    /**
3156
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3157
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3158
-     * and there is no default, we pass it along. WPDB will take care of it)
3159
-     *
3160
-     * @param EE_Model_Field_Base $field_obj
3161
-     * @param array               $fields_n_values
3162
-     * @return mixed string|int|float depending on what the table column will be expecting
3163
-     * @throws EE_Error
3164
-     */
3165
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3166
-    {
3167
-        $field_name = $field_obj->get_name();
3168
-        // if this field doesn't allow nullable, don't allow it
3169
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3170
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3171
-        }
3172
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3173
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3174
-    }
3175
-
3176
-
3177
-    /**
3178
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3179
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3180
-     * the field's prepare_for_set() method.
3181
-     *
3182
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3183
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3184
-     *                                   top of file)
3185
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3186
-     *                                   $value is a custom selection
3187
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3188
-     */
3189
-    private function _prepare_value_for_use_in_db($value, $field)
3190
-    {
3191
-        if ($field instanceof EE_Model_Field_Base) {
3192
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3193
-            switch ($this->_values_already_prepared_by_model_object) {
3194
-                /** @noinspection PhpMissingBreakStatementInspection */
3195
-                case self::not_prepared_by_model_object:
3196
-                    $value = $field->prepare_for_set($value);
3197
-                // purposefully left out "return"
3198
-                // no break
3199
-                case self::prepared_by_model_object:
3200
-                    /** @noinspection SuspiciousAssignmentsInspection */
3201
-                    $value = $field->prepare_for_use_in_db($value);
3202
-                // no break
3203
-                case self::prepared_for_use_in_db:
3204
-                    // leave the value alone
3205
-            }
3206
-            // phpcs:enable
3207
-        }
3208
-        return $value;
3209
-    }
3210
-
3211
-
3212
-    /**
3213
-     * Returns the main table on this model
3214
-     *
3215
-     * @return EE_Primary_Table
3216
-     * @throws EE_Error
3217
-     */
3218
-    protected function _get_main_table()
3219
-    {
3220
-        foreach ($this->_tables as $table) {
3221
-            if ($table instanceof EE_Primary_Table) {
3222
-                return $table;
3223
-            }
3224
-        }
3225
-        throw new EE_Error(
3226
-            sprintf(
3227
-                esc_html__(
3228
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3229
-                    'event_espresso'
3230
-                ),
3231
-                get_class($this)
3232
-            )
3233
-        );
3234
-    }
3235
-
3236
-
3237
-    /**
3238
-     * table
3239
-     * returns EE_Primary_Table table name
3240
-     *
3241
-     * @return string
3242
-     * @throws EE_Error
3243
-     */
3244
-    public function table()
3245
-    {
3246
-        return $this->_get_main_table()->get_table_name();
3247
-    }
3248
-
3249
-
3250
-    /**
3251
-     * table
3252
-     * returns first EE_Secondary_Table table name
3253
-     *
3254
-     * @return string
3255
-     */
3256
-    public function second_table()
3257
-    {
3258
-        // grab second table from tables array
3259
-        $second_table = end($this->_tables);
3260
-        return $second_table instanceof EE_Secondary_Table
3261
-            ? $second_table->get_table_name()
3262
-            : null;
3263
-    }
3264
-
3265
-
3266
-    /**
3267
-     * get_table_obj_by_alias
3268
-     * returns table name given it's alias
3269
-     *
3270
-     * @param string $table_alias
3271
-     * @return EE_Primary_Table | EE_Secondary_Table
3272
-     */
3273
-    public function get_table_obj_by_alias($table_alias = '')
3274
-    {
3275
-        return $this->_tables[ $table_alias ] ?? null;
3276
-    }
3277
-
3278
-
3279
-    /**
3280
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3281
-     *
3282
-     * @return EE_Secondary_Table[]
3283
-     */
3284
-    protected function _get_other_tables()
3285
-    {
3286
-        $other_tables = [];
3287
-        foreach ($this->_tables as $table_alias => $table) {
3288
-            if ($table instanceof EE_Secondary_Table) {
3289
-                $other_tables[ $table_alias ] = $table;
3290
-            }
3291
-        }
3292
-        return $other_tables;
3293
-    }
3294
-
3295
-
3296
-    /**
3297
-     * Finds all the fields that correspond to the given table
3298
-     *
3299
-     * @param string $table_alias , array key in EEM_Base::_tables
3300
-     * @return EE_Model_Field_Base[]
3301
-     */
3302
-    public function _get_fields_for_table($table_alias)
3303
-    {
3304
-        return $this->_fields[ $table_alias ];
3305
-    }
3306
-
3307
-
3308
-    /**
3309
-     * Recurses through all the where parameters, and finds all the related models we'll need
3310
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3311
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3312
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3313
-     * related Registration, Transaction, and Payment models.
3314
-     *
3315
-     * @param array $query_params @see
3316
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3317
-     * @return EE_Model_Query_Info_Carrier
3318
-     * @throws EE_Error
3319
-     */
3320
-    public function _extract_related_models_from_query($query_params)
3321
-    {
3322
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3323
-        if (array_key_exists(0, $query_params)) {
3324
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3325
-        }
3326
-        if (array_key_exists('group_by', $query_params)) {
3327
-            if (is_array($query_params['group_by'])) {
3328
-                $this->_extract_related_models_from_sub_params_array_values(
3329
-                    $query_params['group_by'],
3330
-                    $query_info_carrier,
3331
-                    'group_by'
3332
-                );
3333
-            } elseif (! empty($query_params['group_by'])) {
3334
-                $this->_extract_related_model_info_from_query_param(
3335
-                    $query_params['group_by'],
3336
-                    $query_info_carrier,
3337
-                    'group_by'
3338
-                );
3339
-            }
3340
-        }
3341
-        if (array_key_exists('having', $query_params)) {
3342
-            $this->_extract_related_models_from_sub_params_array_keys(
3343
-                $query_params[0],
3344
-                $query_info_carrier,
3345
-                'having'
3346
-            );
3347
-        }
3348
-        if (array_key_exists('order_by', $query_params)) {
3349
-            if (is_array($query_params['order_by'])) {
3350
-                $this->_extract_related_models_from_sub_params_array_keys(
3351
-                    $query_params['order_by'],
3352
-                    $query_info_carrier,
3353
-                    'order_by'
3354
-                );
3355
-            } elseif (! empty($query_params['order_by'])) {
3356
-                $this->_extract_related_model_info_from_query_param(
3357
-                    $query_params['order_by'],
3358
-                    $query_info_carrier,
3359
-                    'order_by'
3360
-                );
3361
-            }
3362
-        }
3363
-        if (array_key_exists('force_join', $query_params)) {
3364
-            $this->_extract_related_models_from_sub_params_array_values(
3365
-                $query_params['force_join'],
3366
-                $query_info_carrier,
3367
-                'force_join'
3368
-            );
3369
-        }
3370
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3371
-        return $query_info_carrier;
3372
-    }
3373
-
3374
-
3375
-    /**
3376
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3377
-     *
3378
-     * @param array                       $sub_query_params
3379
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3380
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3381
-     * @return EE_Model_Query_Info_Carrier
3382
-     * @throws EE_Error
3383
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3384
-     */
3385
-    private function _extract_related_models_from_sub_params_array_keys(
3386
-        $sub_query_params,
3387
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3388
-        $query_param_type
3389
-    ) {
3390
-        if (! empty($sub_query_params)) {
3391
-            $sub_query_params = (array) $sub_query_params;
3392
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3393
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3394
-                $this->_extract_related_model_info_from_query_param(
3395
-                    $param,
3396
-                    $model_query_info_carrier,
3397
-                    $query_param_type
3398
-                );
3399
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3400
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3401
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3402
-                // of array('Registration.TXN_ID'=>23)
3403
-                $query_param_sans_stars =
3404
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3405
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3406
-                    if (! is_array($possibly_array_of_params)) {
3407
-                        throw new EE_Error(
3408
-                            sprintf(
3409
-                                esc_html__(
3410
-                                    "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'))",
3411
-                                    "event_espresso"
3412
-                                ),
3413
-                                $param,
3414
-                                $possibly_array_of_params
3415
-                            )
3416
-                        );
3417
-                    }
3418
-                    $this->_extract_related_models_from_sub_params_array_keys(
3419
-                        $possibly_array_of_params,
3420
-                        $model_query_info_carrier,
3421
-                        $query_param_type
3422
-                    );
3423
-                } elseif (
3424
-                    $query_param_type === 0 // ie WHERE
3425
-                    && is_array($possibly_array_of_params) // need is_array() check so we don't try to explode a string
3426
-                    && isset($possibly_array_of_params[2])
3427
-                    && $possibly_array_of_params[2]
3428
-                ) {
3429
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3430
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3431
-                    // from which we should extract query parameters!
3432
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3433
-                        throw new EE_Error(
3434
-                            sprintf(
3435
-                                esc_html__(
3436
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3437
-                                    "event_espresso"
3438
-                                ),
3439
-                                $query_param_type,
3440
-                                implode(",", $possibly_array_of_params)
3441
-                            )
3442
-                        );
3443
-                    }
3444
-                    $this->_extract_related_model_info_from_query_param(
3445
-                        $possibly_array_of_params[1],
3446
-                        $model_query_info_carrier,
3447
-                        $query_param_type
3448
-                    );
3449
-                }
3450
-            }
3451
-        }
3452
-        return $model_query_info_carrier;
3453
-    }
3454
-
3455
-
3456
-    /**
3457
-     * For extracting related models from forced_joins, where the array values contain the info about what
3458
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3459
-     *
3460
-     * @param array                       $sub_query_params @see
3461
-     *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3462
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3463
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3464
-     * @return EE_Model_Query_Info_Carrier
3465
-     * @throws EE_Error
3466
-     */
3467
-    private function _extract_related_models_from_sub_params_array_values(
3468
-        $sub_query_params,
3469
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3470
-        $query_param_type
3471
-    ) {
3472
-        if (! empty($sub_query_params)) {
3473
-            if (! is_array($sub_query_params)) {
3474
-                throw new EE_Error(
3475
-                    sprintf(
3476
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3477
-                        $sub_query_params
3478
-                    )
3479
-                );
3480
-            }
3481
-            foreach ($sub_query_params as $param) {
3482
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3483
-                $this->_extract_related_model_info_from_query_param(
3484
-                    $param,
3485
-                    $model_query_info_carrier,
3486
-                    $query_param_type
3487
-                );
3488
-            }
3489
-        }
3490
-        return $model_query_info_carrier;
3491
-    }
3492
-
3493
-
3494
-    /**
3495
-     * Extract all the query parts from  model query params
3496
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3497
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3498
-     * but use them in a different order. Eg, we need to know what models we are querying
3499
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3500
-     * other models before we can finalize the where clause SQL.
3501
-     *
3502
-     * @param array $query_params
3503
-     * @return EE_Model_Query_Info_Carrier
3504
-     * @throws EE_Error
3505
-     * @throws ModelConfigurationException
3506
-     * @throws ReflectionException
3507
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3508
-     */
3509
-    public function _create_model_query_info_carrier($query_params)
3510
-    {
3511
-        if (! is_array($query_params)) {
3512
-            EE_Error::doing_it_wrong(
3513
-                'EEM_Base::_create_model_query_info_carrier',
3514
-                sprintf(
3515
-                    esc_html__(
3516
-                        '$query_params should be an array, you passed a variable of type %s',
3517
-                        'event_espresso'
3518
-                    ),
3519
-                    gettype($query_params)
3520
-                ),
3521
-                '4.6.0'
3522
-            );
3523
-            $query_params = [];
3524
-        }
3525
-        $query_params[0] = $query_params[0] ?? [];
3526
-        // first check if we should alter the query to account for caps or not
3527
-        // because the caps might require us to do extra joins
3528
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3529
-            $query_params[0] = array_replace_recursive(
3530
-                $query_params[0],
3531
-                $this->caps_where_conditions($query_params['caps'])
3532
-            );
3533
-        }
3534
-
3535
-        // check if we should alter the query to remove data related to protected
3536
-        // custom post types
3537
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3538
-            $where_param_key_for_password = $this->modelChainAndPassword();
3539
-            // only include if related to a cpt where no password has been set
3540
-            $query_params[0]['OR*nopassword'] = [
3541
-                $where_param_key_for_password       => '',
3542
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3543
-            ];
3544
-        }
3545
-        $query_object = $this->_extract_related_models_from_query($query_params);
3546
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3547
-        foreach ($query_params[0] as $key => $value) {
3548
-            if (is_int($key)) {
3549
-                throw new EE_Error(
3550
-                    sprintf(
3551
-                        esc_html__(
3552
-                            "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.",
3553
-                            "event_espresso"
3554
-                        ),
3555
-                        $key,
3556
-                        var_export($value, true),
3557
-                        var_export($query_params, true),
3558
-                        get_class($this)
3559
-                    )
3560
-                );
3561
-            }
3562
-        }
3563
-        if (
3564
-            array_key_exists('default_where_conditions', $query_params)
3565
-            && ! empty($query_params['default_where_conditions'])
3566
-        ) {
3567
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3568
-        } else {
3569
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3570
-        }
3571
-        $query_params[0] = array_merge(
3572
-            $this->_get_default_where_conditions_for_models_in_query(
3573
-                $query_object,
3574
-                $use_default_where_conditions,
3575
-                $query_params[0]
3576
-            ),
3577
-            $query_params[0]
3578
-        );
3579
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3580
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3581
-        // So we need to setup a subquery and use that for the main join.
3582
-        // Note for now this only works on the primary table for the model.
3583
-        // So for instance, you could set the limit array like this:
3584
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3585
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3586
-            $query_object->set_main_model_join_sql(
3587
-                $this->_construct_limit_join_select(
3588
-                    $query_params['on_join_limit'][0],
3589
-                    $query_params['on_join_limit'][1]
3590
-                )
3591
-            );
3592
-        }
3593
-        // set limit
3594
-        if (array_key_exists('limit', $query_params)) {
3595
-            if (is_array($query_params['limit'])) {
3596
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3597
-                    $e = sprintf(
3598
-                        esc_html__(
3599
-                            "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)",
3600
-                            "event_espresso"
3601
-                        ),
3602
-                        http_build_query($query_params['limit'])
3603
-                    );
3604
-                    throw new EE_Error($e . "|" . $e);
3605
-                }
3606
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3607
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3608
-            } elseif (! empty($query_params['limit'])) {
3609
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3610
-            }
3611
-        }
3612
-        // set order by
3613
-        if (array_key_exists('order_by', $query_params)) {
3614
-            if (is_array($query_params['order_by'])) {
3615
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3616
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3617
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3618
-                if (array_key_exists('order', $query_params)) {
3619
-                    throw new EE_Error(
3620
-                        sprintf(
3621
-                            esc_html__(
3622
-                                "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 ",
3623
-                                "event_espresso"
3624
-                            ),
3625
-                            get_class($this),
3626
-                            implode(", ", array_keys($query_params['order_by'])),
3627
-                            implode(", ", $query_params['order_by']),
3628
-                            $query_params['order']
3629
-                        )
3630
-                    );
3631
-                }
3632
-                $this->_extract_related_models_from_sub_params_array_keys(
3633
-                    $query_params['order_by'],
3634
-                    $query_object,
3635
-                    'order_by'
3636
-                );
3637
-                // assume it's an array of fields to order by
3638
-                $order_array = [];
3639
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3640
-                    $order         = $this->_extract_order($order);
3641
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3642
-                }
3643
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3644
-            } elseif (! empty($query_params['order_by'])) {
3645
-                $this->_extract_related_model_info_from_query_param(
3646
-                    $query_params['order_by'],
3647
-                    $query_object,
3648
-                    'order',
3649
-                    $query_params['order_by']
3650
-                );
3651
-                $order = isset($query_params['order'])
3652
-                    ? $this->_extract_order($query_params['order'])
3653
-                    : 'DESC';
3654
-                $query_object->set_order_by_sql(
3655
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3656
-                );
3657
-            }
3658
-        }
3659
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3660
-        if (
3661
-            ! array_key_exists('order_by', $query_params)
3662
-            && array_key_exists('order', $query_params)
3663
-            && ! empty($query_params['order'])
3664
-        ) {
3665
-            $pk_field = $this->get_primary_key_field();
3666
-            $order    = $this->_extract_order($query_params['order']);
3667
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3668
-        }
3669
-        // set group by
3670
-        if (array_key_exists('group_by', $query_params)) {
3671
-            if (is_array($query_params['group_by'])) {
3672
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3673
-                $group_by_array = [];
3674
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3675
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3676
-                }
3677
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3678
-            } elseif (! empty($query_params['group_by'])) {
3679
-                $query_object->set_group_by_sql(
3680
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3681
-                );
3682
-            }
3683
-        }
3684
-        // set having
3685
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3686
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3687
-        }
3688
-        // now, just verify they didn't pass anything wack
3689
-        foreach ($query_params as $query_key => $query_value) {
3690
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3691
-                throw new EE_Error(
3692
-                    sprintf(
3693
-                        esc_html__(
3694
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3695
-                            'event_espresso'
3696
-                        ),
3697
-                        $query_key,
3698
-                        get_class($this),
3699
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3700
-                        implode(',', $this->_allowed_query_params)
3701
-                    )
3702
-                );
3703
-            }
3704
-        }
3705
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3706
-        if (empty($main_model_join_sql)) {
3707
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3708
-        }
3709
-        return $query_object;
3710
-    }
3711
-
3712
-
3713
-    /**
3714
-     * Gets the where conditions that should be imposed on the query based on the
3715
-     * context (eg reading frontend, backend, edit or delete).
3716
-     *
3717
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3718
-     * @return array @see
3719
-     *                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3720
-     * @throws EE_Error
3721
-     */
3722
-    public function caps_where_conditions($context = self::caps_read)
3723
-    {
3724
-        EEM_Base::verify_is_valid_cap_context($context);
3725
-        $cap_where_conditions = [];
3726
-        $cap_restrictions     = $this->caps_missing($context);
3727
-        foreach ($cap_restrictions as $restriction_if_no_cap) {
3728
-            $cap_where_conditions = array_replace_recursive(
3729
-                $cap_where_conditions,
3730
-                $restriction_if_no_cap->get_default_where_conditions()
3731
-            );
3732
-        }
3733
-        return apply_filters(
3734
-            'FHEE__EEM_Base__caps_where_conditions__return',
3735
-            $cap_where_conditions,
3736
-            $this,
3737
-            $context,
3738
-            $cap_restrictions
3739
-        );
3740
-    }
3741
-
3742
-
3743
-    /**
3744
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3745
-     * otherwise throws an exception
3746
-     *
3747
-     * @param string $should_be_order_string
3748
-     * @return string either ASC, asc, DESC or desc
3749
-     * @throws EE_Error
3750
-     */
3751
-    private function _extract_order($should_be_order_string)
3752
-    {
3753
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3754
-            return $should_be_order_string;
3755
-        }
3756
-        throw new EE_Error(
3757
-            sprintf(
3758
-                esc_html__(
3759
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3760
-                    "event_espresso"
3761
-                ),
3762
-                get_class($this),
3763
-                $should_be_order_string
3764
-            )
3765
-        );
3766
-    }
3767
-
3768
-
3769
-    /**
3770
-     * Looks at all the models which are included in this query, and asks each
3771
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3772
-     * so they can be merged
3773
-     *
3774
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3775
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3776
-     *                                                                  'none' means NO default where conditions will
3777
-     *                                                                  be used AT ALL during this query.
3778
-     *                                                                  'other_models_only' means default where
3779
-     *                                                                  conditions from other models will be used, but
3780
-     *                                                                  not for this primary model. 'all', the default,
3781
-     *                                                                  means default where conditions will apply as
3782
-     *                                                                  normal
3783
-     * @param array                       $where_query_params
3784
-     * @return array
3785
-     * @throws EE_Error
3786
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params
3787
-     *                                                                  .md#0-where-conditions
3788
-     */
3789
-    private function _get_default_where_conditions_for_models_in_query(
3790
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3791
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3792
-        $where_query_params = []
3793
-    ) {
3794
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3795
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3796
-            throw new EE_Error(
3797
-                sprintf(
3798
-                    esc_html__(
3799
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3800
-                        "event_espresso"
3801
-                    ),
3802
-                    $use_default_where_conditions,
3803
-                    implode(", ", $allowed_used_default_where_conditions_values)
3804
-                )
3805
-            );
3806
-        }
3807
-        $universal_query_params = [];
3808
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3809
-            $universal_query_params = $this->_get_default_where_conditions();
3810
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3811
-            $universal_query_params = $this->_get_minimum_where_conditions();
3812
-        }
3813
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3814
-            $related_model = $this->get_related_model_obj($model_name);
3815
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3816
-                $related_model_universal_where_params =
3817
-                    $related_model->_get_default_where_conditions($model_relation_path);
3818
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3819
-                $related_model_universal_where_params =
3820
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3821
-            } else {
3822
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3823
-                continue;
3824
-            }
3825
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3826
-                $related_model_universal_where_params,
3827
-                $where_query_params,
3828
-                $related_model,
3829
-                $model_relation_path
3830
-            );
3831
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3832
-                $universal_query_params,
3833
-                $overrides
3834
-            );
3835
-        }
3836
-        return $universal_query_params;
3837
-    }
3838
-
3839
-
3840
-    /**
3841
-     * Determines whether or not we should use default where conditions for the model in question
3842
-     * (this model, or other related models).
3843
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3844
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3845
-     * We should use default where conditions on related models when they requested to use default where conditions
3846
-     * on all models, or specifically just on other related models
3847
-     *
3848
-     * @param      $default_where_conditions_value
3849
-     * @param bool $for_this_model false means this is for OTHER related models
3850
-     * @return bool
3851
-     */
3852
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3853
-    {
3854
-        return (
3855
-                   $for_this_model
3856
-                   && in_array(
3857
-                       $default_where_conditions_value,
3858
-                       [
3859
-                           EEM_Base::default_where_conditions_all,
3860
-                           EEM_Base::default_where_conditions_this_only,
3861
-                           EEM_Base::default_where_conditions_minimum_others,
3862
-                       ],
3863
-                       true
3864
-                   )
3865
-               )
3866
-               || (
3867
-                   ! $for_this_model
3868
-                   && in_array(
3869
-                       $default_where_conditions_value,
3870
-                       [
3871
-                           EEM_Base::default_where_conditions_all,
3872
-                           EEM_Base::default_where_conditions_others_only,
3873
-                       ],
3874
-                       true
3875
-                   )
3876
-               );
3877
-    }
3878
-
3879
-
3880
-    /**
3881
-     * Determines whether or not we should use default minimum conditions for the model in question
3882
-     * (this model, or other related models).
3883
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3884
-     * where conditions.
3885
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3886
-     * on this model or others
3887
-     *
3888
-     * @param      $default_where_conditions_value
3889
-     * @param bool $for_this_model false means this is for OTHER related models
3890
-     * @return bool
3891
-     */
3892
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3893
-    {
3894
-        return (
3895
-                   $for_this_model
3896
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3897
-               )
3898
-               || (
3899
-                   ! $for_this_model
3900
-                   && in_array(
3901
-                       $default_where_conditions_value,
3902
-                       [
3903
-                           EEM_Base::default_where_conditions_minimum_others,
3904
-                           EEM_Base::default_where_conditions_minimum_all,
3905
-                       ],
3906
-                       true
3907
-                   )
3908
-               );
3909
-    }
3910
-
3911
-
3912
-    /**
3913
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3914
-     * then we also add a special where condition which allows for that model's primary key
3915
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3916
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3917
-     *
3918
-     * @param array    $default_where_conditions
3919
-     * @param array    $provided_where_conditions
3920
-     * @param EEM_Base $model
3921
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3922
-     * @return array @see
3923
-     *                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3924
-     * @throws EE_Error
3925
-     */
3926
-    private function _override_defaults_or_make_null_friendly(
3927
-        $default_where_conditions,
3928
-        $provided_where_conditions,
3929
-        $model,
3930
-        $model_relation_path
3931
-    ) {
3932
-        $null_friendly_where_conditions = [];
3933
-        $none_overridden                = true;
3934
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3935
-        foreach ($default_where_conditions as $key => $val) {
3936
-            if (isset($provided_where_conditions[ $key ])) {
3937
-                $none_overridden = false;
3938
-            } else {
3939
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3940
-            }
3941
-        }
3942
-        if ($none_overridden && $default_where_conditions) {
3943
-            if ($model->has_primary_key_field()) {
3944
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3945
-                                                                                   . "."
3946
-                                                                                   . $model->primary_key_name() ] =
3947
-                    ['IS NULL'];
3948
-            }/*else{
40
+	/**
41
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
42
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
43
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
44
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
45
+	 *
46
+	 * @var boolean
47
+	 */
48
+	private $_values_already_prepared_by_model_object = 0;
49
+
50
+	/**
51
+	 * when $_values_already_prepared_by_model_object equals this, we assume
52
+	 * the data is just like form input that needs to have the model fields'
53
+	 * prepare_for_set and prepare_for_use_in_db called on it
54
+	 */
55
+	const not_prepared_by_model_object = 0;
56
+
57
+	/**
58
+	 * when $_values_already_prepared_by_model_object equals this, we
59
+	 * assume this value is coming from a model object and doesn't need to have
60
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
61
+	 */
62
+	const prepared_by_model_object = 1;
63
+
64
+	/**
65
+	 * when $_values_already_prepared_by_model_object equals this, we assume
66
+	 * the values are already to be used in the database (ie no processing is done
67
+	 * on them by the model's fields)
68
+	 */
69
+	const prepared_for_use_in_db = 2;
70
+
71
+
72
+	protected $singular_item = 'Item';
73
+
74
+	protected $plural_item   = 'Items';
75
+
76
+	/**
77
+	 * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
78
+	 */
79
+	protected $_tables;
80
+
81
+	/**
82
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
83
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
84
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
85
+	 *
86
+	 * @var EE_Model_Field_Base[][] $_fields
87
+	 */
88
+	protected $_fields;
89
+
90
+	/**
91
+	 * array of different kinds of relations
92
+	 *
93
+	 * @var EE_Model_Relation_Base[] $_model_relations
94
+	 */
95
+	protected $_model_relations = [];
96
+
97
+	/**
98
+	 * @var EE_Index[] $_indexes
99
+	 */
100
+	protected $_indexes = [];
101
+
102
+	/**
103
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
104
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
105
+	 * by setting the same columns as used in these queries in the query yourself.
106
+	 *
107
+	 * @var EE_Default_Where_Conditions
108
+	 */
109
+	protected $_default_where_conditions_strategy;
110
+
111
+	/**
112
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
113
+	 * This is particularly useful when you want something between 'none' and 'default'
114
+	 *
115
+	 * @var EE_Default_Where_Conditions
116
+	 */
117
+	protected $_minimum_where_conditions_strategy;
118
+
119
+	/**
120
+	 * String describing how to find the "owner" of this model's objects.
121
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
122
+	 * But when there isn't, this indicates which related model, or transiently-related model,
123
+	 * has the foreign key to the wp_users table.
124
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
125
+	 * related to events, and events have a foreign key to wp_users.
126
+	 * On EEM_Transaction, this would be 'Transaction.Event'
127
+	 *
128
+	 * @var string
129
+	 */
130
+	protected $_model_chain_to_wp_user = '';
131
+
132
+	/**
133
+	 * String describing how to find the model with a password controlling access to this model. This property has the
134
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
135
+	 * This value is the path of models to follow to arrive at the model with the password field.
136
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
137
+	 * model with a password that should affect reading this on the front-end.
138
+	 * Eg this is an empty string for the Event model because it has a password.
139
+	 * This is null for the Registration model, because its event's password has no bearing on whether
140
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
141
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
142
+	 * should hide tickets for datetimes for events that have a password set.
143
+	 *
144
+	 * @var string |null
145
+	 */
146
+	protected $model_chain_to_password = null;
147
+
148
+	/**
149
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
150
+	 * don't need it (particularly CPT models)
151
+	 *
152
+	 * @var bool
153
+	 */
154
+	protected $_ignore_where_strategy = false;
155
+
156
+	/**
157
+	 * String used in caps relating to this model. Eg, if the caps relating to this
158
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
159
+	 *
160
+	 * @var string. If null it hasn't been initialized yet. If false then we
161
+	 * have indicated capabilities don't apply to this
162
+	 */
163
+	protected $_caps_slug = null;
164
+
165
+	/**
166
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
167
+	 * and next-level keys are capability names, and each's value is a
168
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
169
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
170
+	 * and then each capability in the corresponding sub-array that they're missing
171
+	 * adds the where conditions onto the query.
172
+	 *
173
+	 * @var array
174
+	 */
175
+	protected $_cap_restrictions = [
176
+		self::caps_read       => [],
177
+		self::caps_read_admin => [],
178
+		self::caps_edit       => [],
179
+		self::caps_delete     => [],
180
+	];
181
+
182
+	/**
183
+	 * Array defining which cap restriction generators to use to create default
184
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
185
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
186
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
187
+	 * automatically set this to false (not just null).
188
+	 *
189
+	 * @var EE_Restriction_Generator_Base[]
190
+	 */
191
+	protected $_cap_restriction_generators = [];
192
+
193
+	/**
194
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
195
+	 */
196
+	const caps_read       = 'read';
197
+
198
+	const caps_read_admin = 'read_admin';
199
+
200
+	const caps_edit       = 'edit';
201
+
202
+	const caps_delete     = 'delete';
203
+
204
+	/**
205
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
206
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
207
+	 * maps to 'read' because when looking for relevant permissions we're going to use
208
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
209
+	 *
210
+	 * @var array
211
+	 */
212
+	protected $_cap_contexts_to_cap_action_map = [
213
+		self::caps_read       => 'read',
214
+		self::caps_read_admin => 'read',
215
+		self::caps_edit       => 'edit',
216
+		self::caps_delete     => 'delete',
217
+	];
218
+
219
+	/**
220
+	 * Timezone
221
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
222
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
223
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
224
+	 * EE_Datetime_Field data type will have access to it.
225
+	 *
226
+	 * @var string
227
+	 */
228
+	protected $_timezone;
229
+
230
+
231
+	/**
232
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
233
+	 * multisite.
234
+	 *
235
+	 * @var int
236
+	 */
237
+	protected static $_model_query_blog_id;
238
+
239
+	/**
240
+	 * A copy of _fields, except the array keys are the model names pointed to by
241
+	 * the field
242
+	 *
243
+	 * @var EE_Model_Field_Base[]
244
+	 */
245
+	private $_cache_foreign_key_to_fields = [];
246
+
247
+	/**
248
+	 * Cached list of all the fields on the model, indexed by their name
249
+	 *
250
+	 * @var EE_Model_Field_Base[]
251
+	 */
252
+	private $_cached_fields = null;
253
+
254
+	/**
255
+	 * Cached list of all the fields on the model, except those that are
256
+	 * marked as only pertinent to the database
257
+	 *
258
+	 * @var EE_Model_Field_Base[]
259
+	 */
260
+	private $_cached_fields_non_db_only = null;
261
+
262
+	/**
263
+	 * A cached reference to the primary key for quick lookup
264
+	 *
265
+	 * @var EE_Model_Field_Base
266
+	 */
267
+	private $_primary_key_field = null;
268
+
269
+	/**
270
+	 * Flag indicating whether this model has a primary key or not
271
+	 *
272
+	 * @var boolean
273
+	 */
274
+	protected $_has_primary_key_field = null;
275
+
276
+	/**
277
+	 * array in the format:  [ FK alias => full PK ]
278
+	 * where keys are local column name aliases for foreign keys
279
+	 * and values are the fully qualified column name for the primary key they represent
280
+	 *  ex:
281
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
282
+	 *
283
+	 * @var array $foreign_key_aliases
284
+	 */
285
+	protected $foreign_key_aliases = [];
286
+
287
+	/**
288
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
289
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
290
+	 * This should be true for models that deal with data that should exist independent of EE.
291
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
292
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
293
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
294
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
295
+	 *
296
+	 * @var boolean
297
+	 */
298
+	protected $_wp_core_model = false;
299
+
300
+	/**
301
+	 * @var bool stores whether this model has a password field or not.
302
+	 * null until initialized by hasPasswordField()
303
+	 */
304
+	protected $has_password_field;
305
+
306
+	/**
307
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
308
+	 */
309
+	protected $password_field;
310
+
311
+	/**
312
+	 *    List of valid operators that can be used for querying.
313
+	 * The keys are all operators we'll accept, the values are the real SQL
314
+	 * operators used
315
+	 *
316
+	 * @var array
317
+	 */
318
+	protected $_valid_operators = [
319
+		'='           => '=',
320
+		'<='          => '<=',
321
+		'<'           => '<',
322
+		'>='          => '>=',
323
+		'>'           => '>',
324
+		'!='          => '!=',
325
+		'LIKE'        => 'LIKE',
326
+		'like'        => 'LIKE',
327
+		'NOT_LIKE'    => 'NOT LIKE',
328
+		'not_like'    => 'NOT LIKE',
329
+		'NOT LIKE'    => 'NOT LIKE',
330
+		'not like'    => 'NOT LIKE',
331
+		'IN'          => 'IN',
332
+		'in'          => 'IN',
333
+		'NOT_IN'      => 'NOT IN',
334
+		'not_in'      => 'NOT IN',
335
+		'NOT IN'      => 'NOT IN',
336
+		'not in'      => 'NOT IN',
337
+		'between'     => 'BETWEEN',
338
+		'BETWEEN'     => 'BETWEEN',
339
+		'IS_NOT_NULL' => 'IS NOT NULL',
340
+		'is_not_null' => 'IS NOT NULL',
341
+		'IS NOT NULL' => 'IS NOT NULL',
342
+		'is not null' => 'IS NOT NULL',
343
+		'IS_NULL'     => 'IS NULL',
344
+		'is_null'     => 'IS NULL',
345
+		'IS NULL'     => 'IS NULL',
346
+		'is null'     => 'IS NULL',
347
+		'REGEXP'      => 'REGEXP',
348
+		'regexp'      => 'REGEXP',
349
+		'NOT_REGEXP'  => 'NOT REGEXP',
350
+		'not_regexp'  => 'NOT REGEXP',
351
+		'NOT REGEXP'  => 'NOT REGEXP',
352
+		'not regexp'  => 'NOT REGEXP',
353
+	];
354
+
355
+	/**
356
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
357
+	 *
358
+	 * @var array
359
+	 */
360
+	protected $_in_style_operators = ['IN', 'NOT IN'];
361
+
362
+	/**
363
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
364
+	 * '12-31-2012'"
365
+	 *
366
+	 * @var array
367
+	 */
368
+	protected $_between_style_operators = ['BETWEEN'];
369
+
370
+	/**
371
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
372
+	 *
373
+	 * @var array
374
+	 */
375
+	protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
376
+
377
+	/**
378
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
379
+	 * on a join table.
380
+	 *
381
+	 * @var array
382
+	 */
383
+	protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
384
+
385
+	/**
386
+	 * Allowed values for $query_params['order'] for ordering in queries
387
+	 *
388
+	 * @var array
389
+	 */
390
+	protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
391
+
392
+	/**
393
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
394
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
395
+	 *
396
+	 * @var array
397
+	 */
398
+	private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
399
+
400
+	/**
401
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
402
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
403
+	 *
404
+	 * @var array
405
+	 */
406
+	private $_allowed_query_params = [
407
+		0,
408
+		'limit',
409
+		'order_by',
410
+		'group_by',
411
+		'having',
412
+		'force_join',
413
+		'order',
414
+		'on_join_limit',
415
+		'default_where_conditions',
416
+		'caps',
417
+		'extra_selects',
418
+		'exclude_protected',
419
+	];
420
+
421
+	/**
422
+	 * All the data types that can be used in $wpdb->prepare statements.
423
+	 *
424
+	 * @var array
425
+	 */
426
+	private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
427
+
428
+	/**
429
+	 * @var EE_Registry $EE
430
+	 */
431
+	protected $EE = null;
432
+
433
+
434
+	/**
435
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
436
+	 *
437
+	 * @var int
438
+	 */
439
+	protected $_show_next_x_db_queries = 0;
440
+
441
+	/**
442
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
443
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
444
+	 * WHERE, GROUP_BY, etc.
445
+	 *
446
+	 * @var CustomSelects
447
+	 */
448
+	protected $_custom_selections = [];
449
+
450
+	/**
451
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
452
+	 * caches every model object we've fetched from the DB on this request
453
+	 *
454
+	 * @var array
455
+	 */
456
+	protected $_entity_map;
457
+
458
+	/**
459
+	 * @var LoaderInterface
460
+	 */
461
+	protected static $loader;
462
+
463
+	/**
464
+	 * @var Mirror
465
+	 */
466
+	private static $mirror;
467
+
468
+
469
+	/**
470
+	 * constant used to show EEM_Base has not yet verified the db on this http request
471
+	 */
472
+	const db_verified_none = 0;
473
+
474
+	/**
475
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
476
+	 * but not the addons' dbs
477
+	 */
478
+	const db_verified_core = 1;
479
+
480
+	/**
481
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
482
+	 * the EE core db too)
483
+	 */
484
+	const db_verified_addons = 2;
485
+
486
+	/**
487
+	 * indicates whether an EEM_Base child has already re-verified the DB
488
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
489
+	 * looking like EEM_Base::db_verified_*
490
+	 *
491
+	 * @var int - 0 = none, 1 = core, 2 = addons
492
+	 */
493
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
494
+
495
+	/**
496
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
497
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
498
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
499
+	 */
500
+	const default_where_conditions_all = 'all';
501
+
502
+	/**
503
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
504
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
505
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
506
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
507
+	 *        models which share tables with other models, this can return data for the wrong model.
508
+	 */
509
+	const default_where_conditions_this_only = 'this_model_only';
510
+
511
+	/**
512
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
513
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
514
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
515
+	 */
516
+	const default_where_conditions_others_only = 'other_models_only';
517
+
518
+	/**
519
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
520
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
521
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
522
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
523
+	 *        (regardless of whether those events and venues are trashed)
524
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
525
+	 *        events.
526
+	 */
527
+	const default_where_conditions_minimum_all = 'minimum';
528
+
529
+	/**
530
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
531
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
532
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
533
+	 *        not)
534
+	 */
535
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
536
+
537
+	/**
538
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
539
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
540
+	 *        it's possible it will return table entries for other models. You should use
541
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
542
+	 */
543
+	const default_where_conditions_none = 'none';
544
+
545
+
546
+	/**
547
+	 * About all child constructors:
548
+	 * they should define the _tables, _fields and _model_relations arrays.
549
+	 * Should ALWAYS be called after child constructor.
550
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
551
+	 * finalizes constructing all the object's attributes.
552
+	 * Generally, rather than requiring a child to code
553
+	 * $this->_tables = array(
554
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
555
+	 *        ...);
556
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
557
+	 * each EE_Table has a function to set the table's alias after the constructor, using
558
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
559
+	 * do something similar.
560
+	 *
561
+	 * @param string|null $timezone
562
+	 * @throws EE_Error
563
+	 * @throws Exception
564
+	 */
565
+	protected function __construct($timezone = '')
566
+	{
567
+		// check that the model has not been loaded too soon
568
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
569
+			throw new EE_Error(
570
+				sprintf(
571
+					esc_html__(
572
+						'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.',
573
+						'event_espresso'
574
+					),
575
+					get_class($this)
576
+				)
577
+			);
578
+		}
579
+		/**
580
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
581
+		 */
582
+		if (empty(EEM_Base::$_model_query_blog_id)) {
583
+			EEM_Base::set_model_query_blog_id();
584
+		}
585
+		/**
586
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
587
+		 * just use EE_Register_Model_Extension
588
+		 *
589
+		 * @var EE_Table_Base[] $_tables
590
+		 */
591
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
592
+		foreach ($this->_tables as $table_alias => $table_obj) {
593
+			/** @var $table_obj EE_Table_Base */
594
+			$table_obj->_construct_finalize_with_alias($table_alias);
595
+			if ($table_obj instanceof EE_Secondary_Table) {
596
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
597
+			}
598
+		}
599
+		/**
600
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
601
+		 * EE_Register_Model_Extension
602
+		 *
603
+		 * @param EE_Model_Field_Base[] $_fields
604
+		 */
605
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
606
+		$this->_invalidate_field_caches();
607
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
608
+			if (! array_key_exists($table_alias, $this->_tables)) {
609
+				throw new EE_Error(
610
+					sprintf(
611
+						esc_html__(
612
+							"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
613
+							'event_espresso'
614
+						),
615
+						$table_alias,
616
+						implode(",", $this->_fields)
617
+					)
618
+				);
619
+			}
620
+			foreach ($fields_for_table as $field_name => $field_obj) {
621
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
622
+				// primary key field base has a slightly different _construct_finalize
623
+				/** @var $field_obj EE_Model_Field_Base */
624
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
625
+			}
626
+		}
627
+		// everything is related to Extra_Meta
628
+		if (get_class($this) !== 'EEM_Extra_Meta') {
629
+			// make extra meta related to everything, but don't block deleting things just
630
+			// because they have related extra meta info. For now just orphan those extra meta
631
+			// in the future we should automatically delete them
632
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
633
+		}
634
+		// and change logs
635
+		if (get_class($this) !== 'EEM_Change_Log') {
636
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
637
+		}
638
+		/**
639
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
640
+		 * EE_Register_Model_Extension
641
+		 *
642
+		 * @param EE_Model_Relation_Base[] $_model_relations
643
+		 */
644
+		$this->_model_relations = (array) apply_filters(
645
+			'FHEE__' . get_class($this) . '__construct__model_relations',
646
+			$this->_model_relations
647
+		);
648
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
649
+			/** @var $relation_obj EE_Model_Relation_Base */
650
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
651
+		}
652
+		foreach ($this->_indexes as $index_name => $index_obj) {
653
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
654
+		}
655
+		$this->set_timezone($timezone);
656
+		// finalize default where condition strategy, or set default
657
+		if (! $this->_default_where_conditions_strategy) {
658
+			// nothing was set during child constructor, so set default
659
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
660
+		}
661
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
662
+		if (! $this->_minimum_where_conditions_strategy) {
663
+			// nothing was set during child constructor, so set default
664
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
665
+		}
666
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
667
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
668
+		// to indicate to NOT set it, set it to the logical default
669
+		if ($this->_caps_slug === null) {
670
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
671
+		}
672
+		// initialize the standard cap restriction generators if none were specified by the child constructor
673
+		if (is_array($this->_cap_restriction_generators)) {
674
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
675
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
676
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
677
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
678
+						new EE_Restriction_Generator_Protected(),
679
+						$cap_context,
680
+						$this
681
+					);
682
+				}
683
+			}
684
+		}
685
+		// if there are cap restriction generators, use them to make the default cap restrictions
686
+		if (is_array($this->_cap_restriction_generators)) {
687
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
688
+				if (! $generator_object) {
689
+					continue;
690
+				}
691
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
692
+					throw new EE_Error(
693
+						sprintf(
694
+							esc_html__(
695
+								'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.',
696
+								'event_espresso'
697
+							),
698
+							$context,
699
+							$this->get_this_model_name()
700
+						)
701
+					);
702
+				}
703
+				$action = $this->cap_action_for_context($context);
704
+				if (! $generator_object->construction_finalized()) {
705
+					$generator_object->_construct_finalize($this, $action);
706
+				}
707
+			}
708
+		}
709
+		do_action('AHEE__' . get_class($this) . '__construct__end');
710
+	}
711
+
712
+
713
+	/**
714
+	 * @return LoaderInterface
715
+	 * @throws InvalidArgumentException
716
+	 * @throws InvalidDataTypeException
717
+	 * @throws InvalidInterfaceException
718
+	 */
719
+	protected static function getLoader(): LoaderInterface
720
+	{
721
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
722
+			EEM_Base::$loader = LoaderFactory::getLoader();
723
+		}
724
+		return EEM_Base::$loader;
725
+	}
726
+
727
+
728
+	/**
729
+	 * @return Mirror
730
+	 * @since   5.0.0.p
731
+	 */
732
+	private static function getMirror(): Mirror
733
+	{
734
+		if (! EEM_Base::$mirror instanceof Mirror) {
735
+			EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
736
+		}
737
+		return EEM_Base::$mirror;
738
+	}
739
+
740
+
741
+	/**
742
+	 * @param string $model_class_Name
743
+	 * @param string $timezone
744
+	 * @return array
745
+	 * @throws ReflectionException
746
+	 * @since   5.0.0.p
747
+	 */
748
+	private static function getModelArguments(string $model_class_Name, string $timezone): array
749
+	{
750
+		$arguments = [$timezone];
751
+		$params    = EEM_Base::getMirror()->getParameters($model_class_Name);
752
+		if (count($params) > 1) {
753
+			if ($params[1]->getName() === 'model_field_factory') {
754
+				$arguments = [
755
+					$timezone,
756
+					EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
757
+				];
758
+			} elseif ($model_class_Name === 'EEM_Form_Section') {
759
+				$arguments = [
760
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
761
+					$timezone,
762
+				];
763
+			} elseif ($model_class_Name === 'EEM_Form_Element') {
764
+				$arguments = [
765
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
766
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
767
+					$timezone,
768
+				];
769
+			}
770
+		}
771
+		return $arguments;
772
+	}
773
+
774
+
775
+	/**
776
+	 * This function is a singleton method used to instantiate the Espresso_model object
777
+	 *
778
+	 * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
779
+	 *                                (and any incoming timezone data that gets saved).
780
+	 *                                Note this just sends the timezone info to the date time model field objects.
781
+	 *                                Default is NULL
782
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
783
+	 * @return static (as in the concrete child class)
784
+	 * @throws EE_Error
785
+	 * @throws ReflectionException
786
+	 */
787
+	public static function instance($timezone = '')
788
+	{
789
+		// check if instance of Espresso_model already exists
790
+		if (! static::$_instance instanceof static) {
791
+			$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
792
+			$model     = new static(...$arguments);
793
+			EEM_Base::getLoader()->share(static::class, $model, $arguments);
794
+			static::$_instance = $model;
795
+		}
796
+		// we might have a timezone set, let set_timezone decide what to do with it
797
+		if ($timezone) {
798
+			static::$_instance->set_timezone($timezone);
799
+		}
800
+		// Espresso_model object
801
+		return static::$_instance;
802
+	}
803
+
804
+
805
+	/**
806
+	 * resets the model and returns it
807
+	 *
808
+	 * @param string|null $timezone
809
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
810
+	 * all its properties reset; if it wasn't instantiated, returns null)
811
+	 * @throws EE_Error
812
+	 * @throws ReflectionException
813
+	 * @throws InvalidArgumentException
814
+	 * @throws InvalidDataTypeException
815
+	 * @throws InvalidInterfaceException
816
+	 */
817
+	public static function reset($timezone = '')
818
+	{
819
+		if (! static::$_instance instanceof EEM_Base) {
820
+			return null;
821
+		}
822
+		// Let's NOT swap out the current instance for a new one
823
+		// because if someone has a reference to it, we can't remove their reference.
824
+		// It's best to keep using the same reference but change the original object instead,
825
+		// so reset all its properties to their original values as defined in the class.
826
+		$static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
827
+		foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
828
+			// don't set instance to null like it was originally,
829
+			// but it's static anyways, and we're ignoring static properties (for now at least)
830
+			if (! isset($static_properties[ $property ])) {
831
+				static::$_instance->{$property} = $value;
832
+			}
833
+		}
834
+		// and then directly call its constructor again, like we would if we were creating a new one
835
+		$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
836
+		static::$_instance->__construct(...$arguments);
837
+		return self::instance();
838
+	}
839
+
840
+
841
+	/**
842
+	 * Used to set the $_model_query_blog_id static property.
843
+	 *
844
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
845
+	 *                      value for get_current_blog_id() will be used.
846
+	 */
847
+	public static function set_model_query_blog_id($blog_id = 0)
848
+	{
849
+		EEM_Base::$_model_query_blog_id = $blog_id > 0
850
+			? (int) $blog_id
851
+			: get_current_blog_id();
852
+	}
853
+
854
+
855
+	/**
856
+	 * Returns whatever is set as the internal $model_query_blog_id.
857
+	 *
858
+	 * @return int
859
+	 */
860
+	public static function get_model_query_blog_id()
861
+	{
862
+		return EEM_Base::$_model_query_blog_id;
863
+	}
864
+
865
+
866
+	/**
867
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
868
+	 *
869
+	 * @param boolean $translated return localized strings or JUST the array.
870
+	 * @return array
871
+	 * @throws EE_Error
872
+	 * @throws InvalidArgumentException
873
+	 * @throws InvalidDataTypeException
874
+	 * @throws InvalidInterfaceException
875
+	 * @throws ReflectionException
876
+	 */
877
+	public function status_array($translated = false)
878
+	{
879
+		if (! array_key_exists('Status', $this->_model_relations)) {
880
+			return [];
881
+		}
882
+		$model_name   = $this->get_this_model_name();
883
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
884
+		$stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
885
+		$status_array = [];
886
+		foreach ($stati as $status) {
887
+			$status_array[ $status->ID() ] = $status->get('STS_code');
888
+		}
889
+		return $translated
890
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
891
+			: $status_array;
892
+	}
893
+
894
+
895
+	/**
896
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
897
+	 *
898
+	 * @param array $query_params             @see
899
+	 *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
900
+	 *                                        or if you have the development copy of EE you can view this at the path:
901
+	 *                                        /docs/G--Model-System/model-query-params.md
902
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
903
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
904
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
905
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
906
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
907
+	 *                                        'OR'=>array(
908
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
909
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
910
+	 *                                        )
911
+	 *                                        ),
912
+	 *                                        'limit'=>10,
913
+	 *                                        'group_by'=>'TXN_ID'
914
+	 *                                        ));
915
+	 *                                        get all the answers to the question titled "shirt size" for event with id
916
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
917
+	 *                                        'Question.QST_display_text'=>'shirt size',
918
+	 *                                        'Registration.Event.EVT_ID'=>12
919
+	 *                                        ),
920
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
921
+	 *                                        ));
922
+	 * @throws EE_Error
923
+	 * @throws ReflectionException
924
+	 */
925
+	public function get_all($query_params = [])
926
+	{
927
+		if (
928
+			isset($query_params['limit'])
929
+			&& ! isset($query_params['group_by'])
930
+		) {
931
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
932
+		}
933
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
934
+	}
935
+
936
+
937
+	/**
938
+	 * Modifies the query parameters so we only get back model objects
939
+	 * that "belong" to the current user
940
+	 *
941
+	 * @param array $query_params @see
942
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
943
+	 * @return array @see
944
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
945
+	 * @throws ReflectionException
946
+	 * @throws ReflectionException
947
+	 */
948
+	public function alter_query_params_to_only_include_mine($query_params = [])
949
+	{
950
+		$wp_user_field_name = $this->wp_user_field_name();
951
+		if ($wp_user_field_name) {
952
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
953
+		}
954
+		return $query_params;
955
+	}
956
+
957
+
958
+	/**
959
+	 * Returns the name of the field's name that points to the WP_User table
960
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
+	 * foreign key to the WP_User table)
962
+	 *
963
+	 * @return string|boolean string on success, boolean false when there is no
964
+	 * foreign key to the WP_User table
965
+	 * @throws ReflectionException
966
+	 * @throws ReflectionException
967
+	 */
968
+	public function wp_user_field_name()
969
+	{
970
+		try {
971
+			if (! empty($this->_model_chain_to_wp_user)) {
972
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
973
+				$last_model_name              = end($models_to_follow_to_wp_users);
974
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
975
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
976
+			} else {
977
+				$model_with_fk_to_wp_users = $this;
978
+				$model_chain_to_wp_user    = '';
979
+			}
980
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
981
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
982
+		} catch (EE_Error $e) {
983
+			return false;
984
+		}
985
+	}
986
+
987
+
988
+	/**
989
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
990
+	 * (or transiently-related model) has a foreign key to the wp_users table;
991
+	 * useful for finding if model objects of this type are 'owned' by the current user.
992
+	 * This is an empty string when the foreign key is on this model and when it isn't,
993
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
994
+	 * (or transiently-related model)
995
+	 *
996
+	 * @return string
997
+	 */
998
+	public function model_chain_to_wp_user()
999
+	{
1000
+		return $this->_model_chain_to_wp_user;
1001
+	}
1002
+
1003
+
1004
+	/**
1005
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
+	 * like how registrations don't have a foreign key to wp_users, but the
1007
+	 * events they are for are), or is unrelated to wp users.
1008
+	 * generally available
1009
+	 *
1010
+	 * @return boolean
1011
+	 */
1012
+	public function is_owned()
1013
+	{
1014
+		if ($this->model_chain_to_wp_user()) {
1015
+			return true;
1016
+		}
1017
+		try {
1018
+			$this->get_foreign_key_to('WP_User');
1019
+			return true;
1020
+		} catch (EE_Error $e) {
1021
+			return false;
1022
+		}
1023
+	}
1024
+
1025
+
1026
+	/**
1027
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1028
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1029
+	 * the model)
1030
+	 *
1031
+	 * @param array  $query_params      @see
1032
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1033
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1034
+	 * @param mixed  $columns_to_select What columns to select. By default, we select all columns specified by the
1035
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1036
+	 *                                  override this and set the select to "*", or a specific column name, like
1037
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1038
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1039
+	 *                                  the aliases used to refer to this selection, and values are to be
1040
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1041
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1042
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1043
+	 * @throws EE_Error
1044
+	 * @throws InvalidArgumentException
1045
+	 * @throws ReflectionException
1046
+	 */
1047
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1048
+	{
1049
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1050
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1051
+		$select_expressions       = $columns_to_select === null
1052
+			? $this->_construct_default_select_sql($model_query_info)
1053
+			: '';
1054
+		if ($this->_custom_selections instanceof CustomSelects) {
1055
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1056
+			$select_expressions .= $select_expressions
1057
+				? ', ' . $custom_expressions
1058
+				: $custom_expressions;
1059
+		}
1060
+
1061
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1062
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1063
+	}
1064
+
1065
+
1066
+	/**
1067
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1068
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1069
+	 * method of including extra select information.
1070
+	 *
1071
+	 * @param array             $query_params
1072
+	 * @param null|array|string $columns_to_select
1073
+	 * @return null|CustomSelects
1074
+	 * @throws InvalidArgumentException
1075
+	 */
1076
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1077
+	{
1078
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1079
+			return null;
1080
+		}
1081
+		$selects = $query_params['extra_selects'] ?? $columns_to_select;
1082
+		$selects = is_string($selects)
1083
+			? explode(',', $selects)
1084
+			: $selects;
1085
+		return new CustomSelects($selects);
1086
+	}
1087
+
1088
+
1089
+	/**
1090
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1091
+	 * but you can use the model query params to more easily
1092
+	 * take care of joins, field preparation etc.
1093
+	 *
1094
+	 * @param array  $query_params      @see
1095
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1096
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1097
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1098
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1099
+	 *                                  override this and set the select to "*", or a specific column name, like
1100
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1101
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1102
+	 *                                  the aliases used to refer to this selection, and values are to be
1103
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1104
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1105
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1106
+	 * @throws EE_Error
1107
+	 * @throws ReflectionException
1108
+	 */
1109
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1110
+	{
1111
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1112
+	}
1113
+
1114
+
1115
+	/**
1116
+	 * For creating a custom select statement
1117
+	 *
1118
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1119
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1120
+	 *                                 SQL, and 1=>is the datatype
1121
+	 * @return string
1122
+	 * @throws EE_Error
1123
+	 */
1124
+	private function _construct_select_from_input($columns_to_select)
1125
+	{
1126
+		if (is_array($columns_to_select)) {
1127
+			$select_sql_array = [];
1128
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1129
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1130
+					throw new EE_Error(
1131
+						sprintf(
1132
+							esc_html__(
1133
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1134
+								'event_espresso'
1135
+							),
1136
+							$selection_and_datatype,
1137
+							$alias
1138
+						)
1139
+					);
1140
+				}
1141
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1142
+					throw new EE_Error(
1143
+						sprintf(
1144
+							esc_html__(
1145
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1146
+								'event_espresso'
1147
+							),
1148
+							$selection_and_datatype[1],
1149
+							$selection_and_datatype[0],
1150
+							$alias,
1151
+							implode(', ', $this->_valid_wpdb_data_types)
1152
+						)
1153
+					);
1154
+				}
1155
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1156
+			}
1157
+			$columns_to_select_string = implode(', ', $select_sql_array);
1158
+		} else {
1159
+			$columns_to_select_string = $columns_to_select;
1160
+		}
1161
+		return $columns_to_select_string;
1162
+	}
1163
+
1164
+
1165
+	/**
1166
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1167
+	 *
1168
+	 * @return string
1169
+	 * @throws EE_Error
1170
+	 */
1171
+	public function primary_key_name()
1172
+	{
1173
+		return $this->get_primary_key_field()->get_name();
1174
+	}
1175
+
1176
+
1177
+	/**
1178
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1179
+	 * If there is no primary key on this model, $id is treated as primary key string
1180
+	 *
1181
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1182
+	 * @return EE_Base_Class|mixed|null
1183
+	 * @throws EE_Error
1184
+	 * @throws ReflectionException
1185
+	 */
1186
+	public function get_one_by_ID($id)
1187
+	{
1188
+		if ($this->get_from_entity_map($id)) {
1189
+			return $this->get_from_entity_map($id);
1190
+		}
1191
+		$model_object = $this->get_one(
1192
+			$this->alter_query_params_to_restrict_by_ID(
1193
+				$id,
1194
+				['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1195
+			)
1196
+		);
1197
+		$className    = $this->_get_class_name();
1198
+		if ($model_object instanceof $className) {
1199
+			// make sure valid objects get added to the entity map
1200
+			// so that the next call to this method doesn't trigger another trip to the db
1201
+			$this->add_to_entity_map($model_object);
1202
+		}
1203
+		return $model_object;
1204
+	}
1205
+
1206
+
1207
+	/**
1208
+	 * Alters query parameters to only get items with this ID are returned.
1209
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1210
+	 * or could just be a simple primary key ID
1211
+	 *
1212
+	 * @param int   $id
1213
+	 * @param array $query_params
1214
+	 * @return array of normal query params, @see
1215
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1216
+	 * @throws EE_Error
1217
+	 */
1218
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1219
+	{
1220
+		if (! isset($query_params[0])) {
1221
+			$query_params[0] = [];
1222
+		}
1223
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1224
+		if ($conditions_from_id === null) {
1225
+			$query_params[0][ $this->primary_key_name() ] = $id;
1226
+		} else {
1227
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1228
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1229
+		}
1230
+		return $query_params;
1231
+	}
1232
+
1233
+
1234
+	/**
1235
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1236
+	 * array. If no item is found, null is returned.
1237
+	 *
1238
+	 * @param array $query_params like EEM_Base's $query_params variable.
1239
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1240
+	 * @throws EE_Error
1241
+	 * @throws ReflectionException
1242
+	 */
1243
+	public function get_one($query_params = [])
1244
+	{
1245
+		if (! is_array($query_params)) {
1246
+			EE_Error::doing_it_wrong(
1247
+				'EEM_Base::get_one',
1248
+				sprintf(
1249
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1250
+					gettype($query_params)
1251
+				),
1252
+				'4.6.0'
1253
+			);
1254
+			$query_params = [];
1255
+		}
1256
+		$query_params['limit'] = 1;
1257
+		$items                 = $this->get_all($query_params);
1258
+		if (empty($items)) {
1259
+			return null;
1260
+		}
1261
+		return array_shift($items);
1262
+	}
1263
+
1264
+
1265
+	/**
1266
+	 * Returns the next x number of items in sequence from the given value as
1267
+	 * found in the database matching the given query conditions.
1268
+	 *
1269
+	 * @param mixed $current_field_value    Value used for the reference point.
1270
+	 * @param null  $field_to_order_by      What field is used for the
1271
+	 *                                      reference point.
1272
+	 * @param int   $limit                  How many to return.
1273
+	 * @param array $query_params           Extra conditions on the query.
1274
+	 * @param null  $columns_to_select      If left null, then an array of
1275
+	 *                                      EE_Base_Class objects is returned,
1276
+	 *                                      otherwise you can indicate just the
1277
+	 *                                      columns you want returned.
1278
+	 * @return EE_Base_Class[]|array
1279
+	 * @throws EE_Error
1280
+	 * @throws ReflectionException
1281
+	 */
1282
+	public function next_x(
1283
+		$current_field_value,
1284
+		$field_to_order_by = null,
1285
+		$limit = 1,
1286
+		$query_params = [],
1287
+		$columns_to_select = null
1288
+	) {
1289
+		return $this->_get_consecutive(
1290
+			$current_field_value,
1291
+			'>',
1292
+			$field_to_order_by,
1293
+			$limit,
1294
+			$query_params,
1295
+			$columns_to_select
1296
+		);
1297
+	}
1298
+
1299
+
1300
+	/**
1301
+	 * Returns the previous x number of items in sequence from the given value
1302
+	 * as found in the database matching the given query conditions.
1303
+	 *
1304
+	 * @param mixed $current_field_value    Value used for the reference point.
1305
+	 * @param null  $field_to_order_by      What field is used for the
1306
+	 *                                      reference point.
1307
+	 * @param int   $limit                  How many to return.
1308
+	 * @param array $query_params           Extra conditions on the query.
1309
+	 * @param null  $columns_to_select      If left null, then an array of
1310
+	 *                                      EE_Base_Class objects is returned,
1311
+	 *                                      otherwise you can indicate just the
1312
+	 *                                      columns you want returned.
1313
+	 * @return EE_Base_Class[]|array
1314
+	 * @throws EE_Error
1315
+	 * @throws ReflectionException
1316
+	 */
1317
+	public function previous_x(
1318
+		$current_field_value,
1319
+		$field_to_order_by = null,
1320
+		$limit = 1,
1321
+		$query_params = [],
1322
+		$columns_to_select = null
1323
+	) {
1324
+		return $this->_get_consecutive(
1325
+			$current_field_value,
1326
+			'<',
1327
+			$field_to_order_by,
1328
+			$limit,
1329
+			$query_params,
1330
+			$columns_to_select
1331
+		);
1332
+	}
1333
+
1334
+
1335
+	/**
1336
+	 * Returns the next item in sequence from the given value as found in the
1337
+	 * database matching the given query conditions.
1338
+	 *
1339
+	 * @param mixed $current_field_value    Value used for the reference point.
1340
+	 * @param null  $field_to_order_by      What field is used for the
1341
+	 *                                      reference point.
1342
+	 * @param array $query_params           Extra conditions on the query.
1343
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1344
+	 *                                      object is returned, otherwise you
1345
+	 *                                      can indicate just the columns you
1346
+	 *                                      want and a single array indexed by
1347
+	 *                                      the columns will be returned.
1348
+	 * @return EE_Base_Class|null|array()
1349
+	 * @throws EE_Error
1350
+	 * @throws ReflectionException
1351
+	 */
1352
+	public function next(
1353
+		$current_field_value,
1354
+		$field_to_order_by = null,
1355
+		$query_params = [],
1356
+		$columns_to_select = null
1357
+	) {
1358
+		$results = $this->_get_consecutive(
1359
+			$current_field_value,
1360
+			'>',
1361
+			$field_to_order_by,
1362
+			1,
1363
+			$query_params,
1364
+			$columns_to_select
1365
+		);
1366
+		return empty($results)
1367
+			? null
1368
+			: reset($results);
1369
+	}
1370
+
1371
+
1372
+	/**
1373
+	 * Returns the previous item in sequence from the given value as found in
1374
+	 * the database matching the given query conditions.
1375
+	 *
1376
+	 * @param mixed $current_field_value    Value used for the reference point.
1377
+	 * @param null  $field_to_order_by      What field is used for the
1378
+	 *                                      reference point.
1379
+	 * @param array $query_params           Extra conditions on the query.
1380
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1381
+	 *                                      object is returned, otherwise you
1382
+	 *                                      can indicate just the columns you
1383
+	 *                                      want and a single array indexed by
1384
+	 *                                      the columns will be returned.
1385
+	 * @return EE_Base_Class|null|array()
1386
+	 * @throws EE_Error
1387
+	 * @throws ReflectionException
1388
+	 */
1389
+	public function previous(
1390
+		$current_field_value,
1391
+		$field_to_order_by = null,
1392
+		$query_params = [],
1393
+		$columns_to_select = null
1394
+	) {
1395
+		$results = $this->_get_consecutive(
1396
+			$current_field_value,
1397
+			'<',
1398
+			$field_to_order_by,
1399
+			1,
1400
+			$query_params,
1401
+			$columns_to_select
1402
+		);
1403
+		return empty($results)
1404
+			? null
1405
+			: reset($results);
1406
+	}
1407
+
1408
+
1409
+	/**
1410
+	 * Returns the a consecutive number of items in sequence from the given
1411
+	 * value as found in the database matching the given query conditions.
1412
+	 *
1413
+	 * @param mixed  $current_field_value   Value used for the reference point.
1414
+	 * @param string $operand               What operand is used for the sequence.
1415
+	 * @param string $field_to_order_by     What field is used for the reference point.
1416
+	 * @param int    $limit                 How many to return.
1417
+	 * @param array  $query_params          Extra conditions on the query.
1418
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1419
+	 *                                      otherwise you can indicate just the columns you want returned.
1420
+	 * @return EE_Base_Class[]|array
1421
+	 * @throws EE_Error
1422
+	 * @throws ReflectionException
1423
+	 */
1424
+	protected function _get_consecutive(
1425
+		$current_field_value,
1426
+		$operand = '>',
1427
+		$field_to_order_by = null,
1428
+		$limit = 1,
1429
+		$query_params = [],
1430
+		$columns_to_select = null
1431
+	) {
1432
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1433
+		if (empty($field_to_order_by)) {
1434
+			if ($this->has_primary_key_field()) {
1435
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1436
+			} else {
1437
+				if (WP_DEBUG) {
1438
+					throw new EE_Error(
1439
+						esc_html__(
1440
+							'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).',
1441
+							'event_espresso'
1442
+						)
1443
+					);
1444
+				}
1445
+				EE_Error::add_error(
1446
+					esc_html__('There was an error with the query.', 'event_espresso'),
1447
+					__FILE__,
1448
+					__FUNCTION__,
1449
+					__LINE__
1450
+				);
1451
+				return [];
1452
+			}
1453
+		}
1454
+		if (! is_array($query_params)) {
1455
+			EE_Error::doing_it_wrong(
1456
+				'EEM_Base::_get_consecutive',
1457
+				sprintf(
1458
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1459
+					gettype($query_params)
1460
+				),
1461
+				'4.6.0'
1462
+			);
1463
+			$query_params = [];
1464
+		}
1465
+		// let's add the where query param for consecutive look up.
1466
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1467
+		$query_params['limit']                 = $limit;
1468
+		// set direction
1469
+		$incoming_orderby         = isset($query_params['order_by'])
1470
+			? (array) $query_params['order_by']
1471
+			: [];
1472
+		$query_params['order_by'] = $operand === '>'
1473
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1474
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1475
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1476
+		if (empty($columns_to_select)) {
1477
+			return $this->get_all($query_params);
1478
+		}
1479
+		// getting just the fields
1480
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1481
+	}
1482
+
1483
+
1484
+	/**
1485
+	 * This sets the _timezone property after model object has been instantiated.
1486
+	 *
1487
+	 * @param string|null $timezone valid PHP DateTimeZone timezone string
1488
+	 * @throws Exception
1489
+	 */
1490
+	public function set_timezone(?string $timezone = '')
1491
+	{
1492
+		if (! $timezone) {
1493
+			return;
1494
+		}
1495
+		$this->_timezone = $timezone;
1496
+		// note we need to loop through relations and set the timezone on those objects as well.
1497
+		foreach ($this->_model_relations as $relation) {
1498
+			$relation->set_timezone($timezone);
1499
+		}
1500
+		// and finally we do the same for any datetime fields
1501
+		foreach ($this->_fields as $field) {
1502
+			if ($field instanceof EE_Datetime_Field) {
1503
+				$field->set_timezone($timezone);
1504
+			}
1505
+		}
1506
+	}
1507
+
1508
+
1509
+	/**
1510
+	 * This just returns whatever is set for the current timezone.
1511
+	 *
1512
+	 * @access public
1513
+	 * @return string
1514
+	 * @throws Exception
1515
+	 */
1516
+	public function get_timezone()
1517
+	{
1518
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1519
+		if (empty($this->_timezone)) {
1520
+			foreach ($this->_fields as $field) {
1521
+				if ($field instanceof EE_Datetime_Field) {
1522
+					$this->set_timezone($field->get_timezone());
1523
+					break;
1524
+				}
1525
+			}
1526
+		}
1527
+		// if timezone STILL empty then return the default timezone for the site.
1528
+		if (empty($this->_timezone)) {
1529
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1530
+		}
1531
+		return $this->_timezone;
1532
+	}
1533
+
1534
+
1535
+	/**
1536
+	 * This returns the date formats set for the given field name and also ensures that
1537
+	 * $this->_timezone property is set correctly.
1538
+	 *
1539
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1540
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1541
+	 * @return array formats in an array with the date format first, and the time format last.
1542
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1543
+	 * @since 4.6.x
1544
+	 */
1545
+	public function get_formats_for($field_name, $pretty = false)
1546
+	{
1547
+		$field_settings = $this->field_settings_for($field_name);
1548
+		// if not a valid EE_Datetime_Field then throw error
1549
+		if (! $field_settings instanceof EE_Datetime_Field) {
1550
+			throw new EE_Error(
1551
+				sprintf(
1552
+					esc_html__(
1553
+						'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.',
1554
+						'event_espresso'
1555
+					),
1556
+					$field_name
1557
+				)
1558
+			);
1559
+		}
1560
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1561
+		// the field.
1562
+		$this->_timezone = $field_settings->get_timezone();
1563
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1564
+	}
1565
+
1566
+
1567
+	/**
1568
+	 * This returns the current time in a format setup for a query on this model.
1569
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1570
+	 * it will return:
1571
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1572
+	 *  NOW
1573
+	 *  - or a unix timestamp (equivalent to time())
1574
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1575
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1576
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1577
+	 *
1578
+	 * @param string $field_name       The field the current time is needed for.
1579
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1580
+	 *                                 formatted string matching the set format for the field in the set timezone will
1581
+	 *                                 be returned.
1582
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1583
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1584
+	 *                                 exception is triggered.
1585
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1586
+	 * @throws Exception
1587
+	 * @since 4.6.x
1588
+	 */
1589
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1590
+	{
1591
+		$formats  = $this->get_formats_for($field_name);
1592
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1593
+		if ($timestamp) {
1594
+			return $DateTime->format('U');
1595
+		}
1596
+		// not returning timestamp, so return formatted string in timezone.
1597
+		switch ($what) {
1598
+			case 'time':
1599
+				return $DateTime->format($formats[1]);
1600
+			case 'date':
1601
+				return $DateTime->format($formats[0]);
1602
+			default:
1603
+				return $DateTime->format(implode(' ', $formats));
1604
+		}
1605
+	}
1606
+
1607
+
1608
+	/**
1609
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1610
+	 * for the model are.  Returns a DateTime object.
1611
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1612
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1613
+	 * ignored.
1614
+	 *
1615
+	 * @param string      $field_name      The field being setup.
1616
+	 * @param string      $timestring      The date time string being used.
1617
+	 * @param string      $incoming_format The format for the time string.
1618
+	 * @param string|null $timezone        By default, it is assumed the incoming time string is in timezone for
1619
+	 *                                     the blog.  If this is not the case, then it can be specified here.  If
1620
+	 *                                     incoming format is
1621
+	 *                                     'U', this is ignored.
1622
+	 * @return DateTime
1623
+	 * @throws EE_Error
1624
+	 * @throws Exception
1625
+	 */
1626
+	public function convert_datetime_for_query(
1627
+		string $field_name,
1628
+		string $timestring,
1629
+		string $incoming_format,
1630
+		?string $timezone = ''
1631
+	) {
1632
+		// just using this to ensure the timezone is set correctly internally
1633
+		$this->get_formats_for($field_name);
1634
+		// load EEH_DTT_Helper
1635
+		$set_timezone     = empty($timezone)
1636
+			? EEH_DTT_Helper::get_timezone()
1637
+			: $timezone;
1638
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1639
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1640
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1641
+	}
1642
+
1643
+
1644
+	/**
1645
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1646
+	 *
1647
+	 * @return EE_Table_Base[]
1648
+	 */
1649
+	public function get_tables()
1650
+	{
1651
+		return $this->_tables;
1652
+	}
1653
+
1654
+
1655
+	/**
1656
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1657
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1658
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1659
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1660
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1661
+	 * model object with EVT_ID = 1
1662
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1663
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1664
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1665
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1666
+	 * are not specified)
1667
+	 *
1668
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1669
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1670
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1671
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1672
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1673
+	 *                                         ID=34, we'd use this method as follows:
1674
+	 *                                         EEM_Transaction::instance()->update(
1675
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1676
+	 *                                         array(array('TXN_ID'=>34)));
1677
+	 * @param array   $query_params            @see
1678
+	 *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1679
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1680
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1681
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1682
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1683
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1684
+	 *                                         TRUE, it is assumed that you've already called
1685
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1686
+	 *                                         malicious javascript. However, if
1687
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1688
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1689
+	 *                                         and every other field, before insertion. We provide this parameter
1690
+	 *                                         because model objects perform their prepare_for_set function on all
1691
+	 *                                         their values, and so don't need to be called again (and in many cases,
1692
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1693
+	 *                                         prepare_for_set method...)
1694
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1695
+	 *                                         in this model's entity map according to $fields_n_values that match
1696
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1697
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1698
+	 *                                         could get out-of-sync with the database
1699
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1700
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1701
+	 *                                         bad)
1702
+	 * @throws EE_Error
1703
+	 * @throws ReflectionException
1704
+	 */
1705
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1706
+	{
1707
+		if (! is_array($query_params)) {
1708
+			EE_Error::doing_it_wrong(
1709
+				'EEM_Base::update',
1710
+				sprintf(
1711
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1712
+					gettype($query_params)
1713
+				),
1714
+				'4.6.0'
1715
+			);
1716
+			$query_params = [];
1717
+		}
1718
+		/**
1719
+		 * Action called before a model update call has been made.
1720
+		 *
1721
+		 * @param EEM_Base $model
1722
+		 * @param array    $fields_n_values the updated fields and their new values
1723
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1724
+		 */
1725
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1726
+		/**
1727
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1728
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1729
+		 *
1730
+		 * @param array    $fields_n_values fields and their new values
1731
+		 * @param EEM_Base $model           the model being queried
1732
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1733
+		 */
1734
+		$fields_n_values = (array) apply_filters(
1735
+			'FHEE__EEM_Base__update__fields_n_values',
1736
+			$fields_n_values,
1737
+			$this,
1738
+			$query_params
1739
+		);
1740
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1741
+		// to do that, for each table, verify that it's PK isn't null.
1742
+		$tables = $this->get_tables();
1743
+		// 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
1744
+		// NOTE: we should make this code more efficient by NOT querying twice
1745
+		// before the real update, but that needs to first go through ALPHA testing
1746
+		// as it's dangerous. says Mike August 8 2014
1747
+		// we want to make sure the default_where strategy is ignored
1748
+		$this->_ignore_where_strategy = true;
1749
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1750
+		foreach ($wpdb_select_results as $wpdb_result) {
1751
+			// type cast stdClass as array
1752
+			$wpdb_result = (array) $wpdb_result;
1753
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1754
+			if ($this->has_primary_key_field()) {
1755
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1756
+			} else {
1757
+				// 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)
1758
+				$main_table_pk_value = null;
1759
+			}
1760
+			// 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
1761
+			// 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
1762
+			if (count($tables) > 1) {
1763
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1764
+				// in that table, and so we'll want to insert one
1765
+				foreach ($tables as $table_obj) {
1766
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1767
+					// if there is no private key for this table on the results, it means there's no entry
1768
+					// in this table, right? so insert a row in the current table, using any fields available
1769
+					if (
1770
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1771
+						   && $wpdb_result[ $this_table_pk_column ])
1772
+					) {
1773
+						$success = $this->_insert_into_specific_table(
1774
+							$table_obj,
1775
+							$fields_n_values,
1776
+							$main_table_pk_value
1777
+						);
1778
+						// if we died here, report the error
1779
+						if (! $success) {
1780
+							return false;
1781
+						}
1782
+					}
1783
+				}
1784
+			}
1785
+			//              //and now check that if we have cached any models by that ID on the model, that
1786
+			//              //they also get updated properly
1787
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1788
+			//              if( $model_object ){
1789
+			//                  foreach( $fields_n_values as $field => $value ){
1790
+			//                      $model_object->set($field, $value);
1791
+			// let's make sure default_where strategy is followed now
1792
+			$this->_ignore_where_strategy = false;
1793
+		}
1794
+		// if we want to keep model objects in sync, AND
1795
+		// if this wasn't called from a model object (to update itself)
1796
+		// then we want to make sure we keep all the existing
1797
+		// model objects in sync with the db
1798
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1799
+			if ($this->has_primary_key_field()) {
1800
+				$model_objs_affected_ids = $this->get_col($query_params);
1801
+			} else {
1802
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1803
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1804
+				$model_objs_affected_ids     = [];
1805
+				foreach ($models_affected_key_columns as $row) {
1806
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1807
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1808
+				}
1809
+			}
1810
+			if (! $model_objs_affected_ids) {
1811
+				// wait wait wait- if nothing was affected let's stop here
1812
+				return 0;
1813
+			}
1814
+			foreach ($model_objs_affected_ids as $id) {
1815
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1816
+				if ($model_obj_in_entity_map) {
1817
+					foreach ($fields_n_values as $field => $new_value) {
1818
+						$model_obj_in_entity_map->set($field, $new_value);
1819
+					}
1820
+				}
1821
+			}
1822
+			// if there is a primary key on this model, we can now do a slight optimization
1823
+			if ($this->has_primary_key_field()) {
1824
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1825
+				$query_params = [
1826
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1827
+					'limit'                    => count($model_objs_affected_ids),
1828
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1829
+				];
1830
+			}
1831
+		}
1832
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1833
+
1834
+		// note: the following query doesn't use _construct_2nd_half_of_select_query()
1835
+		// because it doesn't accept LIMIT, ORDER BY, etc.
1836
+		$rows_affected = $this->_do_wpdb_query(
1837
+			'query',
1838
+			[
1839
+				"UPDATE " . $model_query_info->get_full_join_sql()
1840
+				. " SET " . $this->_construct_update_sql($fields_n_values)
1841
+				. $model_query_info->get_where_sql(),
1842
+			]
1843
+		);
1844
+
1845
+		/**
1846
+		 * Action called after a model update call has been made.
1847
+		 *
1848
+		 * @param EEM_Base $model
1849
+		 * @param array    $fields_n_values the updated fields and their new values
1850
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1851
+		 * @param int      $rows_affected
1852
+		 */
1853
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1854
+		return $rows_affected;// how many supposedly got updated
1855
+	}
1856
+
1857
+
1858
+	/**
1859
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1860
+	 * are teh values of the field specified (or by default the primary key field)
1861
+	 * that matched the query params. Note that you should pass the name of the
1862
+	 * model FIELD, not the database table's column name.
1863
+	 *
1864
+	 * @param array  $query_params @see
1865
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1866
+	 * @param string $field_to_select
1867
+	 * @return array just like $wpdb->get_col()
1868
+	 * @throws EE_Error
1869
+	 * @throws ReflectionException
1870
+	 */
1871
+	public function get_col($query_params = [], $field_to_select = null)
1872
+	{
1873
+		if ($field_to_select) {
1874
+			$field = $this->field_settings_for($field_to_select);
1875
+		} elseif ($this->has_primary_key_field()) {
1876
+			$field = $this->get_primary_key_field();
1877
+		} else {
1878
+			$field_settings = $this->field_settings();
1879
+			// no primary key, just grab the first column
1880
+			$field = reset($field_settings);
1881
+			// don't need this array now
1882
+			unset($field_settings);
1883
+		}
1884
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1885
+		$select_expressions = $field->get_qualified_column();
1886
+		$SQL                =
1887
+			"SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1888
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1889
+	}
1890
+
1891
+
1892
+	/**
1893
+	 * Returns a single column value for a single row from the database
1894
+	 *
1895
+	 * @param array  $query_params    @see
1896
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1897
+	 * @param string $field_to_select @see EEM_Base::get_col()
1898
+	 * @return string
1899
+	 * @throws EE_Error
1900
+	 * @throws ReflectionException
1901
+	 */
1902
+	public function get_var($query_params = [], $field_to_select = null)
1903
+	{
1904
+		$query_params['limit'] = 1;
1905
+		$col                   = $this->get_col($query_params, $field_to_select);
1906
+		if (! empty($col)) {
1907
+			return reset($col);
1908
+		}
1909
+		return null;
1910
+	}
1911
+
1912
+
1913
+	/**
1914
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1915
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1916
+	 * injection, but currently no further filtering is done
1917
+	 *
1918
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1919
+	 *                               be updated to in the DB
1920
+	 * @return string of SQL
1921
+	 * @throws EE_Error
1922
+	 * @global      $wpdb
1923
+	 */
1924
+	public function _construct_update_sql($fields_n_values)
1925
+	{
1926
+		/** @type WPDB $wpdb */
1927
+		global $wpdb;
1928
+		$cols_n_values = [];
1929
+		foreach ($fields_n_values as $field_name => $value) {
1930
+			$field_obj = $this->field_settings_for($field_name);
1931
+			// if the value is NULL, we want to assign the value to that.
1932
+			// wpdb->prepare doesn't really handle that properly
1933
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1934
+			$value_sql       = $prepared_value === null
1935
+				? 'NULL'
1936
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1937
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1938
+		}
1939
+		return implode(",", $cols_n_values);
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
+	 * Performs a HARD delete, meaning the database row should always be removed,
1946
+	 * not just have a flag field on it switched
1947
+	 * Wrapper for EEM_Base::delete_permanently()
1948
+	 *
1949
+	 * @param mixed   $id
1950
+	 * @param boolean $allow_blocking
1951
+	 * @return int the number of rows deleted
1952
+	 * @throws EE_Error
1953
+	 * @throws ReflectionException
1954
+	 */
1955
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1956
+	{
1957
+		return $this->delete_permanently(
1958
+			[
1959
+				[$this->get_primary_key_field()->get_name() => $id],
1960
+				'limit' => 1,
1961
+			],
1962
+			$allow_blocking
1963
+		);
1964
+	}
1965
+
1966
+
1967
+	/**
1968
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1969
+	 * Wrapper for EEM_Base::delete()
1970
+	 *
1971
+	 * @param mixed   $id
1972
+	 * @param boolean $allow_blocking
1973
+	 * @return int the number of rows deleted
1974
+	 * @throws EE_Error
1975
+	 * @throws ReflectionException
1976
+	 */
1977
+	public function delete_by_ID($id, $allow_blocking = true)
1978
+	{
1979
+		return $this->delete(
1980
+			[
1981
+				[$this->get_primary_key_field()->get_name() => $id],
1982
+				'limit' => 1,
1983
+			],
1984
+			$allow_blocking
1985
+		);
1986
+	}
1987
+
1988
+
1989
+	/**
1990
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1991
+	 * meaning if the model has a field that indicates its been "trashed" or
1992
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1993
+	 *
1994
+	 * @param array   $query_params
1995
+	 * @param boolean $allow_blocking
1996
+	 * @return int how many rows got deleted
1997
+	 * @throws EE_Error
1998
+	 * @throws ReflectionException
1999
+	 * @see EEM_Base::delete_permanently
2000
+	 */
2001
+	public function delete($query_params, $allow_blocking = true)
2002
+	{
2003
+		return $this->delete_permanently($query_params, $allow_blocking);
2004
+	}
2005
+
2006
+
2007
+	/**
2008
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
2009
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
2010
+	 * as archived, not actually deleted
2011
+	 *
2012
+	 * @param array   $query_params   @see
2013
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2014
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
2015
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
2016
+	 *                                deletes regardless of other objects which may depend on it. Its generally
2017
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
2018
+	 *                                DB
2019
+	 * @return int how many rows got deleted
2020
+	 * @throws EE_Error
2021
+	 * @throws ReflectionException
2022
+	 */
2023
+	public function delete_permanently($query_params, $allow_blocking = true)
2024
+	{
2025
+		/**
2026
+		 * Action called just before performing a real deletion query. You can use the
2027
+		 * model and its $query_params to find exactly which items will be deleted
2028
+		 *
2029
+		 * @param EEM_Base $model
2030
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2031
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
2032
+		 *                                 to block (prevent) this deletion
2033
+		 */
2034
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
2035
+		// some MySQL databases may be running safe mode, which may restrict
2036
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
2037
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
2038
+		// to delete them
2039
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2040
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2041
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2042
+			$columns_and_ids_for_deleting
2043
+		);
2044
+		/**
2045
+		 * Allows client code to act on the items being deleted before the query is actually executed.
2046
+		 *
2047
+		 * @param EEM_Base $this                            The model instance being acted on.
2048
+		 * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
2049
+		 * @param bool     $allow_blocking                  @see param description in method phpdoc block.
2050
+		 * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
2051
+		 *                                                  derived from the incoming query parameters.
2052
+		 * @see details on the structure of this array in the phpdocs
2053
+		 *                                                  for the `_get_ids_for_delete_method`
2054
+		 */
2055
+		do_action(
2056
+			'AHEE__EEM_Base__delete__before_query',
2057
+			$this,
2058
+			$query_params,
2059
+			$allow_blocking,
2060
+			$columns_and_ids_for_deleting
2061
+		);
2062
+		if ($deletion_where_query_part) {
2063
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2064
+			$table_aliases    = array_keys($this->_tables);
2065
+			$SQL              = "DELETE "
2066
+								. implode(", ", $table_aliases)
2067
+								. " FROM "
2068
+								. $model_query_info->get_full_join_sql()
2069
+								. " WHERE "
2070
+								. $deletion_where_query_part;
2071
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2072
+		} else {
2073
+			$rows_deleted = 0;
2074
+		}
2075
+
2076
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2077
+		// there was no error with the delete query.
2078
+		if (
2079
+			$this->has_primary_key_field()
2080
+			&& $rows_deleted !== false
2081
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2082
+		) {
2083
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2084
+			foreach ($ids_for_removal as $id) {
2085
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2086
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2087
+				}
2088
+			}
2089
+
2090
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2091
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2092
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2093
+			// (although it is possible).
2094
+			// Note this can be skipped by using the provided filter and returning false.
2095
+			if (
2096
+				apply_filters(
2097
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2098
+					! $this instanceof EEM_Extra_Meta,
2099
+					$this
2100
+				)
2101
+			) {
2102
+				EEM_Extra_Meta::instance()->delete_permanently(
2103
+					[
2104
+						0 => [
2105
+							'EXM_type' => $this->get_this_model_name(),
2106
+							'OBJ_ID'   => [
2107
+								'IN',
2108
+								$ids_for_removal,
2109
+							],
2110
+						],
2111
+					]
2112
+				);
2113
+			}
2114
+		}
2115
+
2116
+		/**
2117
+		 * Action called just after performing a real deletion query. Although at this point the
2118
+		 * items should have been deleted
2119
+		 *
2120
+		 * @param EEM_Base $model
2121
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2122
+		 * @param int      $rows_deleted
2123
+		 */
2124
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2125
+		return $rows_deleted;// how many supposedly got deleted
2126
+	}
2127
+
2128
+
2129
+	/**
2130
+	 * Checks all the relations that throw error messages when there are blocking related objects
2131
+	 * for related model objects. If there are any related model objects on those relations,
2132
+	 * adds an EE_Error, and return true
2133
+	 *
2134
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2135
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2136
+	 *                                                 should be ignored when determining whether there are related
2137
+	 *                                                 model objects which block this model object's deletion. Useful
2138
+	 *                                                 if you know A is related to B and are considering deleting A,
2139
+	 *                                                 but want to see if A has any other objects blocking its deletion
2140
+	 *                                                 before removing the relation between A and B
2141
+	 * @return boolean
2142
+	 * @throws EE_Error
2143
+	 * @throws ReflectionException
2144
+	 */
2145
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2146
+	{
2147
+		// first, if $ignore_this_model_obj was supplied, get its model
2148
+		$ignored_model = $ignore_this_model_obj instanceof EE_Base_Class
2149
+			? $ignore_this_model_obj->get_model()
2150
+			: null;
2151
+		// now check all the relations of $this_model_obj_or_id and see if there
2152
+		// are any related model objects blocking it?
2153
+		$is_blocked = false;
2154
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2155
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2156
+				// if $ignore_this_model_obj was supplied, then for the query
2157
+				// on that model needs to be told to ignore $ignore_this_model_obj
2158
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2159
+					$related_model_objects = $relation_obj->get_all_related(
2160
+						$this_model_obj_or_id,
2161
+						[
2162
+							[
2163
+								$ignored_model->get_primary_key_field()->get_name() => [
2164
+									'!=',
2165
+									$ignore_this_model_obj->ID(),
2166
+								],
2167
+							],
2168
+						]
2169
+					);
2170
+				} else {
2171
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2172
+				}
2173
+				if ($related_model_objects) {
2174
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2175
+					$is_blocked = true;
2176
+				}
2177
+			}
2178
+		}
2179
+		return $is_blocked;
2180
+	}
2181
+
2182
+
2183
+	/**
2184
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2185
+	 *
2186
+	 * @param array $row_results_for_deleting
2187
+	 * @param bool  $allow_blocking
2188
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2189
+	 *                              model DOES have a primary_key_field, then the array will be a simple single
2190
+	 *                              dimension array where the key is the fully qualified primary key column and the
2191
+	 *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2192
+	 *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2193
+	 *                              be a two dimensional array where each element is a group of columns and values that
2194
+	 *                              get deleted. Example: array(
2195
+	 *                              0 => array(
2196
+	 *                              'Term_Relationship.object_id' => 1
2197
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2198
+	 *                              ),
2199
+	 *                              1 => array(
2200
+	 *                              'Term_Relationship.object_id' => 1
2201
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2202
+	 *                              )
2203
+	 *                              )
2204
+	 * @throws EE_Error
2205
+	 * @throws ReflectionException
2206
+	 */
2207
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2208
+	{
2209
+		$ids_to_delete_indexed_by_column = [];
2210
+		if ($this->has_primary_key_field()) {
2211
+			$primary_table = $this->_get_main_table();
2212
+			// following lines are commented out because the variables were not being used
2213
+			// not deleting because unsure if calls were intentionally causing side effects
2214
+			// $primary_table_pk_field          =
2215
+			//     $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2216
+			// $other_tables                    = $this->_get_other_tables();
2217
+			$ids_to_delete_indexed_by_column = $query = [];
2218
+			foreach ($row_results_for_deleting as $item_to_delete) {
2219
+				// before we mark this item for deletion,
2220
+				// make sure there's no related entities blocking its deletion (if we're checking)
2221
+				if (
2222
+					$allow_blocking
2223
+					&& $this->delete_is_blocked_by_related_models(
2224
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2225
+					)
2226
+				) {
2227
+					continue;
2228
+				}
2229
+				// primary table deletes
2230
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2231
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2232
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2233
+				}
2234
+			}
2235
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2236
+			$fields = $this->get_combined_primary_key_fields();
2237
+			foreach ($row_results_for_deleting as $item_to_delete) {
2238
+				$ids_to_delete_indexed_by_column_for_row = [];
2239
+				foreach ($fields as $cpk_field) {
2240
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2241
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2242
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2243
+					}
2244
+				}
2245
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2246
+			}
2247
+		} else {
2248
+			// so there's no primary key and no combined key...
2249
+			// sorry, can't help you
2250
+			throw new EE_Error(
2251
+				sprintf(
2252
+					esc_html__(
2253
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2254
+						"event_espresso"
2255
+					),
2256
+					get_class($this)
2257
+				)
2258
+			);
2259
+		}
2260
+		return $ids_to_delete_indexed_by_column;
2261
+	}
2262
+
2263
+
2264
+	/**
2265
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2266
+	 * the corresponding query_part for the query performing the delete.
2267
+	 *
2268
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2269
+	 * @return string
2270
+	 * @throws EE_Error
2271
+	 */
2272
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2273
+	{
2274
+		$query_part = '';
2275
+		if (empty($ids_to_delete_indexed_by_column)) {
2276
+			return $query_part;
2277
+		} elseif ($this->has_primary_key_field()) {
2278
+			$query = [];
2279
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2280
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2281
+			}
2282
+			$query_part = ! empty($query)
2283
+				? implode(' AND ', $query)
2284
+				: $query_part;
2285
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2286
+			$ways_to_identify_a_row = [];
2287
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2288
+				$values_for_each_combined_primary_key_for_a_row = [];
2289
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2290
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2291
+				}
2292
+				$ways_to_identify_a_row[] = '('
2293
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2294
+											. ')';
2295
+			}
2296
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2297
+		}
2298
+		return $query_part;
2299
+	}
2300
+
2301
+
2302
+	/**
2303
+	 * Gets the model field by the fully qualified name
2304
+	 *
2305
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2306
+	 * @return EE_Model_Field_Base
2307
+	 * @throws EE_Error
2308
+	 * @throws EE_Error
2309
+	 */
2310
+	public function get_field_by_column($qualified_column_name)
2311
+	{
2312
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2313
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2314
+				return $field_obj;
2315
+			}
2316
+		}
2317
+		throw new EE_Error(
2318
+			sprintf(
2319
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2320
+				$this->get_this_model_name(),
2321
+				$qualified_column_name
2322
+			)
2323
+		);
2324
+	}
2325
+
2326
+
2327
+	/**
2328
+	 * Count all the rows that match criteria the model query params.
2329
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2330
+	 * column
2331
+	 *
2332
+	 * @param array  $query_params   @see
2333
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2334
+	 * @param string $field_to_count field on model to count by (not column name)
2335
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2336
+	 *                               that by the setting $distinct to TRUE;
2337
+	 * @return int
2338
+	 * @throws EE_Error
2339
+	 * @throws ReflectionException
2340
+	 */
2341
+	public function count($query_params = [], $field_to_count = null, $distinct = false)
2342
+	{
2343
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2344
+		if ($field_to_count) {
2345
+			$field_obj       = $this->field_settings_for($field_to_count);
2346
+			$column_to_count = $field_obj->get_qualified_column();
2347
+		} elseif ($this->has_primary_key_field()) {
2348
+			$pk_field_obj    = $this->get_primary_key_field();
2349
+			$column_to_count = $pk_field_obj->get_qualified_column();
2350
+		} else {
2351
+			// there's no primary key
2352
+			// if we're counting distinct items, and there's no primary key,
2353
+			// we need to list out the columns for distinction;
2354
+			// otherwise we can just use star
2355
+			if ($distinct) {
2356
+				$columns_to_use = [];
2357
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2358
+					$columns_to_use[] = $field_obj->get_qualified_column();
2359
+				}
2360
+				$column_to_count = implode(',', $columns_to_use);
2361
+			} else {
2362
+				$column_to_count = '*';
2363
+			}
2364
+		}
2365
+		$column_to_count = $distinct
2366
+			? "DISTINCT " . $column_to_count
2367
+			: $column_to_count;
2368
+		$SQL             =
2369
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2370
+		return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2371
+	}
2372
+
2373
+
2374
+	/**
2375
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2376
+	 *
2377
+	 * @param array  $query_params @see
2378
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2379
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2380
+	 * @return float
2381
+	 * @throws EE_Error
2382
+	 * @throws ReflectionException
2383
+	 */
2384
+	public function sum($query_params, $field_to_sum = null)
2385
+	{
2386
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2387
+		if ($field_to_sum) {
2388
+			$field_obj = $this->field_settings_for($field_to_sum);
2389
+		} else {
2390
+			$field_obj = $this->get_primary_key_field();
2391
+		}
2392
+		$column_to_count = $field_obj->get_qualified_column();
2393
+		$SQL             =
2394
+			"SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2395
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2396
+		$data_type       = $field_obj->get_wpdb_data_type();
2397
+		if ($data_type === '%d' || $data_type === '%s') {
2398
+			return (float) $return_value;
2399
+		}
2400
+		// must be %f
2401
+		return (float) $return_value;
2402
+	}
2403
+
2404
+
2405
+	/**
2406
+	 * Just calls the specified method on $wpdb with the given arguments
2407
+	 * Consolidates a little extra error handling code
2408
+	 *
2409
+	 * @param string $wpdb_method
2410
+	 * @param array  $arguments_to_provide
2411
+	 * @return mixed
2412
+	 * @throws EE_Error
2413
+	 * @global wpdb  $wpdb
2414
+	 */
2415
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2416
+	{
2417
+		// if we're in maintenance mode level 2, DON'T run any queries
2418
+		// because level 2 indicates the database needs updating and
2419
+		// is probably out of sync with the code
2420
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2421
+			throw new RuntimeException(
2422
+				esc_html__(
2423
+					"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.",
2424
+					"event_espresso"
2425
+				)
2426
+			);
2427
+		}
2428
+		/** @type WPDB $wpdb */
2429
+		global $wpdb;
2430
+		if (! method_exists($wpdb, $wpdb_method)) {
2431
+			throw new DomainException(
2432
+				sprintf(
2433
+					esc_html__(
2434
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2435
+						'event_espresso'
2436
+					),
2437
+					$wpdb_method
2438
+				)
2439
+			);
2440
+		}
2441
+		$old_show_errors_value = $wpdb->show_errors;
2442
+		if (WP_DEBUG) {
2443
+			$wpdb->show_errors(false);
2444
+		}
2445
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2446
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2447
+		if (WP_DEBUG) {
2448
+			$wpdb->show_errors($old_show_errors_value);
2449
+			if (! empty($wpdb->last_error)) {
2450
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2451
+			}
2452
+			if ($result === false) {
2453
+				throw new EE_Error(
2454
+					sprintf(
2455
+						esc_html__(
2456
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2457
+							'event_espresso'
2458
+						),
2459
+						$wpdb_method,
2460
+						var_export($arguments_to_provide, true)
2461
+					)
2462
+				);
2463
+			}
2464
+		} elseif ($result === false) {
2465
+			EE_Error::add_error(
2466
+				sprintf(
2467
+					esc_html__(
2468
+						'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"',
2469
+						'event_espresso'
2470
+					),
2471
+					$wpdb_method,
2472
+					var_export($arguments_to_provide, true),
2473
+					$wpdb->last_error
2474
+				),
2475
+				__FILE__,
2476
+				__FUNCTION__,
2477
+				__LINE__
2478
+			);
2479
+		}
2480
+		return $result;
2481
+	}
2482
+
2483
+
2484
+	/**
2485
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2486
+	 * and if there's an error tries to verify the DB is correct. Uses
2487
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2488
+	 * we should try to fix the EE core db, the addons, or just give up
2489
+	 *
2490
+	 * @param string $wpdb_method
2491
+	 * @param array  $arguments_to_provide
2492
+	 * @return mixed
2493
+	 */
2494
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2495
+	{
2496
+		/** @type WPDB $wpdb */
2497
+		global $wpdb;
2498
+		$wpdb->last_error = null;
2499
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2500
+		// was there an error running the query? but we don't care on new activations
2501
+		// (we're going to setup the DB anyway on new activations)
2502
+		if (
2503
+			($result === false || ! empty($wpdb->last_error))
2504
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2505
+		) {
2506
+			switch (EEM_Base::$_db_verification_level) {
2507
+				case EEM_Base::db_verified_none:
2508
+					// let's double-check core's DB
2509
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2510
+					break;
2511
+				case EEM_Base::db_verified_core:
2512
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2513
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2514
+					break;
2515
+				case EEM_Base::db_verified_addons:
2516
+					// ummmm... you in trouble
2517
+					return $result;
2518
+			}
2519
+			if (! empty($error_message)) {
2520
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2521
+				trigger_error($error_message);
2522
+			}
2523
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2524
+		}
2525
+		return $result;
2526
+	}
2527
+
2528
+
2529
+	/**
2530
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2531
+	 * EEM_Base::$_db_verification_level
2532
+	 *
2533
+	 * @param string $wpdb_method
2534
+	 * @param array  $arguments_to_provide
2535
+	 * @return string
2536
+	 * @throws EE_Error
2537
+	 * @throws ReflectionException
2538
+	 */
2539
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2540
+	{
2541
+		/** @type WPDB $wpdb */
2542
+		global $wpdb;
2543
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2544
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2545
+		$error_message                    = sprintf(
2546
+			esc_html__(
2547
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2548
+				'event_espresso'
2549
+			),
2550
+			$wpdb->last_error,
2551
+			$wpdb_method,
2552
+			wp_json_encode($arguments_to_provide)
2553
+		);
2554
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2555
+		return $error_message;
2556
+	}
2557
+
2558
+
2559
+	/**
2560
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2561
+	 * EEM_Base::$_db_verification_level
2562
+	 *
2563
+	 * @param $wpdb_method
2564
+	 * @param $arguments_to_provide
2565
+	 * @return string
2566
+	 * @throws EE_Error
2567
+	 * @throws ReflectionException
2568
+	 */
2569
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2570
+	{
2571
+		/** @type WPDB $wpdb */
2572
+		global $wpdb;
2573
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2574
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2575
+		$error_message                    = sprintf(
2576
+			esc_html__(
2577
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2578
+				'event_espresso'
2579
+			),
2580
+			$wpdb->last_error,
2581
+			$wpdb_method,
2582
+			wp_json_encode($arguments_to_provide)
2583
+		);
2584
+		EE_System::instance()->initialize_addons();
2585
+		return $error_message;
2586
+	}
2587
+
2588
+
2589
+	/**
2590
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2591
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2592
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2593
+	 * ..."
2594
+	 *
2595
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2596
+	 * @return string
2597
+	 */
2598
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2599
+	{
2600
+		return " FROM " . $model_query_info->get_full_join_sql() .
2601
+			   $model_query_info->get_where_sql() .
2602
+			   $model_query_info->get_group_by_sql() .
2603
+			   $model_query_info->get_having_sql() .
2604
+			   $model_query_info->get_order_by_sql() .
2605
+			   $model_query_info->get_limit_sql();
2606
+	}
2607
+
2608
+
2609
+	/**
2610
+	 * Set to easily debug the next X queries ran from this model.
2611
+	 *
2612
+	 * @param int $count
2613
+	 */
2614
+	public function show_next_x_db_queries($count = 1)
2615
+	{
2616
+		$this->_show_next_x_db_queries = $count;
2617
+	}
2618
+
2619
+
2620
+	/**
2621
+	 * @param $sql_query
2622
+	 */
2623
+	public function show_db_query_if_previously_requested($sql_query)
2624
+	{
2625
+		if ($this->_show_next_x_db_queries > 0) {
2626
+			echo esc_html($sql_query);
2627
+			$this->_show_next_x_db_queries--;
2628
+		}
2629
+	}
2630
+
2631
+
2632
+	/**
2633
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2634
+	 * There are the 3 cases:
2635
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2636
+	 * $otherModelObject has no ID, it is first saved.
2637
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2638
+	 * has no ID, it is first saved.
2639
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2640
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2641
+	 * join table
2642
+	 *
2643
+	 * @param EE_Base_Class|int $id_or_obj                        EE_base_Class or ID of $thisModelObject
2644
+	 * @param EE_Base_Class|int $other_model_id_or_obj            EE_base_Class or ID of other Model Object
2645
+	 * @param string            $relationName                     , key in EEM_Base::_relations
2646
+	 *                                                            an attendee to a group, you also want to specify
2647
+	 *                                                            which role they will have in that group. So you would
2648
+	 *                                                            use this parameter to specify
2649
+	 *                                                            array('role-column-name'=>'role-id')
2650
+	 * @param array|null        $extra_join_model_fields_n_values This allows you to enter further query params for the
2651
+	 *                                                            relation to for relation to methods that allow you to
2652
+	 *                                                            further specify extra columns to join by (such as
2653
+	 *                                                            HABTM).  Keep in mind that the only acceptable
2654
+	 *                                                            query_params is strict "col" => "value" pairs because
2655
+	 *                                                            these will be inserted in any new rows created as
2656
+	 *                                                            well.
2657
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2658
+	 * @throws EE_Error
2659
+	 */
2660
+	public function add_relationship_to(
2661
+		$id_or_obj,
2662
+		$other_model_id_or_obj,
2663
+		$relationName,
2664
+		$extra_join_model_fields_n_values = []
2665
+	) {
2666
+		$relation_obj = $this->related_settings_for($relationName);
2667
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2668
+	}
2669
+
2670
+
2671
+	/**
2672
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2673
+	 * There are the 3 cases:
2674
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2675
+	 * error
2676
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2677
+	 * an error
2678
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2679
+	 *
2680
+	 * @param EE_Base_Class|int $id_or_obj             EE_base_Class or ID of $thisModelObject
2681
+	 * @param EE_Base_Class|int $other_model_id_or_obj EE_base_Class or ID of other Model Object
2682
+	 * @param string            $relationName          key in EEM_Base::_relations
2683
+	 * @param array|null        $where_query           This allows you to enter further query params for the relation
2684
+	 *                                                 to for relation to methods that allow you to further specify
2685
+	 *                                                 extra columns to join by (such as HABTM). Keep in mind that the
2686
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2687
+	 *                                                 because these will be inserted in any new rows created as well.
2688
+	 * @return EE_Base_Class
2689
+	 * @throws EE_Error
2690
+	 */
2691
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2692
+	{
2693
+		$relation_obj = $this->related_settings_for($relationName);
2694
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2695
+	}
2696
+
2697
+
2698
+	/**
2699
+	 * @param mixed       $id_or_obj
2700
+	 * @param string      $relationName
2701
+	 * @param array|null  $where_query_params
2702
+	 * @return EE_Base_Class[]
2703
+	 * @throws EE_Error
2704
+	 * @throws ReflectionException
2705
+	 */
2706
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2707
+	{
2708
+		$relation_obj = $this->related_settings_for($relationName);
2709
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2710
+	}
2711
+
2712
+
2713
+	/**
2714
+	 * Gets all the related items of the specified $model_name, using $query_params.
2715
+	 * Note: by default, we remove the "default query params"
2716
+	 * because we want to get even deleted items etc.
2717
+	 *
2718
+	 * @param mixed       $id_or_obj    EE_Base_Class child or its ID
2719
+	 * @param string      $model_name   like 'Event', 'Registration', etc. always singular
2720
+	 * @param array|null  $query_params @see
2721
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2722
+	 * @return EE_Base_Class[]
2723
+	 * @throws EE_Error
2724
+	 * @throws ReflectionException
2725
+	 */
2726
+	public function get_all_related($id_or_obj, $model_name, ?array $query_params = [])
2727
+	{
2728
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2729
+		$relation_settings = $this->related_settings_for($model_name);
2730
+		return $relation_settings->get_all_related($model_obj, $query_params);
2731
+	}
2732
+
2733
+
2734
+	/**
2735
+	 * Deletes all the model objects across the relation indicated by $model_name
2736
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2737
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2738
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2739
+	 *
2740
+	 * @param EE_Base_Class|int|string $id_or_obj
2741
+	 * @param string                   $model_name
2742
+	 * @param array|null               $query_params
2743
+	 * @return int how many deleted
2744
+	 * @throws EE_Error
2745
+	 * @throws ReflectionException
2746
+	 */
2747
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2748
+	{
2749
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2750
+		$relation_settings = $this->related_settings_for($model_name);
2751
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2752
+	}
2753
+
2754
+
2755
+	/**
2756
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2757
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2758
+	 * the model objects can't be hard deleted because of blocking related model objects,
2759
+	 * just does a soft-delete on them instead.
2760
+	 *
2761
+	 * @param EE_Base_Class|int|string $id_or_obj
2762
+	 * @param string                   $model_name
2763
+	 * @param array|null               $query_params
2764
+	 * @return int how many deleted
2765
+	 * @throws EE_Error
2766
+	 * @throws ReflectionException
2767
+	 */
2768
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2769
+	{
2770
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2771
+		$relation_settings = $this->related_settings_for($model_name);
2772
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2773
+	}
2774
+
2775
+
2776
+	/**
2777
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2778
+	 * unless otherwise specified in the $query_params
2779
+	 *
2780
+	 * @param EE_Base_Class|int|string $id_or_obj
2781
+	 * @param string                   $model_name     like 'Event', or 'Registration'
2782
+	 * @param array|null               $query_params   @see
2783
+	 *                                                 https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2784
+	 * @param string                   $field_to_count name of field to count by. By default, uses primary key
2785
+	 * @param bool                     $distinct       if we want to only count the distinct values for the column then
2786
+	 *                                                 you can trigger that by the setting $distinct to TRUE;
2787
+	 * @return int
2788
+	 * @throws EE_Error
2789
+	 * @throws ReflectionException
2790
+	 */
2791
+	public function count_related(
2792
+		$id_or_obj,
2793
+		$model_name,
2794
+		$query_params = [],
2795
+		$field_to_count = null,
2796
+		$distinct = false
2797
+	) {
2798
+		$related_model = $this->get_related_model_obj($model_name);
2799
+		// we're just going to use the query params on the related model's normal get_all query,
2800
+		// except add a condition to say to match the current mod
2801
+		if (! isset($query_params['default_where_conditions'])) {
2802
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2803
+		}
2804
+		$this_model_name                                                 = $this->get_this_model_name();
2805
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2806
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2807
+		return $related_model->count($query_params, $field_to_count, $distinct);
2808
+	}
2809
+
2810
+
2811
+	/**
2812
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2813
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2814
+	 *
2815
+	 * @param EE_Base_Class|int|string $id_or_obj
2816
+	 * @param string                   $model_name   like 'Event', or 'Registration'
2817
+	 * @param array|null               $query_params @see
2818
+	 *                                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2819
+	 * @param string                   $field_to_sum name of field to count by. By default, uses primary key
2820
+	 * @return float
2821
+	 * @throws EE_Error
2822
+	 * @throws ReflectionException
2823
+	 */
2824
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2825
+	{
2826
+		$related_model = $this->get_related_model_obj($model_name);
2827
+		if (! is_array($query_params)) {
2828
+			EE_Error::doing_it_wrong(
2829
+				'EEM_Base::sum_related',
2830
+				sprintf(
2831
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2832
+					gettype($query_params)
2833
+				),
2834
+				'4.6.0'
2835
+			);
2836
+			$query_params = [];
2837
+		}
2838
+		// we're just going to use the query params on the related model's normal get_all query,
2839
+		// except add a condition to say to match the current mod
2840
+		if (! isset($query_params['default_where_conditions'])) {
2841
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2842
+		}
2843
+		$this_model_name                                                 = $this->get_this_model_name();
2844
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2845
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2846
+		return $related_model->sum($query_params, $field_to_sum);
2847
+	}
2848
+
2849
+
2850
+	/**
2851
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2852
+	 * $modelObject
2853
+	 *
2854
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2855
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2856
+	 * @param array|null          $query_params     @see
2857
+	 *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2858
+	 * @return EE_Base_Class
2859
+	 * @throws EE_Error
2860
+	 * @throws ReflectionException
2861
+	 */
2862
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2863
+	{
2864
+		$query_params['limit'] = 1;
2865
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2866
+		if ($results) {
2867
+			return array_shift($results);
2868
+		}
2869
+		return null;
2870
+	}
2871
+
2872
+
2873
+	/**
2874
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2875
+	 *
2876
+	 * @return string
2877
+	 */
2878
+	public function get_this_model_name()
2879
+	{
2880
+		return str_replace("EEM_", "", get_class($this));
2881
+	}
2882
+
2883
+
2884
+	/**
2885
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2886
+	 *
2887
+	 * @return EE_Any_Foreign_Model_Name_Field
2888
+	 * @throws EE_Error
2889
+	 */
2890
+	public function get_field_containing_related_model_name()
2891
+	{
2892
+		foreach ($this->field_settings(true) as $field) {
2893
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2894
+				$field_with_model_name = $field;
2895
+			}
2896
+		}
2897
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2898
+			throw new EE_Error(
2899
+				sprintf(
2900
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2901
+					$this->get_this_model_name()
2902
+				)
2903
+			);
2904
+		}
2905
+		return $field_with_model_name;
2906
+	}
2907
+
2908
+
2909
+	/**
2910
+	 * Inserts a new entry into the database, for each table.
2911
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2912
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2913
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2914
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2915
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2916
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2917
+	 *
2918
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2919
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2920
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2921
+	 *                              of EEM_Base)
2922
+	 * @return int|string new primary key on main table that got inserted
2923
+	 * @throws EE_Error
2924
+	 * @throws ReflectionException
2925
+	 */
2926
+	public function insert($field_n_values)
2927
+	{
2928
+		/**
2929
+		 * Filters the fields and their values before inserting an item using the models
2930
+		 *
2931
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2932
+		 * @param EEM_Base $model           the model used
2933
+		 */
2934
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2935
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2936
+			$main_table = $this->_get_main_table();
2937
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2938
+			if ($new_id !== false) {
2939
+				foreach ($this->_get_other_tables() as $other_table) {
2940
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2941
+				}
2942
+			}
2943
+			/**
2944
+			 * Done just after attempting to insert a new model object
2945
+			 *
2946
+			 * @param EEM_Base $model           used
2947
+			 * @param array    $fields_n_values fields and their values
2948
+			 * @param int|string the              ID of the newly-inserted model object
2949
+			 */
2950
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2951
+			return $new_id;
2952
+		}
2953
+		return false;
2954
+	}
2955
+
2956
+
2957
+	/**
2958
+	 * Checks that the result would satisfy the unique indexes on this model
2959
+	 *
2960
+	 * @param array  $field_n_values
2961
+	 * @param string $action
2962
+	 * @return boolean
2963
+	 * @throws EE_Error
2964
+	 * @throws ReflectionException
2965
+	 */
2966
+	protected function _satisfies_unique_indexes(array $field_n_values, $action = 'insert')
2967
+	{
2968
+		foreach ($this->unique_indexes() as $index_name => $index) {
2969
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2970
+			if ($this->exists([$uniqueness_where_params])) {
2971
+				EE_Error::add_error(
2972
+					sprintf(
2973
+						esc_html__(
2974
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2975
+							"event_espresso"
2976
+						),
2977
+						$action,
2978
+						$this->_get_class_name(),
2979
+						$index_name,
2980
+						implode(",", $index->field_names()),
2981
+						http_build_query($uniqueness_where_params)
2982
+					),
2983
+					__FILE__,
2984
+					__FUNCTION__,
2985
+					__LINE__
2986
+				);
2987
+				return false;
2988
+			}
2989
+		}
2990
+		return true;
2991
+	}
2992
+
2993
+
2994
+	/**
2995
+	 * Checks the database for an item that conflicts (ie, if this item were
2996
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2997
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2998
+	 * can be either an EE_Base_Class or an array of fields n values
2999
+	 *
3000
+	 * @param EE_Base_Class|array $obj_or_fields_array
3001
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
3002
+	 *                                                 when looking for conflicts
3003
+	 *                                                 (ie, if false, we ignore the model object's primary key
3004
+	 *                                                 when finding "conflicts". If true, it's also considered).
3005
+	 *                                                 Only works for INT primary key,
3006
+	 *                                                 STRING primary keys cannot be ignored
3007
+	 * @return EE_Base_Class|array
3008
+	 * @throws EE_Error
3009
+	 * @throws ReflectionException
3010
+	 */
3011
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
3012
+	{
3013
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
3014
+			$fields_n_values = $obj_or_fields_array->model_field_array();
3015
+		} elseif (is_array($obj_or_fields_array)) {
3016
+			$fields_n_values = $obj_or_fields_array;
3017
+		} else {
3018
+			throw new EE_Error(
3019
+				sprintf(
3020
+					esc_html__(
3021
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
3022
+						"event_espresso"
3023
+					),
3024
+					get_class($this),
3025
+					$obj_or_fields_array
3026
+				)
3027
+			);
3028
+		}
3029
+		$query_params = [];
3030
+		if (
3031
+			$this->has_primary_key_field()
3032
+			&& ($include_primary_key
3033
+				|| $this->get_primary_key_field()
3034
+				   instanceof
3035
+				   EE_Primary_Key_String_Field)
3036
+			&& isset($fields_n_values[ $this->primary_key_name() ])
3037
+		) {
3038
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3039
+		}
3040
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3041
+			$uniqueness_where_params                              =
3042
+				array_intersect_key($fields_n_values, $unique_index->fields());
3043
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3044
+		}
3045
+		// if there is nothing to base this search on, then we shouldn't find anything
3046
+		if (empty($query_params)) {
3047
+			return [];
3048
+		}
3049
+		return $this->get_one($query_params);
3050
+	}
3051
+
3052
+
3053
+	/**
3054
+	 * Like count, but is optimized and returns a boolean instead of an int
3055
+	 *
3056
+	 * @param array $query_params
3057
+	 * @return boolean
3058
+	 * @throws EE_Error
3059
+	 * @throws ReflectionException
3060
+	 */
3061
+	public function exists($query_params)
3062
+	{
3063
+		$query_params['limit'] = 1;
3064
+		return $this->count($query_params) > 0;
3065
+	}
3066
+
3067
+
3068
+	/**
3069
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
3070
+	 *
3071
+	 * @param int|string $id
3072
+	 * @return boolean
3073
+	 * @throws EE_Error
3074
+	 * @throws ReflectionException
3075
+	 */
3076
+	public function exists_by_ID($id)
3077
+	{
3078
+		return $this->exists(
3079
+			[
3080
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3081
+				[
3082
+					$this->primary_key_name() => $id,
3083
+				],
3084
+			]
3085
+		);
3086
+	}
3087
+
3088
+
3089
+	/**
3090
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3091
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3092
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3093
+	 * on the main table)
3094
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3095
+	 * cases where we want to call it directly rather than via insert().
3096
+	 *
3097
+	 * @access   protected
3098
+	 * @param EE_Table_Base $table
3099
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3100
+	 *                                       float
3101
+	 * @param int           $new_id          for now we assume only int keys
3102
+	 * @return int ID of new row inserted, or FALSE on failure
3103
+	 * @throws EE_Error
3104
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3105
+	 */
3106
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3107
+	{
3108
+		global $wpdb;
3109
+		$insertion_col_n_values = [];
3110
+		$format_for_insertion   = [];
3111
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3112
+		foreach ($fields_on_table as $field_obj) {
3113
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3114
+			if ($field_obj->is_auto_increment()) {
3115
+				continue;
3116
+			}
3117
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3118
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3119
+			if ($prepared_value !== null) {
3120
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3121
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3122
+			}
3123
+		}
3124
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3125
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3126
+			// so add the fk to the main table as a column
3127
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3128
+			$format_for_insertion[]                              =
3129
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3130
+		}
3131
+
3132
+		// insert the new entry
3133
+		$result = $this->_do_wpdb_query(
3134
+			'insert',
3135
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3136
+		);
3137
+		if ($result === false) {
3138
+			return false;
3139
+		}
3140
+		// ok, now what do we return for the ID of the newly-inserted thing?
3141
+		if ($this->has_primary_key_field()) {
3142
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3143
+				return $wpdb->insert_id;
3144
+			}
3145
+			// it's not an auto-increment primary key, so
3146
+			// it must have been supplied
3147
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3148
+		}
3149
+		// we can't return a  primary key because there is none. instead return
3150
+		// a unique string indicating this model
3151
+		return $this->get_index_primary_key_string($fields_n_values);
3152
+	}
3153
+
3154
+
3155
+	/**
3156
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3157
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3158
+	 * and there is no default, we pass it along. WPDB will take care of it)
3159
+	 *
3160
+	 * @param EE_Model_Field_Base $field_obj
3161
+	 * @param array               $fields_n_values
3162
+	 * @return mixed string|int|float depending on what the table column will be expecting
3163
+	 * @throws EE_Error
3164
+	 */
3165
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3166
+	{
3167
+		$field_name = $field_obj->get_name();
3168
+		// if this field doesn't allow nullable, don't allow it
3169
+		if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3170
+			$fields_n_values[ $field_name ] = $field_obj->get_default_value();
3171
+		}
3172
+		$unprepared_value = $fields_n_values[ $field_name ] ?? null;
3173
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3174
+	}
3175
+
3176
+
3177
+	/**
3178
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3179
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3180
+	 * the field's prepare_for_set() method.
3181
+	 *
3182
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3183
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3184
+	 *                                   top of file)
3185
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3186
+	 *                                   $value is a custom selection
3187
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3188
+	 */
3189
+	private function _prepare_value_for_use_in_db($value, $field)
3190
+	{
3191
+		if ($field instanceof EE_Model_Field_Base) {
3192
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3193
+			switch ($this->_values_already_prepared_by_model_object) {
3194
+				/** @noinspection PhpMissingBreakStatementInspection */
3195
+				case self::not_prepared_by_model_object:
3196
+					$value = $field->prepare_for_set($value);
3197
+				// purposefully left out "return"
3198
+				// no break
3199
+				case self::prepared_by_model_object:
3200
+					/** @noinspection SuspiciousAssignmentsInspection */
3201
+					$value = $field->prepare_for_use_in_db($value);
3202
+				// no break
3203
+				case self::prepared_for_use_in_db:
3204
+					// leave the value alone
3205
+			}
3206
+			// phpcs:enable
3207
+		}
3208
+		return $value;
3209
+	}
3210
+
3211
+
3212
+	/**
3213
+	 * Returns the main table on this model
3214
+	 *
3215
+	 * @return EE_Primary_Table
3216
+	 * @throws EE_Error
3217
+	 */
3218
+	protected function _get_main_table()
3219
+	{
3220
+		foreach ($this->_tables as $table) {
3221
+			if ($table instanceof EE_Primary_Table) {
3222
+				return $table;
3223
+			}
3224
+		}
3225
+		throw new EE_Error(
3226
+			sprintf(
3227
+				esc_html__(
3228
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3229
+					'event_espresso'
3230
+				),
3231
+				get_class($this)
3232
+			)
3233
+		);
3234
+	}
3235
+
3236
+
3237
+	/**
3238
+	 * table
3239
+	 * returns EE_Primary_Table table name
3240
+	 *
3241
+	 * @return string
3242
+	 * @throws EE_Error
3243
+	 */
3244
+	public function table()
3245
+	{
3246
+		return $this->_get_main_table()->get_table_name();
3247
+	}
3248
+
3249
+
3250
+	/**
3251
+	 * table
3252
+	 * returns first EE_Secondary_Table table name
3253
+	 *
3254
+	 * @return string
3255
+	 */
3256
+	public function second_table()
3257
+	{
3258
+		// grab second table from tables array
3259
+		$second_table = end($this->_tables);
3260
+		return $second_table instanceof EE_Secondary_Table
3261
+			? $second_table->get_table_name()
3262
+			: null;
3263
+	}
3264
+
3265
+
3266
+	/**
3267
+	 * get_table_obj_by_alias
3268
+	 * returns table name given it's alias
3269
+	 *
3270
+	 * @param string $table_alias
3271
+	 * @return EE_Primary_Table | EE_Secondary_Table
3272
+	 */
3273
+	public function get_table_obj_by_alias($table_alias = '')
3274
+	{
3275
+		return $this->_tables[ $table_alias ] ?? null;
3276
+	}
3277
+
3278
+
3279
+	/**
3280
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3281
+	 *
3282
+	 * @return EE_Secondary_Table[]
3283
+	 */
3284
+	protected function _get_other_tables()
3285
+	{
3286
+		$other_tables = [];
3287
+		foreach ($this->_tables as $table_alias => $table) {
3288
+			if ($table instanceof EE_Secondary_Table) {
3289
+				$other_tables[ $table_alias ] = $table;
3290
+			}
3291
+		}
3292
+		return $other_tables;
3293
+	}
3294
+
3295
+
3296
+	/**
3297
+	 * Finds all the fields that correspond to the given table
3298
+	 *
3299
+	 * @param string $table_alias , array key in EEM_Base::_tables
3300
+	 * @return EE_Model_Field_Base[]
3301
+	 */
3302
+	public function _get_fields_for_table($table_alias)
3303
+	{
3304
+		return $this->_fields[ $table_alias ];
3305
+	}
3306
+
3307
+
3308
+	/**
3309
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3310
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3311
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3312
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3313
+	 * related Registration, Transaction, and Payment models.
3314
+	 *
3315
+	 * @param array $query_params @see
3316
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3317
+	 * @return EE_Model_Query_Info_Carrier
3318
+	 * @throws EE_Error
3319
+	 */
3320
+	public function _extract_related_models_from_query($query_params)
3321
+	{
3322
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3323
+		if (array_key_exists(0, $query_params)) {
3324
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3325
+		}
3326
+		if (array_key_exists('group_by', $query_params)) {
3327
+			if (is_array($query_params['group_by'])) {
3328
+				$this->_extract_related_models_from_sub_params_array_values(
3329
+					$query_params['group_by'],
3330
+					$query_info_carrier,
3331
+					'group_by'
3332
+				);
3333
+			} elseif (! empty($query_params['group_by'])) {
3334
+				$this->_extract_related_model_info_from_query_param(
3335
+					$query_params['group_by'],
3336
+					$query_info_carrier,
3337
+					'group_by'
3338
+				);
3339
+			}
3340
+		}
3341
+		if (array_key_exists('having', $query_params)) {
3342
+			$this->_extract_related_models_from_sub_params_array_keys(
3343
+				$query_params[0],
3344
+				$query_info_carrier,
3345
+				'having'
3346
+			);
3347
+		}
3348
+		if (array_key_exists('order_by', $query_params)) {
3349
+			if (is_array($query_params['order_by'])) {
3350
+				$this->_extract_related_models_from_sub_params_array_keys(
3351
+					$query_params['order_by'],
3352
+					$query_info_carrier,
3353
+					'order_by'
3354
+				);
3355
+			} elseif (! empty($query_params['order_by'])) {
3356
+				$this->_extract_related_model_info_from_query_param(
3357
+					$query_params['order_by'],
3358
+					$query_info_carrier,
3359
+					'order_by'
3360
+				);
3361
+			}
3362
+		}
3363
+		if (array_key_exists('force_join', $query_params)) {
3364
+			$this->_extract_related_models_from_sub_params_array_values(
3365
+				$query_params['force_join'],
3366
+				$query_info_carrier,
3367
+				'force_join'
3368
+			);
3369
+		}
3370
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3371
+		return $query_info_carrier;
3372
+	}
3373
+
3374
+
3375
+	/**
3376
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3377
+	 *
3378
+	 * @param array                       $sub_query_params
3379
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3380
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3381
+	 * @return EE_Model_Query_Info_Carrier
3382
+	 * @throws EE_Error
3383
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3384
+	 */
3385
+	private function _extract_related_models_from_sub_params_array_keys(
3386
+		$sub_query_params,
3387
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3388
+		$query_param_type
3389
+	) {
3390
+		if (! empty($sub_query_params)) {
3391
+			$sub_query_params = (array) $sub_query_params;
3392
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3393
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3394
+				$this->_extract_related_model_info_from_query_param(
3395
+					$param,
3396
+					$model_query_info_carrier,
3397
+					$query_param_type
3398
+				);
3399
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3400
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3401
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3402
+				// of array('Registration.TXN_ID'=>23)
3403
+				$query_param_sans_stars =
3404
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3405
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3406
+					if (! is_array($possibly_array_of_params)) {
3407
+						throw new EE_Error(
3408
+							sprintf(
3409
+								esc_html__(
3410
+									"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'))",
3411
+									"event_espresso"
3412
+								),
3413
+								$param,
3414
+								$possibly_array_of_params
3415
+							)
3416
+						);
3417
+					}
3418
+					$this->_extract_related_models_from_sub_params_array_keys(
3419
+						$possibly_array_of_params,
3420
+						$model_query_info_carrier,
3421
+						$query_param_type
3422
+					);
3423
+				} elseif (
3424
+					$query_param_type === 0 // ie WHERE
3425
+					&& is_array($possibly_array_of_params) // need is_array() check so we don't try to explode a string
3426
+					&& isset($possibly_array_of_params[2])
3427
+					&& $possibly_array_of_params[2]
3428
+				) {
3429
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3430
+					// indicating that $possible_array_of_params[1] is actually a field name,
3431
+					// from which we should extract query parameters!
3432
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3433
+						throw new EE_Error(
3434
+							sprintf(
3435
+								esc_html__(
3436
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3437
+									"event_espresso"
3438
+								),
3439
+								$query_param_type,
3440
+								implode(",", $possibly_array_of_params)
3441
+							)
3442
+						);
3443
+					}
3444
+					$this->_extract_related_model_info_from_query_param(
3445
+						$possibly_array_of_params[1],
3446
+						$model_query_info_carrier,
3447
+						$query_param_type
3448
+					);
3449
+				}
3450
+			}
3451
+		}
3452
+		return $model_query_info_carrier;
3453
+	}
3454
+
3455
+
3456
+	/**
3457
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3458
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3459
+	 *
3460
+	 * @param array                       $sub_query_params @see
3461
+	 *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3462
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3463
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3464
+	 * @return EE_Model_Query_Info_Carrier
3465
+	 * @throws EE_Error
3466
+	 */
3467
+	private function _extract_related_models_from_sub_params_array_values(
3468
+		$sub_query_params,
3469
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3470
+		$query_param_type
3471
+	) {
3472
+		if (! empty($sub_query_params)) {
3473
+			if (! is_array($sub_query_params)) {
3474
+				throw new EE_Error(
3475
+					sprintf(
3476
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3477
+						$sub_query_params
3478
+					)
3479
+				);
3480
+			}
3481
+			foreach ($sub_query_params as $param) {
3482
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3483
+				$this->_extract_related_model_info_from_query_param(
3484
+					$param,
3485
+					$model_query_info_carrier,
3486
+					$query_param_type
3487
+				);
3488
+			}
3489
+		}
3490
+		return $model_query_info_carrier;
3491
+	}
3492
+
3493
+
3494
+	/**
3495
+	 * Extract all the query parts from  model query params
3496
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3497
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3498
+	 * but use them in a different order. Eg, we need to know what models we are querying
3499
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3500
+	 * other models before we can finalize the where clause SQL.
3501
+	 *
3502
+	 * @param array $query_params
3503
+	 * @return EE_Model_Query_Info_Carrier
3504
+	 * @throws EE_Error
3505
+	 * @throws ModelConfigurationException
3506
+	 * @throws ReflectionException
3507
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3508
+	 */
3509
+	public function _create_model_query_info_carrier($query_params)
3510
+	{
3511
+		if (! is_array($query_params)) {
3512
+			EE_Error::doing_it_wrong(
3513
+				'EEM_Base::_create_model_query_info_carrier',
3514
+				sprintf(
3515
+					esc_html__(
3516
+						'$query_params should be an array, you passed a variable of type %s',
3517
+						'event_espresso'
3518
+					),
3519
+					gettype($query_params)
3520
+				),
3521
+				'4.6.0'
3522
+			);
3523
+			$query_params = [];
3524
+		}
3525
+		$query_params[0] = $query_params[0] ?? [];
3526
+		// first check if we should alter the query to account for caps or not
3527
+		// because the caps might require us to do extra joins
3528
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3529
+			$query_params[0] = array_replace_recursive(
3530
+				$query_params[0],
3531
+				$this->caps_where_conditions($query_params['caps'])
3532
+			);
3533
+		}
3534
+
3535
+		// check if we should alter the query to remove data related to protected
3536
+		// custom post types
3537
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3538
+			$where_param_key_for_password = $this->modelChainAndPassword();
3539
+			// only include if related to a cpt where no password has been set
3540
+			$query_params[0]['OR*nopassword'] = [
3541
+				$where_param_key_for_password       => '',
3542
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3543
+			];
3544
+		}
3545
+		$query_object = $this->_extract_related_models_from_query($query_params);
3546
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3547
+		foreach ($query_params[0] as $key => $value) {
3548
+			if (is_int($key)) {
3549
+				throw new EE_Error(
3550
+					sprintf(
3551
+						esc_html__(
3552
+							"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.",
3553
+							"event_espresso"
3554
+						),
3555
+						$key,
3556
+						var_export($value, true),
3557
+						var_export($query_params, true),
3558
+						get_class($this)
3559
+					)
3560
+				);
3561
+			}
3562
+		}
3563
+		if (
3564
+			array_key_exists('default_where_conditions', $query_params)
3565
+			&& ! empty($query_params['default_where_conditions'])
3566
+		) {
3567
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3568
+		} else {
3569
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3570
+		}
3571
+		$query_params[0] = array_merge(
3572
+			$this->_get_default_where_conditions_for_models_in_query(
3573
+				$query_object,
3574
+				$use_default_where_conditions,
3575
+				$query_params[0]
3576
+			),
3577
+			$query_params[0]
3578
+		);
3579
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3580
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3581
+		// So we need to setup a subquery and use that for the main join.
3582
+		// Note for now this only works on the primary table for the model.
3583
+		// So for instance, you could set the limit array like this:
3584
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3585
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3586
+			$query_object->set_main_model_join_sql(
3587
+				$this->_construct_limit_join_select(
3588
+					$query_params['on_join_limit'][0],
3589
+					$query_params['on_join_limit'][1]
3590
+				)
3591
+			);
3592
+		}
3593
+		// set limit
3594
+		if (array_key_exists('limit', $query_params)) {
3595
+			if (is_array($query_params['limit'])) {
3596
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3597
+					$e = sprintf(
3598
+						esc_html__(
3599
+							"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)",
3600
+							"event_espresso"
3601
+						),
3602
+						http_build_query($query_params['limit'])
3603
+					);
3604
+					throw new EE_Error($e . "|" . $e);
3605
+				}
3606
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3607
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3608
+			} elseif (! empty($query_params['limit'])) {
3609
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3610
+			}
3611
+		}
3612
+		// set order by
3613
+		if (array_key_exists('order_by', $query_params)) {
3614
+			if (is_array($query_params['order_by'])) {
3615
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3616
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3617
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3618
+				if (array_key_exists('order', $query_params)) {
3619
+					throw new EE_Error(
3620
+						sprintf(
3621
+							esc_html__(
3622
+								"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 ",
3623
+								"event_espresso"
3624
+							),
3625
+							get_class($this),
3626
+							implode(", ", array_keys($query_params['order_by'])),
3627
+							implode(", ", $query_params['order_by']),
3628
+							$query_params['order']
3629
+						)
3630
+					);
3631
+				}
3632
+				$this->_extract_related_models_from_sub_params_array_keys(
3633
+					$query_params['order_by'],
3634
+					$query_object,
3635
+					'order_by'
3636
+				);
3637
+				// assume it's an array of fields to order by
3638
+				$order_array = [];
3639
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3640
+					$order         = $this->_extract_order($order);
3641
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3642
+				}
3643
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3644
+			} elseif (! empty($query_params['order_by'])) {
3645
+				$this->_extract_related_model_info_from_query_param(
3646
+					$query_params['order_by'],
3647
+					$query_object,
3648
+					'order',
3649
+					$query_params['order_by']
3650
+				);
3651
+				$order = isset($query_params['order'])
3652
+					? $this->_extract_order($query_params['order'])
3653
+					: 'DESC';
3654
+				$query_object->set_order_by_sql(
3655
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3656
+				);
3657
+			}
3658
+		}
3659
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3660
+		if (
3661
+			! array_key_exists('order_by', $query_params)
3662
+			&& array_key_exists('order', $query_params)
3663
+			&& ! empty($query_params['order'])
3664
+		) {
3665
+			$pk_field = $this->get_primary_key_field();
3666
+			$order    = $this->_extract_order($query_params['order']);
3667
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3668
+		}
3669
+		// set group by
3670
+		if (array_key_exists('group_by', $query_params)) {
3671
+			if (is_array($query_params['group_by'])) {
3672
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3673
+				$group_by_array = [];
3674
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3675
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3676
+				}
3677
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3678
+			} elseif (! empty($query_params['group_by'])) {
3679
+				$query_object->set_group_by_sql(
3680
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3681
+				);
3682
+			}
3683
+		}
3684
+		// set having
3685
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3686
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3687
+		}
3688
+		// now, just verify they didn't pass anything wack
3689
+		foreach ($query_params as $query_key => $query_value) {
3690
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3691
+				throw new EE_Error(
3692
+					sprintf(
3693
+						esc_html__(
3694
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3695
+							'event_espresso'
3696
+						),
3697
+						$query_key,
3698
+						get_class($this),
3699
+						//                      print_r( $this->_allowed_query_params, TRUE )
3700
+						implode(',', $this->_allowed_query_params)
3701
+					)
3702
+				);
3703
+			}
3704
+		}
3705
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3706
+		if (empty($main_model_join_sql)) {
3707
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3708
+		}
3709
+		return $query_object;
3710
+	}
3711
+
3712
+
3713
+	/**
3714
+	 * Gets the where conditions that should be imposed on the query based on the
3715
+	 * context (eg reading frontend, backend, edit or delete).
3716
+	 *
3717
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3718
+	 * @return array @see
3719
+	 *                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3720
+	 * @throws EE_Error
3721
+	 */
3722
+	public function caps_where_conditions($context = self::caps_read)
3723
+	{
3724
+		EEM_Base::verify_is_valid_cap_context($context);
3725
+		$cap_where_conditions = [];
3726
+		$cap_restrictions     = $this->caps_missing($context);
3727
+		foreach ($cap_restrictions as $restriction_if_no_cap) {
3728
+			$cap_where_conditions = array_replace_recursive(
3729
+				$cap_where_conditions,
3730
+				$restriction_if_no_cap->get_default_where_conditions()
3731
+			);
3732
+		}
3733
+		return apply_filters(
3734
+			'FHEE__EEM_Base__caps_where_conditions__return',
3735
+			$cap_where_conditions,
3736
+			$this,
3737
+			$context,
3738
+			$cap_restrictions
3739
+		);
3740
+	}
3741
+
3742
+
3743
+	/**
3744
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3745
+	 * otherwise throws an exception
3746
+	 *
3747
+	 * @param string $should_be_order_string
3748
+	 * @return string either ASC, asc, DESC or desc
3749
+	 * @throws EE_Error
3750
+	 */
3751
+	private function _extract_order($should_be_order_string)
3752
+	{
3753
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3754
+			return $should_be_order_string;
3755
+		}
3756
+		throw new EE_Error(
3757
+			sprintf(
3758
+				esc_html__(
3759
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3760
+					"event_espresso"
3761
+				),
3762
+				get_class($this),
3763
+				$should_be_order_string
3764
+			)
3765
+		);
3766
+	}
3767
+
3768
+
3769
+	/**
3770
+	 * Looks at all the models which are included in this query, and asks each
3771
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3772
+	 * so they can be merged
3773
+	 *
3774
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3775
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3776
+	 *                                                                  'none' means NO default where conditions will
3777
+	 *                                                                  be used AT ALL during this query.
3778
+	 *                                                                  'other_models_only' means default where
3779
+	 *                                                                  conditions from other models will be used, but
3780
+	 *                                                                  not for this primary model. 'all', the default,
3781
+	 *                                                                  means default where conditions will apply as
3782
+	 *                                                                  normal
3783
+	 * @param array                       $where_query_params
3784
+	 * @return array
3785
+	 * @throws EE_Error
3786
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params
3787
+	 *                                                                  .md#0-where-conditions
3788
+	 */
3789
+	private function _get_default_where_conditions_for_models_in_query(
3790
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3791
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3792
+		$where_query_params = []
3793
+	) {
3794
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3795
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3796
+			throw new EE_Error(
3797
+				sprintf(
3798
+					esc_html__(
3799
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3800
+						"event_espresso"
3801
+					),
3802
+					$use_default_where_conditions,
3803
+					implode(", ", $allowed_used_default_where_conditions_values)
3804
+				)
3805
+			);
3806
+		}
3807
+		$universal_query_params = [];
3808
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3809
+			$universal_query_params = $this->_get_default_where_conditions();
3810
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3811
+			$universal_query_params = $this->_get_minimum_where_conditions();
3812
+		}
3813
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3814
+			$related_model = $this->get_related_model_obj($model_name);
3815
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3816
+				$related_model_universal_where_params =
3817
+					$related_model->_get_default_where_conditions($model_relation_path);
3818
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3819
+				$related_model_universal_where_params =
3820
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3821
+			} else {
3822
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3823
+				continue;
3824
+			}
3825
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3826
+				$related_model_universal_where_params,
3827
+				$where_query_params,
3828
+				$related_model,
3829
+				$model_relation_path
3830
+			);
3831
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3832
+				$universal_query_params,
3833
+				$overrides
3834
+			);
3835
+		}
3836
+		return $universal_query_params;
3837
+	}
3838
+
3839
+
3840
+	/**
3841
+	 * Determines whether or not we should use default where conditions for the model in question
3842
+	 * (this model, or other related models).
3843
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3844
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3845
+	 * We should use default where conditions on related models when they requested to use default where conditions
3846
+	 * on all models, or specifically just on other related models
3847
+	 *
3848
+	 * @param      $default_where_conditions_value
3849
+	 * @param bool $for_this_model false means this is for OTHER related models
3850
+	 * @return bool
3851
+	 */
3852
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3853
+	{
3854
+		return (
3855
+				   $for_this_model
3856
+				   && in_array(
3857
+					   $default_where_conditions_value,
3858
+					   [
3859
+						   EEM_Base::default_where_conditions_all,
3860
+						   EEM_Base::default_where_conditions_this_only,
3861
+						   EEM_Base::default_where_conditions_minimum_others,
3862
+					   ],
3863
+					   true
3864
+				   )
3865
+			   )
3866
+			   || (
3867
+				   ! $for_this_model
3868
+				   && in_array(
3869
+					   $default_where_conditions_value,
3870
+					   [
3871
+						   EEM_Base::default_where_conditions_all,
3872
+						   EEM_Base::default_where_conditions_others_only,
3873
+					   ],
3874
+					   true
3875
+				   )
3876
+			   );
3877
+	}
3878
+
3879
+
3880
+	/**
3881
+	 * Determines whether or not we should use default minimum conditions for the model in question
3882
+	 * (this model, or other related models).
3883
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3884
+	 * where conditions.
3885
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3886
+	 * on this model or others
3887
+	 *
3888
+	 * @param      $default_where_conditions_value
3889
+	 * @param bool $for_this_model false means this is for OTHER related models
3890
+	 * @return bool
3891
+	 */
3892
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3893
+	{
3894
+		return (
3895
+				   $for_this_model
3896
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3897
+			   )
3898
+			   || (
3899
+				   ! $for_this_model
3900
+				   && in_array(
3901
+					   $default_where_conditions_value,
3902
+					   [
3903
+						   EEM_Base::default_where_conditions_minimum_others,
3904
+						   EEM_Base::default_where_conditions_minimum_all,
3905
+					   ],
3906
+					   true
3907
+				   )
3908
+			   );
3909
+	}
3910
+
3911
+
3912
+	/**
3913
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3914
+	 * then we also add a special where condition which allows for that model's primary key
3915
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3916
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3917
+	 *
3918
+	 * @param array    $default_where_conditions
3919
+	 * @param array    $provided_where_conditions
3920
+	 * @param EEM_Base $model
3921
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3922
+	 * @return array @see
3923
+	 *                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3924
+	 * @throws EE_Error
3925
+	 */
3926
+	private function _override_defaults_or_make_null_friendly(
3927
+		$default_where_conditions,
3928
+		$provided_where_conditions,
3929
+		$model,
3930
+		$model_relation_path
3931
+	) {
3932
+		$null_friendly_where_conditions = [];
3933
+		$none_overridden                = true;
3934
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3935
+		foreach ($default_where_conditions as $key => $val) {
3936
+			if (isset($provided_where_conditions[ $key ])) {
3937
+				$none_overridden = false;
3938
+			} else {
3939
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3940
+			}
3941
+		}
3942
+		if ($none_overridden && $default_where_conditions) {
3943
+			if ($model->has_primary_key_field()) {
3944
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3945
+																				   . "."
3946
+																				   . $model->primary_key_name() ] =
3947
+					['IS NULL'];
3948
+			}/*else{
3949 3949
                 //@todo NO PK, use other defaults
3950 3950
             }*/
3951
-        }
3952
-        return $null_friendly_where_conditions;
3953
-    }
3954
-
3955
-
3956
-    /**
3957
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3958
-     * default where conditions on all get_all, update, and delete queries done by this model.
3959
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3960
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3961
-     *
3962
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3963
-     * @return array @see
3964
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3965
-     * @throws EE_Error
3966
-     * @throws EE_Error
3967
-     */
3968
-    private function _get_default_where_conditions($model_relation_path = '')
3969
-    {
3970
-        if ($this->_ignore_where_strategy) {
3971
-            return [];
3972
-        }
3973
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3974
-    }
3975
-
3976
-
3977
-    /**
3978
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3979
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3980
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3981
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3982
-     * Similar to _get_default_where_conditions
3983
-     *
3984
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3985
-     * @return array @see
3986
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3987
-     * @throws EE_Error
3988
-     * @throws EE_Error
3989
-     */
3990
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3991
-    {
3992
-        if ($this->_ignore_where_strategy) {
3993
-            return [];
3994
-        }
3995
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3996
-    }
3997
-
3998
-
3999
-    /**
4000
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
4001
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
4002
-     *
4003
-     * @param EE_Model_Query_Info_Carrier $model_query_info
4004
-     * @return string
4005
-     * @throws EE_Error
4006
-     */
4007
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
4008
-    {
4009
-        $selects = $this->_get_columns_to_select_for_this_model();
4010
-        foreach (
4011
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
4012
-        ) {
4013
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
4014
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
4015
-            foreach ($other_model_selects as $key => $value) {
4016
-                $selects[] = $value;
4017
-            }
4018
-        }
4019
-        return implode(", ", $selects);
4020
-    }
4021
-
4022
-
4023
-    /**
4024
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
4025
-     * So that's going to be the columns for all the fields on the model
4026
-     *
4027
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
4028
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
4029
-     */
4030
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
4031
-    {
4032
-        $fields                                       = $this->field_settings();
4033
-        $selects                                      = [];
4034
-        $table_alias_with_model_relation_chain_prefix =
4035
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
4036
-                $model_relation_chain,
4037
-                $this->get_this_model_name()
4038
-            );
4039
-        foreach ($fields as $field_obj) {
4040
-            $selects[] = $table_alias_with_model_relation_chain_prefix
4041
-                         . $field_obj->get_table_alias()
4042
-                         . "."
4043
-                         . $field_obj->get_table_column()
4044
-                         . " AS '"
4045
-                         . $table_alias_with_model_relation_chain_prefix
4046
-                         . $field_obj->get_table_alias()
4047
-                         . "."
4048
-                         . $field_obj->get_table_column()
4049
-                         . "'";
4050
-        }
4051
-        // make sure we are also getting the PKs of each table
4052
-        $tables = $this->get_tables();
4053
-        if (count($tables) > 1) {
4054
-            foreach ($tables as $table_obj) {
4055
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4056
-                                       . $table_obj->get_fully_qualified_pk_column();
4057
-                if (! in_array($qualified_pk_column, $selects)) {
4058
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4059
-                }
4060
-            }
4061
-        }
4062
-        return $selects;
4063
-    }
4064
-
4065
-
4066
-    /**
4067
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4068
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4069
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4070
-     * SQL for joining, and the data types
4071
-     *
4072
-     * @param null|string                 $original_query_param
4073
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
4074
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4075
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4076
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4077
-     *                                                          column name. We only want model names, eg 'Event.Venue'
4078
-     *                                                          or 'Registration's
4079
-     * @param string                      $original_query_param what it originally was (eg
4080
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4081
-     *                                                          matches $query_param
4082
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4083
-     * @throws EE_Error
4084
-     */
4085
-    private function _extract_related_model_info_from_query_param(
4086
-        $query_param,
4087
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4088
-        $query_param_type,
4089
-        $original_query_param = null
4090
-    ) {
4091
-        if ($original_query_param === null) {
4092
-            $original_query_param = $query_param;
4093
-        }
4094
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4095
-        // check to see if we have a field on this model
4096
-        $this_model_fields = $this->field_settings(true);
4097
-        if (array_key_exists($query_param, $this_model_fields)) {
4098
-            $field_is_allowed = in_array(
4099
-                $query_param_type,
4100
-                [0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4101
-                true
4102
-            );
4103
-            if ($field_is_allowed) {
4104
-                return;
4105
-            }
4106
-            throw new EE_Error(
4107
-                sprintf(
4108
-                    esc_html__(
4109
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4110
-                        "event_espresso"
4111
-                    ),
4112
-                    $query_param,
4113
-                    get_class($this),
4114
-                    $query_param_type,
4115
-                    $original_query_param
4116
-                )
4117
-            );
4118
-        }
4119
-        // check if this is a special logic query param
4120
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4121
-            $operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4122
-            if ($operator_is_allowed) {
4123
-                return;
4124
-            }
4125
-            throw new EE_Error(
4126
-                sprintf(
4127
-                    esc_html__(
4128
-                        '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',
4129
-                        'event_espresso'
4130
-                    ),
4131
-                    implode('", "', $this->_logic_query_param_keys),
4132
-                    $query_param,
4133
-                    get_class($this),
4134
-                    '<br />',
4135
-                    "\t"
4136
-                    . ' $passed_in_query_info = <pre>'
4137
-                    . print_r($passed_in_query_info, true)
4138
-                    . '</pre>'
4139
-                    . "\n\t"
4140
-                    . ' $query_param_type = '
4141
-                    . $query_param_type
4142
-                    . "\n\t"
4143
-                    . ' $original_query_param = '
4144
-                    . $original_query_param
4145
-                )
4146
-            );
4147
-        }
4148
-        // check if it's a custom selection
4149
-        if (
4150
-            $this->_custom_selections instanceof CustomSelects
4151
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4152
-        ) {
4153
-            return;
4154
-        }
4155
-        // check if has a model name at the beginning
4156
-        // and
4157
-        // check if it's a field on a related model
4158
-        if (
4159
-            $this->extractJoinModelFromQueryParams(
4160
-                $passed_in_query_info,
4161
-                $query_param,
4162
-                $original_query_param,
4163
-                $query_param_type
4164
-            )
4165
-        ) {
4166
-            return;
4167
-        }
4168
-
4169
-        // ok so $query_param didn't start with a model name
4170
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4171
-        // it's wack, that's what it is
4172
-        throw new EE_Error(
4173
-            sprintf(
4174
-                esc_html__(
4175
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4176
-                    "event_espresso"
4177
-                ),
4178
-                $query_param,
4179
-                get_class($this),
4180
-                $query_param_type,
4181
-                $original_query_param
4182
-            )
4183
-        );
4184
-    }
4185
-
4186
-
4187
-    /**
4188
-     * Extracts any possible join model information from the provided possible_join_string.
4189
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4190
-     * join
4191
-     * parts that should be added to the query.
4192
-     *
4193
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4194
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4195
-     * @param null|string                 $original_query_param
4196
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4197
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4198
-     *                                                           etc.)
4199
-     * @return bool  returns true if a join was added and false if not.
4200
-     * @throws EE_Error
4201
-     */
4202
-    private function extractJoinModelFromQueryParams(
4203
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4204
-        $possible_join_string,
4205
-        $original_query_param,
4206
-        $query_parameter_type
4207
-    ) {
4208
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4209
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4210
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4211
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4212
-                if ($possible_join_string === '') {
4213
-                    // nothing left to $query_param
4214
-                    // we should actually end in a field name, not a model like this!
4215
-                    throw new EE_Error(
4216
-                        sprintf(
4217
-                            esc_html__(
4218
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4219
-                                "event_espresso"
4220
-                            ),
4221
-                            $possible_join_string,
4222
-                            $query_parameter_type,
4223
-                            get_class($this),
4224
-                            $valid_related_model_name
4225
-                        )
4226
-                    );
4227
-                }
4228
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4229
-                $related_model_obj->_extract_related_model_info_from_query_param(
4230
-                    $possible_join_string,
4231
-                    $query_info_carrier,
4232
-                    $query_parameter_type,
4233
-                    $original_query_param
4234
-                );
4235
-                return true;
4236
-            }
4237
-            if ($possible_join_string === $valid_related_model_name) {
4238
-                $this->_add_join_to_model(
4239
-                    $valid_related_model_name,
4240
-                    $query_info_carrier,
4241
-                    $original_query_param
4242
-                );
4243
-                return true;
4244
-            }
4245
-        }
4246
-        return false;
4247
-    }
4248
-
4249
-
4250
-    /**
4251
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4252
-     *
4253
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4254
-     * @throws EE_Error
4255
-     */
4256
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4257
-    {
4258
-        if (
4259
-            $this->_custom_selections instanceof CustomSelects
4260
-            && (
4261
-                $this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4262
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4263
-            )
4264
-        ) {
4265
-            $original_selects = $this->_custom_selections->originalSelects();
4266
-            foreach ($original_selects as $alias => $select_configuration) {
4267
-                $this->extractJoinModelFromQueryParams(
4268
-                    $query_info_carrier,
4269
-                    $select_configuration[0],
4270
-                    $select_configuration[0],
4271
-                    'custom_selects'
4272
-                );
4273
-            }
4274
-        }
4275
-    }
4276
-
4277
-
4278
-    /**
4279
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4280
-     * and store it on $passed_in_query_info
4281
-     *
4282
-     * @param string                      $model_name
4283
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4284
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4285
-     *                                                          model and $model_name. Eg, if we are querying Event,
4286
-     *                                                          and are adding a join to 'Payment' with the original
4287
-     *                                                          query param key
4288
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4289
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4290
-     *                                                          Payment wants to add default query params so that it
4291
-     *                                                          will know what models to prepend onto its default query
4292
-     *                                                          params or in case it wants to rename tables (in case
4293
-     *                                                          there are multiple joins to the same table)
4294
-     * @return void
4295
-     * @throws EE_Error
4296
-     */
4297
-    private function _add_join_to_model(
4298
-        $model_name,
4299
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4300
-        $original_query_param
4301
-    ) {
4302
-        $relation_obj         = $this->related_settings_for($model_name);
4303
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4304
-        // check if the relation is HABTM, because then we're essentially doing two joins
4305
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4306
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4307
-            $join_model_obj = $relation_obj->get_join_model();
4308
-            // replace the model specified with the join model for this relation chain, whi
4309
-            $relation_chain_to_join_model =
4310
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4311
-                    $model_name,
4312
-                    $join_model_obj->get_this_model_name(),
4313
-                    $model_relation_chain
4314
-                );
4315
-            $passed_in_query_info->merge(
4316
-                new EE_Model_Query_Info_Carrier(
4317
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4318
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4319
-                )
4320
-            );
4321
-        }
4322
-        // now just join to the other table pointed to by the relation object, and add its data types
4323
-        $passed_in_query_info->merge(
4324
-            new EE_Model_Query_Info_Carrier(
4325
-                [$model_relation_chain => $model_name],
4326
-                $relation_obj->get_join_statement($model_relation_chain)
4327
-            )
4328
-        );
4329
-    }
4330
-
4331
-
4332
-    /**
4333
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4334
-     *
4335
-     * @param array $where_params @see
4336
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4337
-     * @return string of SQL
4338
-     * @throws EE_Error
4339
-     */
4340
-    private function _construct_where_clause($where_params)
4341
-    {
4342
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4343
-        if ($SQL) {
4344
-            return " WHERE " . $SQL;
4345
-        }
4346
-        return '';
4347
-    }
4348
-
4349
-
4350
-    /**
4351
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4352
-     * and should be passed HAVING parameters, not WHERE parameters
4353
-     *
4354
-     * @param array $having_params
4355
-     * @return string
4356
-     * @throws EE_Error
4357
-     */
4358
-    private function _construct_having_clause($having_params)
4359
-    {
4360
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4361
-        if ($SQL) {
4362
-            return " HAVING " . $SQL;
4363
-        }
4364
-        return '';
4365
-    }
4366
-
4367
-
4368
-    /**
4369
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4370
-     * Event_Meta.meta_value = 'foo'))"
4371
-     *
4372
-     * @param array  $where_params @see
4373
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4374
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4375
-     * @return string of SQL
4376
-     * @throws EE_Error
4377
-     */
4378
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4379
-    {
4380
-        $where_clauses = [];
4381
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4382
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4383
-            if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4384
-                switch ($query_param) {
4385
-                    case 'not':
4386
-                    case 'NOT':
4387
-                        $where_clauses[] = "! ("
4388
-                                           . $this->_construct_condition_clause_recursive(
4389
-                                $op_and_value_or_sub_condition,
4390
-                                $glue
4391
-                            )
4392
-                                           . ")";
4393
-                        break;
4394
-                    case 'and':
4395
-                    case 'AND':
4396
-                        $where_clauses[] = " ("
4397
-                                           . $this->_construct_condition_clause_recursive(
4398
-                                $op_and_value_or_sub_condition,
4399
-                                ' AND '
4400
-                            )
4401
-                                           . ")";
4402
-                        break;
4403
-                    case 'or':
4404
-                    case 'OR':
4405
-                        $where_clauses[] = " ("
4406
-                                           . $this->_construct_condition_clause_recursive(
4407
-                                $op_and_value_or_sub_condition,
4408
-                                ' OR '
4409
-                            )
4410
-                                           . ")";
4411
-                        break;
4412
-                }
4413
-            } else {
4414
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4415
-                // if it's not a normal field, maybe it's a custom selection?
4416
-                if (! $field_obj) {
4417
-                    if ($this->_custom_selections instanceof CustomSelects) {
4418
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4419
-                    } else {
4420
-                        throw new EE_Error(
4421
-                            sprintf(
4422
-                                esc_html__(
4423
-                                    "%s is neither a valid model field name, nor a custom selection",
4424
-                                    "event_espresso"
4425
-                                ),
4426
-                                $query_param
4427
-                            )
4428
-                        );
4429
-                    }
4430
-                }
4431
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4432
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4433
-            }
4434
-        }
4435
-        return $where_clauses
4436
-            ? implode($glue, $where_clauses)
4437
-            : '';
4438
-    }
4439
-
4440
-
4441
-    /**
4442
-     * Takes the input parameter and extract the table name (alias) and column name
4443
-     *
4444
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4445
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4446
-     * @throws EE_Error
4447
-     */
4448
-    private function _deduce_column_name_from_query_param($query_param)
4449
-    {
4450
-        $field = $this->_deduce_field_from_query_param($query_param);
4451
-        if ($field) {
4452
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4453
-                $field->get_model_name(),
4454
-                $query_param
4455
-            );
4456
-            return $table_alias_prefix . $field->get_qualified_column();
4457
-        }
4458
-        if (
4459
-            $this->_custom_selections instanceof CustomSelects
4460
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4461
-        ) {
4462
-            // maybe it's custom selection item?
4463
-            // if so, just use it as the "column name"
4464
-            return $query_param;
4465
-        }
4466
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4467
-            ? implode(',', $this->_custom_selections->columnAliases())
4468
-            : '';
4469
-        throw new EE_Error(
4470
-            sprintf(
4471
-                esc_html__(
4472
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4473
-                    "event_espresso"
4474
-                ),
4475
-                $query_param,
4476
-                $custom_select_aliases
4477
-            )
4478
-        );
4479
-    }
4480
-
4481
-
4482
-    /**
4483
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4484
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4485
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4486
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4487
-     *
4488
-     * @param string $condition_query_param_key
4489
-     * @return string
4490
-     */
4491
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4492
-    {
4493
-        $pos_of_star = strpos($condition_query_param_key, '*');
4494
-        if ($pos_of_star === false) {
4495
-            return $condition_query_param_key;
4496
-        }
4497
-        return substr($condition_query_param_key, 0, $pos_of_star);
4498
-    }
4499
-
4500
-
4501
-    /**
4502
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4503
-     *
4504
-     * @param array|string               $op_and_value
4505
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4506
-     * @return string
4507
-     * @throws EE_Error
4508
-     */
4509
-    private function _construct_op_and_value($op_and_value, $field_obj)
4510
-    {
4511
-        $operator = '=';
4512
-        $value    = $op_and_value;
4513
-        if (is_array($op_and_value)) {
4514
-            $operator = isset($op_and_value[0])
4515
-                ? $this->_prepare_operator_for_sql($op_and_value[0])
4516
-                : null;
4517
-            if (! $operator) {
4518
-                $php_array_like_string = [];
4519
-                foreach ($op_and_value as $key => $value) {
4520
-                    $php_array_like_string[] = "$key=>$value";
4521
-                }
4522
-                throw new EE_Error(
4523
-                    sprintf(
4524
-                        esc_html__(
4525
-                            "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))",
4526
-                            "event_espresso"
4527
-                        ),
4528
-                        implode(",", $php_array_like_string)
4529
-                    )
4530
-                );
4531
-            }
4532
-            $value = $op_and_value[1] ?? null;
4533
-        }
4534
-
4535
-        // check to see if the value is actually another field
4536
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4537
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4538
-        }
4539
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4540
-            // in this case, the value should be an array, or at least a comma-separated list
4541
-            // it will need to handle a little differently
4542
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4543
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4544
-            return $operator . SP . $cleaned_value;
4545
-        }
4546
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4547
-            // the value should be an array with count of two.
4548
-            if (count($value) !== 2) {
4549
-                throw new EE_Error(
4550
-                    sprintf(
4551
-                        esc_html__(
4552
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4553
-                            'event_espresso'
4554
-                        ),
4555
-                        "BETWEEN"
4556
-                    )
4557
-                );
4558
-            }
4559
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4560
-            return $operator . SP . $cleaned_value;
4561
-        }
4562
-        if (in_array($operator, $this->valid_null_style_operators())) {
4563
-            if ($value !== null) {
4564
-                throw new EE_Error(
4565
-                    sprintf(
4566
-                        esc_html__(
4567
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4568
-                            "event_espresso"
4569
-                        ),
4570
-                        $value,
4571
-                        $operator
4572
-                    )
4573
-                );
4574
-            }
4575
-            return $operator;
4576
-        }
4577
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4578
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4579
-            // remove other junk. So just treat it as a string.
4580
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4581
-        }
4582
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4583
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4584
-        }
4585
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4586
-            throw new EE_Error(
4587
-                sprintf(
4588
-                    esc_html__(
4589
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4590
-                        'event_espresso'
4591
-                    ),
4592
-                    $operator,
4593
-                    $operator
4594
-                )
4595
-            );
4596
-        }
4597
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4598
-            throw new EE_Error(
4599
-                sprintf(
4600
-                    esc_html__(
4601
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4602
-                        'event_espresso'
4603
-                    ),
4604
-                    $operator,
4605
-                    $operator
4606
-                )
4607
-            );
4608
-        }
4609
-        throw new EE_Error(
4610
-            sprintf(
4611
-                esc_html__(
4612
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4613
-                    "event_espresso"
4614
-                ),
4615
-                http_build_query($op_and_value)
4616
-            )
4617
-        );
4618
-    }
4619
-
4620
-
4621
-    /**
4622
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4623
-     *
4624
-     * @param array                      $values
4625
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4626
-     *                                              '%s'
4627
-     * @return string
4628
-     * @throws EE_Error
4629
-     */
4630
-    public function _construct_between_value($values, $field_obj)
4631
-    {
4632
-        $cleaned_values = [];
4633
-        foreach ($values as $value) {
4634
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4635
-        }
4636
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4637
-    }
4638
-
4639
-
4640
-    /**
4641
-     * Takes an array or a comma-separated list of $values and cleans them
4642
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4643
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4644
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4645
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4646
-     *
4647
-     * @param mixed                      $values    array or comma-separated string
4648
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4649
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4650
-     * @throws EE_Error
4651
-     */
4652
-    public function _construct_in_value($values, $field_obj)
4653
-    {
4654
-        $prepped = [];
4655
-        // check if the value is a CSV list
4656
-        if (is_string($values)) {
4657
-            // in which case, turn it into an array
4658
-            $values = explode(',', $values);
4659
-        }
4660
-        // make sure we only have one of each value in the list
4661
-        $values = array_unique($values);
4662
-        foreach ($values as $value) {
4663
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4664
-        }
4665
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4666
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4667
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4668
-        if (empty($prepped)) {
4669
-            $all_fields  = $this->field_settings();
4670
-            $first_field = reset($all_fields);
4671
-            $main_table  = $this->_get_main_table();
4672
-            $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4673
-        }
4674
-        return '(' . implode(',', $prepped) . ')';
4675
-    }
4676
-
4677
-
4678
-    /**
4679
-     * @param mixed                      $value
4680
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4681
-     * @return false|null|string
4682
-     * @throws EE_Error
4683
-     */
4684
-    private function _wpdb_prepare_using_field($value, $field_obj)
4685
-    {
4686
-        /** @type WPDB $wpdb */
4687
-        global $wpdb;
4688
-        if ($field_obj instanceof EE_Model_Field_Base) {
4689
-            return $wpdb->prepare(
4690
-                $field_obj->get_wpdb_data_type(),
4691
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4692
-            );
4693
-        } //$field_obj should really just be a data type
4694
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4695
-            throw new EE_Error(
4696
-                sprintf(
4697
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4698
-                    $field_obj,
4699
-                    implode(",", $this->_valid_wpdb_data_types)
4700
-                )
4701
-            );
4702
-        }
4703
-        return $wpdb->prepare($field_obj, $value);
4704
-    }
4705
-
4706
-
4707
-    /**
4708
-     * Takes the input parameter and finds the model field that it indicates.
4709
-     *
4710
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4711
-     * @return EE_Model_Field_Base
4712
-     * @throws EE_Error
4713
-     */
4714
-    protected function _deduce_field_from_query_param($query_param_name)
4715
-    {
4716
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4717
-        // which will help us find the database table and column
4718
-        $query_param_parts = explode(".", $query_param_name);
4719
-        if (empty($query_param_parts)) {
4720
-            throw new EE_Error(
4721
-                sprintf(
4722
-                    esc_html__(
4723
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4724
-                        'event_espresso'
4725
-                    ),
4726
-                    $query_param_name
4727
-                )
4728
-            );
4729
-        }
4730
-        $number_of_parts       = count($query_param_parts);
4731
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4732
-        if ($number_of_parts === 1) {
4733
-            $field_name = $last_query_param_part;
4734
-            $model_obj  = $this;
4735
-        } else {// $number_of_parts >= 2
4736
-            // the last part is the column name, and there are only 2parts. therefore...
4737
-            $field_name = $last_query_param_part;
4738
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4739
-        }
4740
-        try {
4741
-            return $model_obj->field_settings_for($field_name);
4742
-        } catch (EE_Error $e) {
4743
-            return null;
4744
-        }
4745
-    }
4746
-
4747
-
4748
-    /**
4749
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4750
-     * alias and column which corresponds to it
4751
-     *
4752
-     * @param string $field_name
4753
-     * @return string
4754
-     * @throws EE_Error
4755
-     */
4756
-    public function _get_qualified_column_for_field($field_name)
4757
-    {
4758
-        $all_fields = $this->field_settings();
4759
-        $field      = $all_fields[ $field_name ] ?? false;
4760
-        if ($field) {
4761
-            return $field->get_qualified_column();
4762
-        }
4763
-        throw new EE_Error(
4764
-            sprintf(
4765
-                esc_html__(
4766
-                    "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.",
4767
-                    'event_espresso'
4768
-                ),
4769
-                $field_name,
4770
-                get_class($this)
4771
-            )
4772
-        );
4773
-    }
4774
-
4775
-
4776
-    /**
4777
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4778
-     * Example usage:
4779
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4780
-     *      array(),
4781
-     *      ARRAY_A,
4782
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4783
-     *  );
4784
-     * is equivalent to
4785
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4786
-     * and
4787
-     *  EEM_Event::instance()->get_all_wpdb_results(
4788
-     *      array(
4789
-     *          array(
4790
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4791
-     *          ),
4792
-     *          ARRAY_A,
4793
-     *          implode(
4794
-     *              ', ',
4795
-     *              array_merge(
4796
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4797
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4798
-     *              )
4799
-     *          )
4800
-     *      )
4801
-     *  );
4802
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4803
-     *
4804
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4805
-     *                                            and the one whose fields you are selecting for example: when querying
4806
-     *                                            tickets model and selecting fields from the tickets model you would
4807
-     *                                            leave this parameter empty, because no models are needed to join
4808
-     *                                            between the queried model and the selected one. Likewise when
4809
-     *                                            querying the datetime model and selecting fields from the tickets
4810
-     *                                            model, it would also be left empty, because there is a direct
4811
-     *                                            relation from datetimes to tickets, so no model is needed to join
4812
-     *                                            them together. However, when querying from the event model and
4813
-     *                                            selecting fields from the ticket model, you should provide the string
4814
-     *                                            'Datetime', indicating that the event model must first join to the
4815
-     *                                            datetime model in order to find its relation to ticket model.
4816
-     *                                            Also, when querying from the venue model and selecting fields from
4817
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4818
-     *                                            indicating you need to join the venue model to the event model,
4819
-     *                                            to the datetime model, in order to find its relation to the ticket
4820
-     *                                            model. This string is used to deduce the prefix that gets added onto
4821
-     *                                            the models' tables qualified columns
4822
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4823
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4824
-     *                                            qualified column names
4825
-     * @return array|string
4826
-     */
4827
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4828
-    {
4829
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4830
-                ? ''
4831
-                : '__');
4832
-        $qualified_columns = [];
4833
-        foreach ($this->field_settings() as $field_name => $field) {
4834
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4835
-        }
4836
-        return $return_string
4837
-            ? implode(', ', $qualified_columns)
4838
-            : $qualified_columns;
4839
-    }
4840
-
4841
-
4842
-    /**
4843
-     * constructs the select use on special limit joins
4844
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4845
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4846
-     * (as that is typically where the limits would be set).
4847
-     *
4848
-     * @param string       $table_alias The table the select is being built for
4849
-     * @param mixed|string $limit       The limit for this select
4850
-     * @return string                The final select join element for the query.
4851
-     * @throws EE_Error
4852
-     * @throws EE_Error
4853
-     */
4854
-    public function _construct_limit_join_select($table_alias, $limit)
4855
-    {
4856
-        $SQL = '';
4857
-        foreach ($this->_tables as $table_obj) {
4858
-            if ($table_obj instanceof EE_Primary_Table) {
4859
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4860
-                    ? $table_obj->get_select_join_limit($limit)
4861
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4862
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4863
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4864
-                    ? $table_obj->get_select_join_limit_join($limit)
4865
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4866
-            }
4867
-        }
4868
-        return $SQL;
4869
-    }
4870
-
4871
-
4872
-    /**
4873
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4874
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4875
-     *
4876
-     * @return string SQL
4877
-     * @throws EE_Error
4878
-     */
4879
-    public function _construct_internal_join()
4880
-    {
4881
-        $SQL = $this->_get_main_table()->get_table_sql();
4882
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4883
-        return $SQL;
4884
-    }
4885
-
4886
-
4887
-    /**
4888
-     * Constructs the SQL for joining all the tables on this model.
4889
-     * Normally $alias should be the primary table's alias, but in cases where
4890
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4891
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4892
-     * alias, this will construct SQL like:
4893
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4894
-     * With $alias being a secondary table's alias, this will construct SQL like:
4895
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4896
-     *
4897
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4898
-     * @return string
4899
-     * @throws EE_Error
4900
-     * @throws EE_Error
4901
-     */
4902
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4903
-    {
4904
-        $SQL               = '';
4905
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4906
-        foreach ($this->_tables as $table_obj) {
4907
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4908
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4909
-                    // so we're joining to this table, meaning the table is already in
4910
-                    // the FROM statement, BUT the primary table isn't. So we want
4911
-                    // to add the inverse join sql
4912
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4913
-                } else {
4914
-                    // just add a regular JOIN to this table from the primary table
4915
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4916
-                }
4917
-            }// if it's a primary table, dont add any SQL. it should already be in the FROM statement
4918
-        }
4919
-        return $SQL;
4920
-    }
4921
-
4922
-
4923
-    /**
4924
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4925
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4926
-     * their data type (eg, '%s', '%d', etc)
4927
-     *
4928
-     * @return array
4929
-     */
4930
-    public function _get_data_types()
4931
-    {
4932
-        $data_types = [];
4933
-        foreach ($this->field_settings() as $field_obj) {
4934
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4935
-            /** @var $field_obj EE_Model_Field_Base */
4936
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4937
-        }
4938
-        return $data_types;
4939
-    }
4940
-
4941
-
4942
-    /**
4943
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4944
-     *
4945
-     * @param string $model_name
4946
-     * @return EEM_Base
4947
-     * @throws EE_Error
4948
-     */
4949
-    public function get_related_model_obj($model_name)
4950
-    {
4951
-        $model_classname = "EEM_" . $model_name;
4952
-        if (! class_exists($model_classname)) {
4953
-            throw new EE_Error(
4954
-                sprintf(
4955
-                    esc_html__(
4956
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4957
-                        'event_espresso'
4958
-                    ),
4959
-                    $model_name,
4960
-                    $model_classname
4961
-                )
4962
-            );
4963
-        }
4964
-        return call_user_func($model_classname . "::instance");
4965
-    }
4966
-
4967
-
4968
-    /**
4969
-     * Returns the array of EE_ModelRelations for this model.
4970
-     *
4971
-     * @return EE_Model_Relation_Base[]
4972
-     */
4973
-    public function relation_settings()
4974
-    {
4975
-        return $this->_model_relations;
4976
-    }
4977
-
4978
-
4979
-    /**
4980
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4981
-     * because without THOSE models, this model probably doesn't have much purpose.
4982
-     * (Eg, without an event, datetimes have little purpose.)
4983
-     *
4984
-     * @return EE_Belongs_To_Relation[]
4985
-     */
4986
-    public function belongs_to_relations()
4987
-    {
4988
-        $belongs_to_relations = [];
4989
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4990
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4991
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4992
-            }
4993
-        }
4994
-        return $belongs_to_relations;
4995
-    }
4996
-
4997
-
4998
-    /**
4999
-     * Returns the specified EE_Model_Relation, or throws an exception
5000
-     *
5001
-     * @param string $relation_name name of relation, key in $this->_relatedModels
5002
-     * @return EE_Model_Relation_Base
5003
-     * @throws EE_Error
5004
-     */
5005
-    public function related_settings_for($relation_name)
5006
-    {
5007
-        $relatedModels = $this->relation_settings();
5008
-        if (! array_key_exists($relation_name, $relatedModels)) {
5009
-            throw new EE_Error(
5010
-                sprintf(
5011
-                    esc_html__(
5012
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
5013
-                        'event_espresso'
5014
-                    ),
5015
-                    $relation_name,
5016
-                    $this->_get_class_name(),
5017
-                    implode(', ', array_keys($relatedModels))
5018
-                )
5019
-            );
5020
-        }
5021
-        return $relatedModels[ $relation_name ];
5022
-    }
5023
-
5024
-
5025
-    /**
5026
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
5027
-     * fields
5028
-     *
5029
-     * @param string  $fieldName
5030
-     * @param boolean $include_db_only_fields
5031
-     * @return EE_Model_Field_Base
5032
-     * @throws EE_Error
5033
-     */
5034
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
5035
-    {
5036
-        $fieldSettings = $this->field_settings($include_db_only_fields);
5037
-        if (! array_key_exists($fieldName, $fieldSettings)) {
5038
-            throw new EE_Error(
5039
-                sprintf(
5040
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
5041
-                    $fieldName,
5042
-                    get_class($this)
5043
-                )
5044
-            );
5045
-        }
5046
-        return $fieldSettings[ $fieldName ];
5047
-    }
5048
-
5049
-
5050
-    /**
5051
-     * Checks if this field exists on this model
5052
-     *
5053
-     * @param string $fieldName a key in the model's _field_settings array
5054
-     * @return boolean
5055
-     */
5056
-    public function has_field($fieldName)
5057
-    {
5058
-        $fieldSettings = $this->field_settings(true);
5059
-        if (isset($fieldSettings[ $fieldName ])) {
5060
-            return true;
5061
-        }
5062
-        return false;
5063
-    }
5064
-
5065
-
5066
-    /**
5067
-     * Returns whether or not this model has a relation to the specified model
5068
-     *
5069
-     * @param string $relation_name possibly one of the keys in the relation_settings array
5070
-     * @return boolean
5071
-     */
5072
-    public function has_relation($relation_name)
5073
-    {
5074
-        $relations = $this->relation_settings();
5075
-        if (isset($relations[ $relation_name ])) {
5076
-            return true;
5077
-        }
5078
-        return false;
5079
-    }
5080
-
5081
-
5082
-    /**
5083
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5084
-     * Eg, on EE_Answer that would be ANS_ID field object
5085
-     *
5086
-     * @param $field_obj
5087
-     * @return boolean
5088
-     */
5089
-    public function is_primary_key_field($field_obj): bool
5090
-    {
5091
-        return $field_obj instanceof EE_Primary_Key_Field_Base;
5092
-    }
5093
-
5094
-
5095
-    /**
5096
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5097
-     * Eg, on EE_Answer that would be ANS_ID field object
5098
-     *
5099
-     * @return EE_Primary_Key_Field_Base
5100
-     * @throws EE_Error
5101
-     */
5102
-    public function get_primary_key_field()
5103
-    {
5104
-        if ($this->_primary_key_field === null) {
5105
-            foreach ($this->field_settings(true) as $field_obj) {
5106
-                if ($this->is_primary_key_field($field_obj)) {
5107
-                    $this->_primary_key_field = $field_obj;
5108
-                    break;
5109
-                }
5110
-            }
5111
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5112
-                throw new EE_Error(
5113
-                    sprintf(
5114
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5115
-                        get_class($this)
5116
-                    )
5117
-                );
5118
-            }
5119
-        }
5120
-        return $this->_primary_key_field;
5121
-    }
5122
-
5123
-
5124
-    /**
5125
-     * Returns whether or not not there is a primary key on this model.
5126
-     * Internally does some caching.
5127
-     *
5128
-     * @return boolean
5129
-     */
5130
-    public function has_primary_key_field()
5131
-    {
5132
-        if ($this->_has_primary_key_field === null) {
5133
-            try {
5134
-                $this->get_primary_key_field();
5135
-                $this->_has_primary_key_field = true;
5136
-            } catch (EE_Error $e) {
5137
-                $this->_has_primary_key_field = false;
5138
-            }
5139
-        }
5140
-        return $this->_has_primary_key_field;
5141
-    }
5142
-
5143
-
5144
-    /**
5145
-     * Finds the first field of type $field_class_name.
5146
-     *
5147
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5148
-     *                                 EE_Foreign_Key_Field, etc
5149
-     * @return EE_Model_Field_Base or null if none is found
5150
-     */
5151
-    public function get_a_field_of_type($field_class_name)
5152
-    {
5153
-        foreach ($this->field_settings() as $field) {
5154
-            if ($field instanceof $field_class_name) {
5155
-                return $field;
5156
-            }
5157
-        }
5158
-        return null;
5159
-    }
5160
-
5161
-
5162
-    /**
5163
-     * Gets a foreign key field pointing to model.
5164
-     *
5165
-     * @param string $model_name eg Event, Registration, not EEM_Event
5166
-     * @return EE_Foreign_Key_Field_Base
5167
-     * @throws EE_Error
5168
-     */
5169
-    public function get_foreign_key_to($model_name)
5170
-    {
5171
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5172
-            foreach ($this->field_settings() as $field) {
5173
-                if (
5174
-                    $field instanceof EE_Foreign_Key_Field_Base
5175
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5176
-                ) {
5177
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5178
-                    break;
5179
-                }
5180
-            }
5181
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5182
-                throw new EE_Error(
5183
-                    sprintf(
5184
-                        esc_html__(
5185
-                            "There is no foreign key field pointing to model %s on model %s",
5186
-                            'event_espresso'
5187
-                        ),
5188
-                        $model_name,
5189
-                        get_class($this)
5190
-                    )
5191
-                );
5192
-            }
5193
-        }
5194
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5195
-    }
5196
-
5197
-
5198
-    /**
5199
-     * Gets the table name (including $wpdb->prefix) for the table alias
5200
-     *
5201
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5202
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5203
-     *                            Either one works
5204
-     * @return string
5205
-     */
5206
-    public function get_table_for_alias($table_alias)
5207
-    {
5208
-        $table_alias_sans_model_relation_chain_prefix =
5209
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5210
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5211
-    }
5212
-
5213
-
5214
-    /**
5215
-     * Returns a flat array of all field son this model, instead of organizing them
5216
-     * by table_alias as they are in the constructor.
5217
-     *
5218
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5219
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5220
-     */
5221
-    public function field_settings($include_db_only_fields = false)
5222
-    {
5223
-        if ($include_db_only_fields) {
5224
-            if ($this->_cached_fields === null) {
5225
-                $this->_cached_fields = [];
5226
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5227
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5228
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5229
-                    }
5230
-                }
5231
-            }
5232
-            return $this->_cached_fields;
5233
-        }
5234
-        if ($this->_cached_fields_non_db_only === null) {
5235
-            $this->_cached_fields_non_db_only = [];
5236
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5237
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5238
-                    /** @var $field_obj EE_Model_Field_Base */
5239
-                    if (! $field_obj->is_db_only_field()) {
5240
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5241
-                    }
5242
-                }
5243
-            }
5244
-        }
5245
-        return $this->_cached_fields_non_db_only;
5246
-    }
5247
-
5248
-
5249
-    /**
5250
-     *        cycle though array of attendees and create objects out of each item
5251
-     *
5252
-     * @access        private
5253
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5254
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5255
-     *                           numerically indexed)
5256
-     * @throws EE_Error
5257
-     * @throws ReflectionException
5258
-     */
5259
-    protected function _create_objects($rows = [])
5260
-    {
5261
-        $array_of_objects = [];
5262
-        if (empty($rows)) {
5263
-            return [];
5264
-        }
5265
-        $count_if_model_has_no_primary_key = 0;
5266
-        $has_primary_key                   = $this->has_primary_key_field();
5267
-        $primary_key_field                 = $has_primary_key
5268
-            ? $this->get_primary_key_field()
5269
-            : null;
5270
-        foreach ((array) $rows as $row) {
5271
-            if (empty($row)) {
5272
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5273
-                return [];
5274
-            }
5275
-            // check if we've already set this object in the results array,
5276
-            // in which case there's no need to process it further (again)
5277
-            if ($has_primary_key) {
5278
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5279
-                    $row,
5280
-                    $primary_key_field->get_qualified_column(),
5281
-                    $primary_key_field->get_table_column()
5282
-                );
5283
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5284
-                    continue;
5285
-                }
5286
-            }
5287
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5288
-            if (! $classInstance) {
5289
-                throw new EE_Error(
5290
-                    sprintf(
5291
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5292
-                        $this->get_this_model_name(),
5293
-                        http_build_query($row)
5294
-                    )
5295
-                );
5296
-            }
5297
-            // set the timezone on the instantiated objects
5298
-            $classInstance->set_timezone($this->_timezone);
5299
-            // make sure if there is any timezone setting present that we set the timezone for the object
5300
-            $key                      = $has_primary_key
5301
-                ? $classInstance->ID()
5302
-                : $count_if_model_has_no_primary_key++;
5303
-            $array_of_objects[ $key ] = $classInstance;
5304
-            // also, for all the relations of type BelongsTo, see if we can cache
5305
-            // those related models
5306
-            // (we could do this for other relations too, but if there are conditions
5307
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5308
-            // so it requires a little more thought than just caching them immediately...)
5309
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5310
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5311
-                    // check if this model's INFO is present. If so, cache it on the model
5312
-                    $other_model           = $relation_obj->get_other_model();
5313
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5314
-                    // if we managed to make a model object from the results, cache it on the main model object
5315
-                    if ($other_model_obj_maybe) {
5316
-                        // set timezone on these other model objects if they are present
5317
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5318
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5319
-                    }
5320
-                }
5321
-            }
5322
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5323
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5324
-            // the field in the CustomSelects object
5325
-            if ($this->_custom_selections instanceof CustomSelects) {
5326
-                $classInstance->setCustomSelectsValues(
5327
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5328
-                );
5329
-            }
5330
-        }
5331
-        return $array_of_objects;
5332
-    }
5333
-
5334
-
5335
-    /**
5336
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5337
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5338
-     *
5339
-     * @param array $db_results_row
5340
-     * @return array
5341
-     */
5342
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5343
-    {
5344
-        $results = [];
5345
-        if ($this->_custom_selections instanceof CustomSelects) {
5346
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5347
-                if (isset($db_results_row[ $alias ])) {
5348
-                    $results[ $alias ] = $this->convertValueToDataType(
5349
-                        $db_results_row[ $alias ],
5350
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5351
-                    );
5352
-                }
5353
-            }
5354
-        }
5355
-        return $results;
5356
-    }
5357
-
5358
-
5359
-    /**
5360
-     * This will set the value for the given alias
5361
-     *
5362
-     * @param string $value
5363
-     * @param string $datatype (one of %d, %s, %f)
5364
-     * @return int|string|float (int for %d, string for %s, float for %f)
5365
-     */
5366
-    protected function convertValueToDataType($value, $datatype)
5367
-    {
5368
-        switch ($datatype) {
5369
-            case '%f':
5370
-                return (float) $value;
5371
-            case '%d':
5372
-                return (int) $value;
5373
-            default:
5374
-                return (string) $value;
5375
-        }
5376
-    }
5377
-
5378
-
5379
-    /**
5380
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5381
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5382
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5383
-     * object (as set in the model_field!).
5384
-     *
5385
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5386
-     * @throws EE_Error
5387
-     * @throws ReflectionException
5388
-     */
5389
-    public function create_default_object()
5390
-    {
5391
-        $this_model_fields_and_values = [];
5392
-        // setup the row using default values;
5393
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5394
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5395
-        }
5396
-        $className = $this->_get_class_name();
5397
-        return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5398
-    }
5399
-
5400
-
5401
-    /**
5402
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5403
-     *                             or an stdClass where each property is the name of a column,
5404
-     * @return EE_Base_Class
5405
-     * @throws EE_Error
5406
-     * @throws ReflectionException
5407
-     */
5408
-    public function instantiate_class_from_array_or_object($cols_n_values)
5409
-    {
5410
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5411
-            $cols_n_values = get_object_vars($cols_n_values);
5412
-        }
5413
-        $primary_key = null;
5414
-        // make sure the array only has keys that are fields/columns on this model
5415
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5416
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5417
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5418
-        }
5419
-        $className = $this->_get_class_name();
5420
-        // check we actually found results that we can use to build our model object
5421
-        // if not, return null
5422
-        if ($this->has_primary_key_field()) {
5423
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5424
-                return null;
5425
-            }
5426
-        } elseif ($this->unique_indexes()) {
5427
-            $first_column = reset($this_model_fields_n_values);
5428
-            if (empty($first_column)) {
5429
-                return null;
5430
-            }
5431
-        }
5432
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5433
-        if ($primary_key) {
5434
-            $classInstance = $this->get_from_entity_map($primary_key);
5435
-            if (! $classInstance) {
5436
-                $classInstance = EE_Registry::instance()
5437
-                                            ->load_class(
5438
-                                                $className,
5439
-                                                [$this_model_fields_n_values, $this->_timezone],
5440
-                                                true,
5441
-                                                false
5442
-                                            );
5443
-                // add this new object to the entity map
5444
-                $classInstance = $this->add_to_entity_map($classInstance);
5445
-            }
5446
-        } else {
5447
-            $classInstance = EE_Registry::instance()->load_class(
5448
-                $className,
5449
-                [$this_model_fields_n_values, $this->_timezone],
5450
-                true,
5451
-                false
5452
-            );
5453
-        }
5454
-        return $classInstance;
5455
-    }
5456
-
5457
-
5458
-    /**
5459
-     * Gets the model object from the  entity map if it exists
5460
-     *
5461
-     * @param int|string $id the ID of the model object
5462
-     * @return EE_Base_Class
5463
-     */
5464
-    public function get_from_entity_map($id)
5465
-    {
5466
-        return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5467
-    }
5468
-
5469
-
5470
-    /**
5471
-     * add_to_entity_map
5472
-     * Adds the object to the model's entity mappings
5473
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5474
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5475
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5476
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5477
-     *        then this method should be called immediately after the update query
5478
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5479
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5480
-     *
5481
-     * @param EE_Base_Class $object
5482
-     * @return EE_Base_Class
5483
-     * @throws EE_Error
5484
-     * @throws ReflectionException
5485
-     */
5486
-    public function add_to_entity_map(EE_Base_Class $object)
5487
-    {
5488
-        $className = $this->_get_class_name();
5489
-        if (! $object instanceof $className) {
5490
-            throw new EE_Error(
5491
-                sprintf(
5492
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5493
-                    is_object($object)
5494
-                        ? get_class($object)
5495
-                        : $object,
5496
-                    $className
5497
-                )
5498
-            );
5499
-        }
5500
-
5501
-        if (! $object->ID()) {
5502
-            throw new EE_Error(
5503
-                sprintf(
5504
-                    esc_html__(
5505
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5506
-                        "event_espresso"
5507
-                    ),
5508
-                    get_class($this)
5509
-                )
5510
-            );
5511
-        }
5512
-        // double check it's not already there
5513
-        $classInstance = $this->get_from_entity_map($object->ID());
5514
-        if ($classInstance) {
5515
-            return $classInstance;
5516
-        }
5517
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5518
-        return $object;
5519
-    }
5520
-
5521
-
5522
-    /**
5523
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5524
-     * if no identifier is provided, then the entire entity map is emptied
5525
-     *
5526
-     * @param int|string $id the ID of the model object
5527
-     * @return boolean
5528
-     */
5529
-    public function clear_entity_map($id = null)
5530
-    {
5531
-        if (empty($id)) {
5532
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5533
-            return true;
5534
-        }
5535
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5536
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5537
-            return true;
5538
-        }
5539
-        return false;
5540
-    }
5541
-
5542
-
5543
-    /**
5544
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5545
-     * Given an array where keys are column (or column alias) names and values,
5546
-     * returns an array of their corresponding field names and database values
5547
-     *
5548
-     * @param array $cols_n_values
5549
-     * @return array
5550
-     * @throws EE_Error
5551
-     * @throws ReflectionException
5552
-     */
5553
-    public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5554
-    {
5555
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5556
-    }
5557
-
5558
-
5559
-    /**
5560
-     * _deduce_fields_n_values_from_cols_n_values
5561
-     * Given an array where keys are column (or column alias) names and values,
5562
-     * returns an array of their corresponding field names and database values
5563
-     *
5564
-     * @param array|stdClass $cols_n_values
5565
-     * @return array
5566
-     * @throws EE_Error
5567
-     * @throws ReflectionException
5568
-     */
5569
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5570
-    {
5571
-        if ($cols_n_values instanceof stdClass) {
5572
-            $cols_n_values = get_object_vars($cols_n_values);
5573
-        }
5574
-        $this_model_fields_n_values = [];
5575
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5576
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5577
-                $cols_n_values,
5578
-                $table_obj->get_fully_qualified_pk_column(),
5579
-                $table_obj->get_pk_column()
5580
-            );
5581
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5582
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5583
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5584
-                    if (! $field_obj->is_db_only_field()) {
5585
-                        // prepare field as if its coming from db
5586
-                        $prepared_value                            =
5587
-                            $field_obj->prepare_for_set($field_obj->get_default_value());
5588
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5589
-                    }
5590
-                }
5591
-            } else {
5592
-                // the table's rows existed. Use their values
5593
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5594
-                    if (! $field_obj->is_db_only_field()) {
5595
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5596
-                            $cols_n_values,
5597
-                            $field_obj->get_qualified_column(),
5598
-                            $field_obj->get_table_column()
5599
-                        );
5600
-                    }
5601
-                }
5602
-            }
5603
-        }
5604
-        return $this_model_fields_n_values;
5605
-    }
5606
-
5607
-
5608
-    /**
5609
-     * @param $cols_n_values
5610
-     * @param $qualified_column
5611
-     * @param $regular_column
5612
-     * @return null
5613
-     * @throws EE_Error
5614
-     * @throws ReflectionException
5615
-     */
5616
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5617
-    {
5618
-        $value = null;
5619
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5620
-        // does the field on the model relate to this column retrieved from the db?
5621
-        // or is it a db-only field? (not relating to the model)
5622
-        if (isset($cols_n_values[ $qualified_column ])) {
5623
-            $value = $cols_n_values[ $qualified_column ];
5624
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5625
-            $value = $cols_n_values[ $regular_column ];
5626
-        } elseif (! empty($this->foreign_key_aliases)) {
5627
-            // no PK?  ok check if there is a foreign key alias set for this table
5628
-            // then check if that alias exists in the incoming data
5629
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5630
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5631
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5632
-                    $value = $cols_n_values[ $FK_alias ];
5633
-                    [$pk_class] = explode('.', $PK_column);
5634
-                    $pk_model_name = "EEM_{$pk_class}";
5635
-                    /** @var EEM_Base $pk_model */
5636
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5637
-                    if ($pk_model instanceof EEM_Base) {
5638
-                        // make sure object is pulled from db and added to entity map
5639
-                        $pk_model->get_one_by_ID($value);
5640
-                    }
5641
-                    break;
5642
-                }
5643
-            }
5644
-        }
5645
-        return $value;
5646
-    }
5647
-
5648
-
5649
-    /**
5650
-     * refresh_entity_map_from_db
5651
-     * Makes sure the model object in the entity map at $id assumes the values
5652
-     * of the database (opposite of EE_base_Class::save())
5653
-     *
5654
-     * @param int|string $id
5655
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5656
-     * @throws EE_Error
5657
-     * @throws ReflectionException
5658
-     */
5659
-    public function refresh_entity_map_from_db($id)
5660
-    {
5661
-        $obj_in_map = $this->get_from_entity_map($id);
5662
-        if ($obj_in_map) {
5663
-            $wpdb_results = $this->_get_all_wpdb_results(
5664
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5665
-            );
5666
-            if ($wpdb_results && is_array($wpdb_results)) {
5667
-                $one_row = reset($wpdb_results);
5668
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5669
-                    $obj_in_map->set_from_db($field_name, $db_value);
5670
-                }
5671
-                // clear the cache of related model objects
5672
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5673
-                    $obj_in_map->clear_cache($relation_name, null, true);
5674
-                }
5675
-            }
5676
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5677
-            return $obj_in_map;
5678
-        }
5679
-        return $this->get_one_by_ID($id);
5680
-    }
5681
-
5682
-
5683
-    /**
5684
-     * refresh_entity_map_with
5685
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5686
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5687
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5688
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5689
-     *
5690
-     * @param int|string    $id
5691
-     * @param EE_Base_Class $replacing_model_obj
5692
-     * @return EE_Base_Class
5693
-     * @throws EE_Error
5694
-     * @throws ReflectionException
5695
-     */
5696
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5697
-    {
5698
-        $obj_in_map = $this->get_from_entity_map($id);
5699
-        if ($obj_in_map) {
5700
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5701
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5702
-                    $obj_in_map->set($field_name, $value);
5703
-                }
5704
-                // make the model object in the entity map's cache match the $replacing_model_obj
5705
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5706
-                    $obj_in_map->clear_cache($relation_name, null, true);
5707
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5708
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5709
-                    }
5710
-                }
5711
-            }
5712
-            return $obj_in_map;
5713
-        }
5714
-        $this->add_to_entity_map($replacing_model_obj);
5715
-        return $replacing_model_obj;
5716
-    }
5717
-
5718
-
5719
-    /**
5720
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5721
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5722
-     * require_once($this->_getClassName().".class.php");
5723
-     *
5724
-     * @return string
5725
-     */
5726
-    private function _get_class_name()
5727
-    {
5728
-        return "EE_" . $this->get_this_model_name();
5729
-    }
5730
-
5731
-
5732
-    /**
5733
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5734
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5735
-     * it would be 'Events'.
5736
-     *
5737
-     * @param int|float|null $quantity
5738
-     * @return string
5739
-     */
5740
-    public function item_name($quantity = 1): string
5741
-    {
5742
-        $quantity = floor($quantity);
5743
-        return apply_filters(
5744
-            'FHEE__EEM_Base__item_name__plural_or_singular',
5745
-            $quantity > 1
5746
-                ? $this->plural_item
5747
-                : $this->singular_item,
5748
-            $quantity,
5749
-            $this->plural_item,
5750
-            $this->singular_item
5751
-        );
5752
-    }
5753
-
5754
-
5755
-    /**
5756
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5757
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5758
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5759
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5760
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5761
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5762
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5763
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5764
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5765
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5766
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5767
-     *        return $previousReturnValue.$returnString;
5768
-     * }
5769
-     * require('EEM_Answer.model.php');
5770
-     * echo EEM_Answer::instance()->my_callback('monkeys',100);
5771
-     * // will output "you called my_callback! and passed args:monkeys,100"
5772
-     *
5773
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5774
-     * @param array  $args       array of original arguments passed to the function
5775
-     * @return mixed whatever the plugin which calls add_filter decides
5776
-     * @throws EE_Error
5777
-     */
5778
-    public function __call($methodName, $args)
5779
-    {
5780
-        $className = get_class($this);
5781
-        $tagName   = "FHEE__{$className}__{$methodName}";
5782
-        if (! has_filter($tagName)) {
5783
-            throw new EE_Error(
5784
-                sprintf(
5785
-                    esc_html__(
5786
-                        '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 );',
5787
-                        'event_espresso'
5788
-                    ),
5789
-                    $methodName,
5790
-                    $className,
5791
-                    $tagName,
5792
-                    '<br />'
5793
-                )
5794
-            );
5795
-        }
5796
-        return apply_filters($tagName, null, $this, $args);
5797
-    }
5798
-
5799
-
5800
-    /**
5801
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5802
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5803
-     *
5804
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5805
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5806
-     *                                                       the object's class name
5807
-     *                                                       or object's ID
5808
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5809
-     *                                                       exists in the database. If it does not, we add it
5810
-     * @return EE_Base_Class
5811
-     * @throws EE_Error
5812
-     * @throws ReflectionException
5813
-     */
5814
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5815
-    {
5816
-        $className = $this->_get_class_name();
5817
-        if ($base_class_obj_or_id instanceof $className) {
5818
-            $model_object = $base_class_obj_or_id;
5819
-        } else {
5820
-            $primary_key_field = $this->get_primary_key_field();
5821
-            if (
5822
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5823
-                && (
5824
-                    is_int($base_class_obj_or_id)
5825
-                    || is_string($base_class_obj_or_id)
5826
-                )
5827
-            ) {
5828
-                // assume it's an ID.
5829
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5830
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5831
-            } elseif (
5832
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5833
-                && is_string($base_class_obj_or_id)
5834
-            ) {
5835
-                // assume its a string representation of the object
5836
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5837
-            } else {
5838
-                throw new EE_Error(
5839
-                    sprintf(
5840
-                        esc_html__(
5841
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5842
-                            'event_espresso'
5843
-                        ),
5844
-                        $base_class_obj_or_id,
5845
-                        $this->_get_class_name(),
5846
-                        print_r($base_class_obj_or_id, true)
5847
-                    )
5848
-                );
5849
-            }
5850
-        }
5851
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5852
-            $model_object->save();
5853
-        }
5854
-        return $model_object;
5855
-    }
5856
-
5857
-
5858
-    /**
5859
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5860
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5861
-     * returns it ID.
5862
-     *
5863
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5864
-     * @return int|string depending on the type of this model object's ID
5865
-     * @throws EE_Error
5866
-     * @throws ReflectionException
5867
-     */
5868
-    public function ensure_is_ID($base_class_obj_or_id)
5869
-    {
5870
-        $className = $this->_get_class_name();
5871
-        if ($base_class_obj_or_id instanceof $className) {
5872
-            /** @var $base_class_obj_or_id EE_Base_Class */
5873
-            $id = $base_class_obj_or_id->ID();
5874
-        } elseif (is_int($base_class_obj_or_id)) {
5875
-            // assume it's an ID
5876
-            $id = $base_class_obj_or_id;
5877
-        } elseif (is_string($base_class_obj_or_id)) {
5878
-            // assume its a string representation of the object
5879
-            $id = $base_class_obj_or_id;
5880
-        } else {
5881
-            throw new EE_Error(
5882
-                sprintf(
5883
-                    esc_html__(
5884
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5885
-                        'event_espresso'
5886
-                    ),
5887
-                    $base_class_obj_or_id,
5888
-                    $this->_get_class_name(),
5889
-                    print_r($base_class_obj_or_id, true)
5890
-                )
5891
-            );
5892
-        }
5893
-        return $id;
5894
-    }
5895
-
5896
-
5897
-    /**
5898
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5899
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5900
-     * been sanitized and converted into the appropriate domain.
5901
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5902
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5903
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5904
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5905
-     * $EVT = EEM_Event::instance(); $old_setting =
5906
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5907
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5908
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5909
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5910
-     *
5911
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5912
-     * @return void
5913
-     */
5914
-    public function assume_values_already_prepared_by_model_object(
5915
-        $values_already_prepared = self::not_prepared_by_model_object
5916
-    ) {
5917
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5918
-    }
5919
-
5920
-
5921
-    /**
5922
-     * Read comments for assume_values_already_prepared_by_model_object()
5923
-     *
5924
-     * @return int
5925
-     */
5926
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5927
-    {
5928
-        return $this->_values_already_prepared_by_model_object;
5929
-    }
5930
-
5931
-
5932
-    /**
5933
-     * Gets all the indexes on this model
5934
-     *
5935
-     * @return EE_Index[]
5936
-     */
5937
-    public function indexes()
5938
-    {
5939
-        return $this->_indexes;
5940
-    }
5941
-
5942
-
5943
-    /**
5944
-     * Gets all the Unique Indexes on this model
5945
-     *
5946
-     * @return EE_Unique_Index[]
5947
-     */
5948
-    public function unique_indexes()
5949
-    {
5950
-        $unique_indexes = [];
5951
-        foreach ($this->_indexes as $name => $index) {
5952
-            if ($index instanceof EE_Unique_Index) {
5953
-                $unique_indexes [ $name ] = $index;
5954
-            }
5955
-        }
5956
-        return $unique_indexes;
5957
-    }
5958
-
5959
-
5960
-    /**
5961
-     * Gets all the fields which, when combined, make the primary key.
5962
-     * This is usually just an array with 1 element (the primary key), but in cases
5963
-     * where there is no primary key, it's a combination of fields as defined
5964
-     * on a primary index
5965
-     *
5966
-     * @return EE_Model_Field_Base[] indexed by the field's name
5967
-     * @throws EE_Error
5968
-     */
5969
-    public function get_combined_primary_key_fields()
5970
-    {
5971
-        foreach ($this->indexes() as $index) {
5972
-            if ($index instanceof EE_Primary_Key_Index) {
5973
-                return $index->fields();
5974
-            }
5975
-        }
5976
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5977
-    }
5978
-
5979
-
5980
-    /**
5981
-     * Used to build a primary key string (when the model has no primary key),
5982
-     * which can be used a unique string to identify this model object.
5983
-     *
5984
-     * @param array $fields_n_values keys are field names, values are their values.
5985
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5986
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5987
-     *                               before passing it to this function (that will convert it from columns-n-values
5988
-     *                               to field-names-n-values).
5989
-     * @return string
5990
-     * @throws EE_Error
5991
-     */
5992
-    public function get_index_primary_key_string($fields_n_values)
5993
-    {
5994
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5995
-            $fields_n_values,
5996
-            $this->get_combined_primary_key_fields()
5997
-        );
5998
-        return http_build_query($cols_n_values_for_primary_key_index);
5999
-    }
6000
-
6001
-
6002
-    /**
6003
-     * Gets the field values from the primary key string
6004
-     *
6005
-     * @param string $index_primary_key_string
6006
-     * @return null|array
6007
-     * @throws EE_Error
6008
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
6009
-     */
6010
-    public function parse_index_primary_key_string($index_primary_key_string)
6011
-    {
6012
-        $key_fields = $this->get_combined_primary_key_fields();
6013
-        // check all of them are in the $id
6014
-        $key_vals_in_combined_pk = [];
6015
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6016
-        foreach ($key_fields as $key_field_name => $field_obj) {
6017
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6018
-                return null;
6019
-            }
6020
-        }
6021
-        return $key_vals_in_combined_pk;
6022
-    }
6023
-
6024
-
6025
-    /**
6026
-     * verifies that an array of key-value pairs for model fields has a key
6027
-     * for each field comprising the primary key index
6028
-     *
6029
-     * @param array $key_vals
6030
-     * @return boolean
6031
-     * @throws EE_Error
6032
-     */
6033
-    public function has_all_combined_primary_key_fields($key_vals)
6034
-    {
6035
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6036
-        foreach ($keys_it_should_have as $key) {
6037
-            if (! isset($key_vals[ $key ])) {
6038
-                return false;
6039
-            }
6040
-        }
6041
-        return true;
6042
-    }
6043
-
6044
-
6045
-    /**
6046
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
6047
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
6048
-     *
6049
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
6050
-     * @param array               $query_params                     @see
6051
-     *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
6052
-     * @throws EE_Error
6053
-     * @throws ReflectionException
6054
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
6055
-     *                                                              indexed)
6056
-     */
6057
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
6058
-    {
6059
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
6060
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
6061
-        } elseif (is_array($model_object_or_attributes_array)) {
6062
-            $attributes_array = $model_object_or_attributes_array;
6063
-        } else {
6064
-            throw new EE_Error(
6065
-                sprintf(
6066
-                    esc_html__(
6067
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
6068
-                        "event_espresso"
6069
-                    ),
6070
-                    $model_object_or_attributes_array
6071
-                )
6072
-            );
6073
-        }
6074
-        // even copies obviously won't have the same ID, so remove the primary key
6075
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
6076
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6077
-            unset($attributes_array[ $this->primary_key_name() ]);
6078
-        }
6079
-        if (isset($query_params[0])) {
6080
-            $query_params[0] = array_merge($attributes_array, $query_params);
6081
-        } else {
6082
-            $query_params[0] = $attributes_array;
6083
-        }
6084
-        return $this->get_all($query_params);
6085
-    }
6086
-
6087
-
6088
-    /**
6089
-     * Gets the first copy we find. See get_all_copies for more details
6090
-     *
6091
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6092
-     * @param array $query_params
6093
-     * @return EE_Base_Class
6094
-     * @throws EE_Error
6095
-     * @throws ReflectionException
6096
-     */
6097
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6098
-    {
6099
-        if (! is_array($query_params)) {
6100
-            EE_Error::doing_it_wrong(
6101
-                'EEM_Base::get_one_copy',
6102
-                sprintf(
6103
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6104
-                    gettype($query_params)
6105
-                ),
6106
-                '4.6.0'
6107
-            );
6108
-            $query_params = [];
6109
-        }
6110
-        $query_params['limit'] = 1;
6111
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6112
-        if (is_array($copies)) {
6113
-            return array_shift($copies);
6114
-        }
6115
-        return null;
6116
-    }
6117
-
6118
-
6119
-    /**
6120
-     * Updates the item with the specified id. Ignores default query parameters because
6121
-     * we have specified the ID, and its assumed we KNOW what we're doing
6122
-     *
6123
-     * @param array      $fields_n_values keys are field names, values are their new values
6124
-     * @param int|string $id              the value of the primary key to update
6125
-     * @return int number of rows updated
6126
-     * @throws EE_Error
6127
-     * @throws ReflectionException
6128
-     */
6129
-    public function update_by_ID($fields_n_values, $id)
6130
-    {
6131
-        $query_params = [
6132
-            0                          => [$this->get_primary_key_field()->get_name() => $id],
6133
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6134
-        ];
6135
-        return $this->update($fields_n_values, $query_params);
6136
-    }
6137
-
6138
-
6139
-    /**
6140
-     * Changes an operator which was supplied to the models into one usable in SQL
6141
-     *
6142
-     * @param string $operator_supplied
6143
-     * @return string an operator which can be used in SQL
6144
-     * @throws EE_Error
6145
-     */
6146
-    private function _prepare_operator_for_sql($operator_supplied)
6147
-    {
6148
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6149
-        if ($sql_operator) {
6150
-            return $sql_operator;
6151
-        }
6152
-        throw new EE_Error(
6153
-            sprintf(
6154
-                esc_html__(
6155
-                    "The operator '%s' is not in the list of valid operators: %s",
6156
-                    "event_espresso"
6157
-                ),
6158
-                $operator_supplied,
6159
-                implode(",", array_keys($this->_valid_operators))
6160
-            )
6161
-        );
6162
-    }
6163
-
6164
-
6165
-    /**
6166
-     * Gets the valid operators
6167
-     *
6168
-     * @return array keys are accepted strings, values are the SQL they are converted to
6169
-     */
6170
-    public function valid_operators()
6171
-    {
6172
-        return $this->_valid_operators;
6173
-    }
6174
-
6175
-
6176
-    /**
6177
-     * Gets the between-style operators (take 2 arguments).
6178
-     *
6179
-     * @return array keys are accepted strings, values are the SQL they are converted to
6180
-     */
6181
-    public function valid_between_style_operators()
6182
-    {
6183
-        return array_intersect(
6184
-            $this->valid_operators(),
6185
-            $this->_between_style_operators
6186
-        );
6187
-    }
6188
-
6189
-
6190
-    /**
6191
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6192
-     *
6193
-     * @return array keys are accepted strings, values are the SQL they are converted to
6194
-     */
6195
-    public function valid_like_style_operators()
6196
-    {
6197
-        return array_intersect(
6198
-            $this->valid_operators(),
6199
-            $this->_like_style_operators
6200
-        );
6201
-    }
6202
-
6203
-
6204
-    /**
6205
-     * Gets the "in"-style operators
6206
-     *
6207
-     * @return array keys are accepted strings, values are the SQL they are converted to
6208
-     */
6209
-    public function valid_in_style_operators()
6210
-    {
6211
-        return array_intersect(
6212
-            $this->valid_operators(),
6213
-            $this->_in_style_operators
6214
-        );
6215
-    }
6216
-
6217
-
6218
-    /**
6219
-     * Gets the "null"-style operators (accept no arguments)
6220
-     *
6221
-     * @return array keys are accepted strings, values are the SQL they are converted to
6222
-     */
6223
-    public function valid_null_style_operators()
6224
-    {
6225
-        return array_intersect(
6226
-            $this->valid_operators(),
6227
-            $this->_null_style_operators
6228
-        );
6229
-    }
6230
-
6231
-
6232
-    /**
6233
-     * Gets an array where keys are the primary keys and values are their 'names'
6234
-     * (as determined by the model object's name() function, which is often overridden)
6235
-     *
6236
-     * @param array $query_params like get_all's
6237
-     * @return string[]
6238
-     * @throws EE_Error
6239
-     * @throws ReflectionException
6240
-     */
6241
-    public function get_all_names($query_params = [])
6242
-    {
6243
-        $objs  = $this->get_all($query_params);
6244
-        $names = [];
6245
-        foreach ($objs as $obj) {
6246
-            $names[ $obj->ID() ] = $obj->name();
6247
-        }
6248
-        return $names;
6249
-    }
6250
-
6251
-
6252
-    /**
6253
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6254
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6255
-     * this is duplicated effort and reduces efficiency) you would be better to use
6256
-     * array_keys() on $model_objects.
6257
-     *
6258
-     * @param \EE_Base_Class[] $model_objects
6259
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6260
-     *                                               in the returned array
6261
-     * @return array
6262
-     * @throws EE_Error
6263
-     * @throws ReflectionException
6264
-     */
6265
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6266
-    {
6267
-        if (! $this->has_primary_key_field()) {
6268
-            if (WP_DEBUG) {
6269
-                EE_Error::add_error(
6270
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6271
-                    __FILE__,
6272
-                    __FUNCTION__,
6273
-                    __LINE__
6274
-                );
6275
-            }
6276
-        }
6277
-        $IDs = [];
6278
-        foreach ($model_objects as $model_object) {
6279
-            $id = $model_object->ID();
6280
-            if (! $id) {
6281
-                if ($filter_out_empty_ids) {
6282
-                    continue;
6283
-                }
6284
-                if (WP_DEBUG) {
6285
-                    EE_Error::add_error(
6286
-                        esc_html__(
6287
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6288
-                            'event_espresso'
6289
-                        ),
6290
-                        __FILE__,
6291
-                        __FUNCTION__,
6292
-                        __LINE__
6293
-                    );
6294
-                }
6295
-            }
6296
-            $IDs[] = $id;
6297
-        }
6298
-        return $IDs;
6299
-    }
6300
-
6301
-
6302
-    /**
6303
-     * Returns the string used in capabilities relating to this model. If there
6304
-     * are no capabilities that relate to this model returns false
6305
-     *
6306
-     * @return string|false
6307
-     */
6308
-    public function cap_slug()
6309
-    {
6310
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6311
-    }
6312
-
6313
-
6314
-    /**
6315
-     * Returns the capability-restrictions array (@param string $context
6316
-     *
6317
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6318
-     * @throws EE_Error
6319
-     * @see EEM_Base::_cap_restrictions).
6320
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6321
-     *      only returns the cap restrictions array in that context (ie, the array
6322
-     *      at that key)
6323
-     */
6324
-    public function cap_restrictions($context = EEM_Base::caps_read)
6325
-    {
6326
-        EEM_Base::verify_is_valid_cap_context($context);
6327
-        // check if we ought to run the restriction generator first
6328
-        if (
6329
-            isset($this->_cap_restriction_generators[ $context ])
6330
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6331
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6332
-        ) {
6333
-            $this->_cap_restrictions[ $context ] = array_merge(
6334
-                $this->_cap_restrictions[ $context ],
6335
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6336
-            );
6337
-        }
6338
-        // and make sure we've finalized the construction of each restriction
6339
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6340
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6341
-                $where_conditions_obj->_finalize_construct($this);
6342
-            }
6343
-        }
6344
-        return $this->_cap_restrictions[ $context ];
6345
-    }
6346
-
6347
-
6348
-    /**
6349
-     * Indicating whether or not this model thinks its a wp core model
6350
-     *
6351
-     * @return boolean
6352
-     */
6353
-    public function is_wp_core_model()
6354
-    {
6355
-        return $this->_wp_core_model;
6356
-    }
6357
-
6358
-
6359
-    /**
6360
-     * Gets all the caps that are missing which impose a restriction on
6361
-     * queries made in this context
6362
-     *
6363
-     * @param string $context one of EEM_Base::caps_ constants
6364
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6365
-     * @throws EE_Error
6366
-     */
6367
-    public function caps_missing($context = EEM_Base::caps_read)
6368
-    {
6369
-        $missing_caps     = [];
6370
-        $cap_restrictions = $this->cap_restrictions($context);
6371
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6372
-            if (
6373
-                ! EE_Capabilities::instance()
6374
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6375
-            ) {
6376
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6377
-            }
6378
-        }
6379
-        return $missing_caps;
6380
-    }
6381
-
6382
-
6383
-    /**
6384
-     * Gets the mapping from capability contexts to action strings used in capability names
6385
-     *
6386
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6387
-     * one of 'read', 'edit', or 'delete'
6388
-     */
6389
-    public function cap_contexts_to_cap_action_map()
6390
-    {
6391
-        return apply_filters(
6392
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6393
-            $this->_cap_contexts_to_cap_action_map,
6394
-            $this
6395
-        );
6396
-    }
6397
-
6398
-
6399
-    /**
6400
-     * Gets the action string for the specified capability context
6401
-     *
6402
-     * @param string $context
6403
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6404
-     * @throws EE_Error
6405
-     */
6406
-    public function cap_action_for_context($context)
6407
-    {
6408
-        $mapping = $this->cap_contexts_to_cap_action_map();
6409
-        if (isset($mapping[ $context ])) {
6410
-            return $mapping[ $context ];
6411
-        }
6412
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6413
-            return $action;
6414
-        }
6415
-        throw new EE_Error(
6416
-            sprintf(
6417
-                esc_html__(
6418
-                    'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6419
-                    'event_espresso'
6420
-                ),
6421
-                $context,
6422
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6423
-            )
6424
-        );
6425
-    }
6426
-
6427
-
6428
-    /**
6429
-     * Returns all the capability contexts which are valid when querying models
6430
-     *
6431
-     * @return array
6432
-     */
6433
-    public static function valid_cap_contexts(): array
6434
-    {
6435
-        return (array) apply_filters(
6436
-            'FHEE__EEM_Base__valid_cap_contexts',
6437
-            [
6438
-                self::caps_read,
6439
-                self::caps_read_admin,
6440
-                self::caps_edit,
6441
-                self::caps_delete,
6442
-            ]
6443
-        );
6444
-    }
6445
-
6446
-
6447
-    /**
6448
-     * Returns all valid options for 'default_where_conditions'
6449
-     *
6450
-     * @return array
6451
-     */
6452
-    public static function valid_default_where_conditions(): array
6453
-    {
6454
-        return [
6455
-            EEM_Base::default_where_conditions_all,
6456
-            EEM_Base::default_where_conditions_this_only,
6457
-            EEM_Base::default_where_conditions_others_only,
6458
-            EEM_Base::default_where_conditions_minimum_all,
6459
-            EEM_Base::default_where_conditions_minimum_others,
6460
-            EEM_Base::default_where_conditions_none,
6461
-        ];
6462
-    }
6463
-
6464
-    // public static function default_where_conditions_full
6465
-
6466
-
6467
-    /**
6468
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6469
-     *
6470
-     * @param string $context
6471
-     * @return bool
6472
-     * @throws EE_Error
6473
-     */
6474
-    public static function verify_is_valid_cap_context($context): bool
6475
-    {
6476
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6477
-        if (in_array($context, $valid_cap_contexts)) {
6478
-            return true;
6479
-        }
6480
-        throw new EE_Error(
6481
-            sprintf(
6482
-                esc_html__(
6483
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6484
-                    'event_espresso'
6485
-                ),
6486
-                $context,
6487
-                'EEM_Base',
6488
-                implode(',', $valid_cap_contexts)
6489
-            )
6490
-        );
6491
-    }
6492
-
6493
-
6494
-    /**
6495
-     * Clears all the models field caches. This is only useful when a sub-class
6496
-     * might have added a field or something and these caches might be invalidated
6497
-     */
6498
-    protected function _invalidate_field_caches()
6499
-    {
6500
-        $this->_cache_foreign_key_to_fields = [];
6501
-        $this->_cached_fields               = null;
6502
-        $this->_cached_fields_non_db_only   = null;
6503
-    }
6504
-
6505
-
6506
-    /**
6507
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6508
-     * (eg "and", "or", "not").
6509
-     *
6510
-     * @return array
6511
-     */
6512
-    public function logic_query_param_keys(): array
6513
-    {
6514
-        return $this->_logic_query_param_keys;
6515
-    }
6516
-
6517
-
6518
-    /**
6519
-     * Determines whether or not the where query param array key is for a logic query param.
6520
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6521
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6522
-     *
6523
-     * @param $query_param_key
6524
-     * @return bool
6525
-     */
6526
-    public function is_logic_query_param_key($query_param_key): bool
6527
-    {
6528
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6529
-            if (
6530
-                $query_param_key === $logic_query_param_key
6531
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6532
-            ) {
6533
-                return true;
6534
-            }
6535
-        }
6536
-        return false;
6537
-    }
6538
-
6539
-
6540
-    /**
6541
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6542
-     *
6543
-     * @return boolean
6544
-     * @since 4.9.74.p
6545
-     */
6546
-    public function hasPassword(): bool
6547
-    {
6548
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6549
-        if ($this->has_password_field === null) {
6550
-            $password_field           = $this->getPasswordField();
6551
-            $this->has_password_field = $password_field instanceof EE_Password_Field;
6552
-        }
6553
-        return $this->has_password_field;
6554
-    }
6555
-
6556
-
6557
-    /**
6558
-     * Returns the password field on this model, if there is one
6559
-     *
6560
-     * @return EE_Password_Field|null
6561
-     * @since 4.9.74.p
6562
-     */
6563
-    public function getPasswordField()
6564
-    {
6565
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6566
-        // there's no need to search for it. If we don't know yet, then find out
6567
-        if ($this->has_password_field === null && $this->password_field === null) {
6568
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6569
-        }
6570
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6571
-        return $this->password_field;
6572
-    }
6573
-
6574
-
6575
-    /**
6576
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6577
-     *
6578
-     * @return EE_Model_Field_Base[]
6579
-     * @throws EE_Error
6580
-     * @since 4.9.74.p
6581
-     */
6582
-    public function getPasswordProtectedFields()
6583
-    {
6584
-        $password_field = $this->getPasswordField();
6585
-        $fields         = [];
6586
-        if ($password_field instanceof EE_Password_Field) {
6587
-            $field_names = $password_field->protectedFields();
6588
-            foreach ($field_names as $field_name) {
6589
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6590
-            }
6591
-        }
6592
-        return $fields;
6593
-    }
6594
-
6595
-
6596
-    /**
6597
-     * Checks if the current user can perform the requested action on this model
6598
-     *
6599
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6600
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6601
-     * @return bool
6602
-     * @throws EE_Error
6603
-     * @throws InvalidArgumentException
6604
-     * @throws InvalidDataTypeException
6605
-     * @throws InvalidInterfaceException
6606
-     * @throws ReflectionException
6607
-     * @throws UnexpectedEntityException
6608
-     * @since 4.9.74.p
6609
-     */
6610
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6611
-    {
6612
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6613
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6614
-        }
6615
-        if (! is_array($model_obj_or_fields_n_values)) {
6616
-            throw new UnexpectedEntityException(
6617
-                $model_obj_or_fields_n_values,
6618
-                'EE_Base_Class',
6619
-                sprintf(
6620
-                    esc_html__(
6621
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6622
-                        'event_espresso'
6623
-                    ),
6624
-                    __FUNCTION__
6625
-                )
6626
-            );
6627
-        }
6628
-        return $this->exists(
6629
-            $this->alter_query_params_to_restrict_by_ID(
6630
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6631
-                [
6632
-                    'default_where_conditions' => 'none',
6633
-                    'caps'                     => $cap_to_check,
6634
-                ]
6635
-            )
6636
-        );
6637
-    }
6638
-
6639
-
6640
-    /**
6641
-     * Returns the query param where conditions key to the password affecting this model.
6642
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6643
-     *
6644
-     * @return null|string
6645
-     * @throws EE_Error
6646
-     * @throws InvalidArgumentException
6647
-     * @throws InvalidDataTypeException
6648
-     * @throws InvalidInterfaceException
6649
-     * @throws ModelConfigurationException
6650
-     * @throws ReflectionException
6651
-     * @since 4.9.74.p
6652
-     */
6653
-    public function modelChainAndPassword()
6654
-    {
6655
-        if ($this->model_chain_to_password === null) {
6656
-            throw new ModelConfigurationException(
6657
-                $this,
6658
-                esc_html_x(
6659
-                // @codingStandardsIgnoreStart
6660
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6661
-                    // @codingStandardsIgnoreEnd
6662
-                    '1: model name',
6663
-                    'event_espresso'
6664
-                )
6665
-            );
6666
-        }
6667
-        if ($this->model_chain_to_password === '') {
6668
-            $model_with_password = $this;
6669
-        } else {
6670
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6671
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6672
-            } else {
6673
-                $last_model_in_chain = $this->model_chain_to_password;
6674
-            }
6675
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6676
-        }
6677
-
6678
-        $password_field = $model_with_password->getPasswordField();
6679
-        if ($password_field instanceof EE_Password_Field) {
6680
-            $password_field_name = $password_field->get_name();
6681
-        } else {
6682
-            throw new ModelConfigurationException(
6683
-                $this,
6684
-                sprintf(
6685
-                    esc_html_x(
6686
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6687
-                        '1: model name, 2: special string',
6688
-                        'event_espresso'
6689
-                    ),
6690
-                    $model_with_password->get_this_model_name(),
6691
-                    $this->model_chain_to_password
6692
-                )
6693
-            );
6694
-        }
6695
-        return (
6696
-               $this->model_chain_to_password
6697
-                   ? $this->model_chain_to_password . '.'
6698
-                   : ''
6699
-               ) . $password_field_name;
6700
-    }
6701
-
6702
-
6703
-    /**
6704
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6705
-     * or if this model itself has a password affecting access to some of its other fields.
6706
-     *
6707
-     * @return boolean
6708
-     * @since 4.9.74.p
6709
-     */
6710
-    public function restrictedByRelatedModelPassword(): bool
6711
-    {
6712
-        return $this->model_chain_to_password !== null;
6713
-    }
3951
+		}
3952
+		return $null_friendly_where_conditions;
3953
+	}
3954
+
3955
+
3956
+	/**
3957
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3958
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3959
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3960
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3961
+	 *
3962
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3963
+	 * @return array @see
3964
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3965
+	 * @throws EE_Error
3966
+	 * @throws EE_Error
3967
+	 */
3968
+	private function _get_default_where_conditions($model_relation_path = '')
3969
+	{
3970
+		if ($this->_ignore_where_strategy) {
3971
+			return [];
3972
+		}
3973
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3974
+	}
3975
+
3976
+
3977
+	/**
3978
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3979
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3980
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3981
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3982
+	 * Similar to _get_default_where_conditions
3983
+	 *
3984
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3985
+	 * @return array @see
3986
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3987
+	 * @throws EE_Error
3988
+	 * @throws EE_Error
3989
+	 */
3990
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3991
+	{
3992
+		if ($this->_ignore_where_strategy) {
3993
+			return [];
3994
+		}
3995
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3996
+	}
3997
+
3998
+
3999
+	/**
4000
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
4001
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
4002
+	 *
4003
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
4004
+	 * @return string
4005
+	 * @throws EE_Error
4006
+	 */
4007
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
4008
+	{
4009
+		$selects = $this->_get_columns_to_select_for_this_model();
4010
+		foreach (
4011
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
4012
+		) {
4013
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
4014
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
4015
+			foreach ($other_model_selects as $key => $value) {
4016
+				$selects[] = $value;
4017
+			}
4018
+		}
4019
+		return implode(", ", $selects);
4020
+	}
4021
+
4022
+
4023
+	/**
4024
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
4025
+	 * So that's going to be the columns for all the fields on the model
4026
+	 *
4027
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
4028
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
4029
+	 */
4030
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
4031
+	{
4032
+		$fields                                       = $this->field_settings();
4033
+		$selects                                      = [];
4034
+		$table_alias_with_model_relation_chain_prefix =
4035
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
4036
+				$model_relation_chain,
4037
+				$this->get_this_model_name()
4038
+			);
4039
+		foreach ($fields as $field_obj) {
4040
+			$selects[] = $table_alias_with_model_relation_chain_prefix
4041
+						 . $field_obj->get_table_alias()
4042
+						 . "."
4043
+						 . $field_obj->get_table_column()
4044
+						 . " AS '"
4045
+						 . $table_alias_with_model_relation_chain_prefix
4046
+						 . $field_obj->get_table_alias()
4047
+						 . "."
4048
+						 . $field_obj->get_table_column()
4049
+						 . "'";
4050
+		}
4051
+		// make sure we are also getting the PKs of each table
4052
+		$tables = $this->get_tables();
4053
+		if (count($tables) > 1) {
4054
+			foreach ($tables as $table_obj) {
4055
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4056
+									   . $table_obj->get_fully_qualified_pk_column();
4057
+				if (! in_array($qualified_pk_column, $selects)) {
4058
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4059
+				}
4060
+			}
4061
+		}
4062
+		return $selects;
4063
+	}
4064
+
4065
+
4066
+	/**
4067
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4068
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4069
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4070
+	 * SQL for joining, and the data types
4071
+	 *
4072
+	 * @param null|string                 $original_query_param
4073
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
4074
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4075
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4076
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4077
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
4078
+	 *                                                          or 'Registration's
4079
+	 * @param string                      $original_query_param what it originally was (eg
4080
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4081
+	 *                                                          matches $query_param
4082
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4083
+	 * @throws EE_Error
4084
+	 */
4085
+	private function _extract_related_model_info_from_query_param(
4086
+		$query_param,
4087
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4088
+		$query_param_type,
4089
+		$original_query_param = null
4090
+	) {
4091
+		if ($original_query_param === null) {
4092
+			$original_query_param = $query_param;
4093
+		}
4094
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4095
+		// check to see if we have a field on this model
4096
+		$this_model_fields = $this->field_settings(true);
4097
+		if (array_key_exists($query_param, $this_model_fields)) {
4098
+			$field_is_allowed = in_array(
4099
+				$query_param_type,
4100
+				[0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4101
+				true
4102
+			);
4103
+			if ($field_is_allowed) {
4104
+				return;
4105
+			}
4106
+			throw new EE_Error(
4107
+				sprintf(
4108
+					esc_html__(
4109
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4110
+						"event_espresso"
4111
+					),
4112
+					$query_param,
4113
+					get_class($this),
4114
+					$query_param_type,
4115
+					$original_query_param
4116
+				)
4117
+			);
4118
+		}
4119
+		// check if this is a special logic query param
4120
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4121
+			$operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4122
+			if ($operator_is_allowed) {
4123
+				return;
4124
+			}
4125
+			throw new EE_Error(
4126
+				sprintf(
4127
+					esc_html__(
4128
+						'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',
4129
+						'event_espresso'
4130
+					),
4131
+					implode('", "', $this->_logic_query_param_keys),
4132
+					$query_param,
4133
+					get_class($this),
4134
+					'<br />',
4135
+					"\t"
4136
+					. ' $passed_in_query_info = <pre>'
4137
+					. print_r($passed_in_query_info, true)
4138
+					. '</pre>'
4139
+					. "\n\t"
4140
+					. ' $query_param_type = '
4141
+					. $query_param_type
4142
+					. "\n\t"
4143
+					. ' $original_query_param = '
4144
+					. $original_query_param
4145
+				)
4146
+			);
4147
+		}
4148
+		// check if it's a custom selection
4149
+		if (
4150
+			$this->_custom_selections instanceof CustomSelects
4151
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4152
+		) {
4153
+			return;
4154
+		}
4155
+		// check if has a model name at the beginning
4156
+		// and
4157
+		// check if it's a field on a related model
4158
+		if (
4159
+			$this->extractJoinModelFromQueryParams(
4160
+				$passed_in_query_info,
4161
+				$query_param,
4162
+				$original_query_param,
4163
+				$query_param_type
4164
+			)
4165
+		) {
4166
+			return;
4167
+		}
4168
+
4169
+		// ok so $query_param didn't start with a model name
4170
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4171
+		// it's wack, that's what it is
4172
+		throw new EE_Error(
4173
+			sprintf(
4174
+				esc_html__(
4175
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4176
+					"event_espresso"
4177
+				),
4178
+				$query_param,
4179
+				get_class($this),
4180
+				$query_param_type,
4181
+				$original_query_param
4182
+			)
4183
+		);
4184
+	}
4185
+
4186
+
4187
+	/**
4188
+	 * Extracts any possible join model information from the provided possible_join_string.
4189
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4190
+	 * join
4191
+	 * parts that should be added to the query.
4192
+	 *
4193
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4194
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4195
+	 * @param null|string                 $original_query_param
4196
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4197
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4198
+	 *                                                           etc.)
4199
+	 * @return bool  returns true if a join was added and false if not.
4200
+	 * @throws EE_Error
4201
+	 */
4202
+	private function extractJoinModelFromQueryParams(
4203
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4204
+		$possible_join_string,
4205
+		$original_query_param,
4206
+		$query_parameter_type
4207
+	) {
4208
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4209
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4210
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4211
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4212
+				if ($possible_join_string === '') {
4213
+					// nothing left to $query_param
4214
+					// we should actually end in a field name, not a model like this!
4215
+					throw new EE_Error(
4216
+						sprintf(
4217
+							esc_html__(
4218
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4219
+								"event_espresso"
4220
+							),
4221
+							$possible_join_string,
4222
+							$query_parameter_type,
4223
+							get_class($this),
4224
+							$valid_related_model_name
4225
+						)
4226
+					);
4227
+				}
4228
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4229
+				$related_model_obj->_extract_related_model_info_from_query_param(
4230
+					$possible_join_string,
4231
+					$query_info_carrier,
4232
+					$query_parameter_type,
4233
+					$original_query_param
4234
+				);
4235
+				return true;
4236
+			}
4237
+			if ($possible_join_string === $valid_related_model_name) {
4238
+				$this->_add_join_to_model(
4239
+					$valid_related_model_name,
4240
+					$query_info_carrier,
4241
+					$original_query_param
4242
+				);
4243
+				return true;
4244
+			}
4245
+		}
4246
+		return false;
4247
+	}
4248
+
4249
+
4250
+	/**
4251
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4252
+	 *
4253
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4254
+	 * @throws EE_Error
4255
+	 */
4256
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4257
+	{
4258
+		if (
4259
+			$this->_custom_selections instanceof CustomSelects
4260
+			&& (
4261
+				$this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4262
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4263
+			)
4264
+		) {
4265
+			$original_selects = $this->_custom_selections->originalSelects();
4266
+			foreach ($original_selects as $alias => $select_configuration) {
4267
+				$this->extractJoinModelFromQueryParams(
4268
+					$query_info_carrier,
4269
+					$select_configuration[0],
4270
+					$select_configuration[0],
4271
+					'custom_selects'
4272
+				);
4273
+			}
4274
+		}
4275
+	}
4276
+
4277
+
4278
+	/**
4279
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4280
+	 * and store it on $passed_in_query_info
4281
+	 *
4282
+	 * @param string                      $model_name
4283
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4284
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4285
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4286
+	 *                                                          and are adding a join to 'Payment' with the original
4287
+	 *                                                          query param key
4288
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4289
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4290
+	 *                                                          Payment wants to add default query params so that it
4291
+	 *                                                          will know what models to prepend onto its default query
4292
+	 *                                                          params or in case it wants to rename tables (in case
4293
+	 *                                                          there are multiple joins to the same table)
4294
+	 * @return void
4295
+	 * @throws EE_Error
4296
+	 */
4297
+	private function _add_join_to_model(
4298
+		$model_name,
4299
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4300
+		$original_query_param
4301
+	) {
4302
+		$relation_obj         = $this->related_settings_for($model_name);
4303
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4304
+		// check if the relation is HABTM, because then we're essentially doing two joins
4305
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4306
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4307
+			$join_model_obj = $relation_obj->get_join_model();
4308
+			// replace the model specified with the join model for this relation chain, whi
4309
+			$relation_chain_to_join_model =
4310
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4311
+					$model_name,
4312
+					$join_model_obj->get_this_model_name(),
4313
+					$model_relation_chain
4314
+				);
4315
+			$passed_in_query_info->merge(
4316
+				new EE_Model_Query_Info_Carrier(
4317
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4318
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4319
+				)
4320
+			);
4321
+		}
4322
+		// now just join to the other table pointed to by the relation object, and add its data types
4323
+		$passed_in_query_info->merge(
4324
+			new EE_Model_Query_Info_Carrier(
4325
+				[$model_relation_chain => $model_name],
4326
+				$relation_obj->get_join_statement($model_relation_chain)
4327
+			)
4328
+		);
4329
+	}
4330
+
4331
+
4332
+	/**
4333
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4334
+	 *
4335
+	 * @param array $where_params @see
4336
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4337
+	 * @return string of SQL
4338
+	 * @throws EE_Error
4339
+	 */
4340
+	private function _construct_where_clause($where_params)
4341
+	{
4342
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4343
+		if ($SQL) {
4344
+			return " WHERE " . $SQL;
4345
+		}
4346
+		return '';
4347
+	}
4348
+
4349
+
4350
+	/**
4351
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4352
+	 * and should be passed HAVING parameters, not WHERE parameters
4353
+	 *
4354
+	 * @param array $having_params
4355
+	 * @return string
4356
+	 * @throws EE_Error
4357
+	 */
4358
+	private function _construct_having_clause($having_params)
4359
+	{
4360
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4361
+		if ($SQL) {
4362
+			return " HAVING " . $SQL;
4363
+		}
4364
+		return '';
4365
+	}
4366
+
4367
+
4368
+	/**
4369
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4370
+	 * Event_Meta.meta_value = 'foo'))"
4371
+	 *
4372
+	 * @param array  $where_params @see
4373
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4374
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4375
+	 * @return string of SQL
4376
+	 * @throws EE_Error
4377
+	 */
4378
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4379
+	{
4380
+		$where_clauses = [];
4381
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4382
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4383
+			if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4384
+				switch ($query_param) {
4385
+					case 'not':
4386
+					case 'NOT':
4387
+						$where_clauses[] = "! ("
4388
+										   . $this->_construct_condition_clause_recursive(
4389
+								$op_and_value_or_sub_condition,
4390
+								$glue
4391
+							)
4392
+										   . ")";
4393
+						break;
4394
+					case 'and':
4395
+					case 'AND':
4396
+						$where_clauses[] = " ("
4397
+										   . $this->_construct_condition_clause_recursive(
4398
+								$op_and_value_or_sub_condition,
4399
+								' AND '
4400
+							)
4401
+										   . ")";
4402
+						break;
4403
+					case 'or':
4404
+					case 'OR':
4405
+						$where_clauses[] = " ("
4406
+										   . $this->_construct_condition_clause_recursive(
4407
+								$op_and_value_or_sub_condition,
4408
+								' OR '
4409
+							)
4410
+										   . ")";
4411
+						break;
4412
+				}
4413
+			} else {
4414
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4415
+				// if it's not a normal field, maybe it's a custom selection?
4416
+				if (! $field_obj) {
4417
+					if ($this->_custom_selections instanceof CustomSelects) {
4418
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4419
+					} else {
4420
+						throw new EE_Error(
4421
+							sprintf(
4422
+								esc_html__(
4423
+									"%s is neither a valid model field name, nor a custom selection",
4424
+									"event_espresso"
4425
+								),
4426
+								$query_param
4427
+							)
4428
+						);
4429
+					}
4430
+				}
4431
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4432
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4433
+			}
4434
+		}
4435
+		return $where_clauses
4436
+			? implode($glue, $where_clauses)
4437
+			: '';
4438
+	}
4439
+
4440
+
4441
+	/**
4442
+	 * Takes the input parameter and extract the table name (alias) and column name
4443
+	 *
4444
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4445
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4446
+	 * @throws EE_Error
4447
+	 */
4448
+	private function _deduce_column_name_from_query_param($query_param)
4449
+	{
4450
+		$field = $this->_deduce_field_from_query_param($query_param);
4451
+		if ($field) {
4452
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4453
+				$field->get_model_name(),
4454
+				$query_param
4455
+			);
4456
+			return $table_alias_prefix . $field->get_qualified_column();
4457
+		}
4458
+		if (
4459
+			$this->_custom_selections instanceof CustomSelects
4460
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4461
+		) {
4462
+			// maybe it's custom selection item?
4463
+			// if so, just use it as the "column name"
4464
+			return $query_param;
4465
+		}
4466
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4467
+			? implode(',', $this->_custom_selections->columnAliases())
4468
+			: '';
4469
+		throw new EE_Error(
4470
+			sprintf(
4471
+				esc_html__(
4472
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4473
+					"event_espresso"
4474
+				),
4475
+				$query_param,
4476
+				$custom_select_aliases
4477
+			)
4478
+		);
4479
+	}
4480
+
4481
+
4482
+	/**
4483
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4484
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4485
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4486
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4487
+	 *
4488
+	 * @param string $condition_query_param_key
4489
+	 * @return string
4490
+	 */
4491
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4492
+	{
4493
+		$pos_of_star = strpos($condition_query_param_key, '*');
4494
+		if ($pos_of_star === false) {
4495
+			return $condition_query_param_key;
4496
+		}
4497
+		return substr($condition_query_param_key, 0, $pos_of_star);
4498
+	}
4499
+
4500
+
4501
+	/**
4502
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4503
+	 *
4504
+	 * @param array|string               $op_and_value
4505
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4506
+	 * @return string
4507
+	 * @throws EE_Error
4508
+	 */
4509
+	private function _construct_op_and_value($op_and_value, $field_obj)
4510
+	{
4511
+		$operator = '=';
4512
+		$value    = $op_and_value;
4513
+		if (is_array($op_and_value)) {
4514
+			$operator = isset($op_and_value[0])
4515
+				? $this->_prepare_operator_for_sql($op_and_value[0])
4516
+				: null;
4517
+			if (! $operator) {
4518
+				$php_array_like_string = [];
4519
+				foreach ($op_and_value as $key => $value) {
4520
+					$php_array_like_string[] = "$key=>$value";
4521
+				}
4522
+				throw new EE_Error(
4523
+					sprintf(
4524
+						esc_html__(
4525
+							"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))",
4526
+							"event_espresso"
4527
+						),
4528
+						implode(",", $php_array_like_string)
4529
+					)
4530
+				);
4531
+			}
4532
+			$value = $op_and_value[1] ?? null;
4533
+		}
4534
+
4535
+		// check to see if the value is actually another field
4536
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4537
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4538
+		}
4539
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4540
+			// in this case, the value should be an array, or at least a comma-separated list
4541
+			// it will need to handle a little differently
4542
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4543
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4544
+			return $operator . SP . $cleaned_value;
4545
+		}
4546
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4547
+			// the value should be an array with count of two.
4548
+			if (count($value) !== 2) {
4549
+				throw new EE_Error(
4550
+					sprintf(
4551
+						esc_html__(
4552
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4553
+							'event_espresso'
4554
+						),
4555
+						"BETWEEN"
4556
+					)
4557
+				);
4558
+			}
4559
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4560
+			return $operator . SP . $cleaned_value;
4561
+		}
4562
+		if (in_array($operator, $this->valid_null_style_operators())) {
4563
+			if ($value !== null) {
4564
+				throw new EE_Error(
4565
+					sprintf(
4566
+						esc_html__(
4567
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4568
+							"event_espresso"
4569
+						),
4570
+						$value,
4571
+						$operator
4572
+					)
4573
+				);
4574
+			}
4575
+			return $operator;
4576
+		}
4577
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4578
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4579
+			// remove other junk. So just treat it as a string.
4580
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4581
+		}
4582
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4583
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4584
+		}
4585
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4586
+			throw new EE_Error(
4587
+				sprintf(
4588
+					esc_html__(
4589
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4590
+						'event_espresso'
4591
+					),
4592
+					$operator,
4593
+					$operator
4594
+				)
4595
+			);
4596
+		}
4597
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4598
+			throw new EE_Error(
4599
+				sprintf(
4600
+					esc_html__(
4601
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4602
+						'event_espresso'
4603
+					),
4604
+					$operator,
4605
+					$operator
4606
+				)
4607
+			);
4608
+		}
4609
+		throw new EE_Error(
4610
+			sprintf(
4611
+				esc_html__(
4612
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4613
+					"event_espresso"
4614
+				),
4615
+				http_build_query($op_and_value)
4616
+			)
4617
+		);
4618
+	}
4619
+
4620
+
4621
+	/**
4622
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4623
+	 *
4624
+	 * @param array                      $values
4625
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4626
+	 *                                              '%s'
4627
+	 * @return string
4628
+	 * @throws EE_Error
4629
+	 */
4630
+	public function _construct_between_value($values, $field_obj)
4631
+	{
4632
+		$cleaned_values = [];
4633
+		foreach ($values as $value) {
4634
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4635
+		}
4636
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4637
+	}
4638
+
4639
+
4640
+	/**
4641
+	 * Takes an array or a comma-separated list of $values and cleans them
4642
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4643
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4644
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4645
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4646
+	 *
4647
+	 * @param mixed                      $values    array or comma-separated string
4648
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4649
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4650
+	 * @throws EE_Error
4651
+	 */
4652
+	public function _construct_in_value($values, $field_obj)
4653
+	{
4654
+		$prepped = [];
4655
+		// check if the value is a CSV list
4656
+		if (is_string($values)) {
4657
+			// in which case, turn it into an array
4658
+			$values = explode(',', $values);
4659
+		}
4660
+		// make sure we only have one of each value in the list
4661
+		$values = array_unique($values);
4662
+		foreach ($values as $value) {
4663
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4664
+		}
4665
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4666
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4667
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4668
+		if (empty($prepped)) {
4669
+			$all_fields  = $this->field_settings();
4670
+			$first_field = reset($all_fields);
4671
+			$main_table  = $this->_get_main_table();
4672
+			$prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4673
+		}
4674
+		return '(' . implode(',', $prepped) . ')';
4675
+	}
4676
+
4677
+
4678
+	/**
4679
+	 * @param mixed                      $value
4680
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4681
+	 * @return false|null|string
4682
+	 * @throws EE_Error
4683
+	 */
4684
+	private function _wpdb_prepare_using_field($value, $field_obj)
4685
+	{
4686
+		/** @type WPDB $wpdb */
4687
+		global $wpdb;
4688
+		if ($field_obj instanceof EE_Model_Field_Base) {
4689
+			return $wpdb->prepare(
4690
+				$field_obj->get_wpdb_data_type(),
4691
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4692
+			);
4693
+		} //$field_obj should really just be a data type
4694
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4695
+			throw new EE_Error(
4696
+				sprintf(
4697
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4698
+					$field_obj,
4699
+					implode(",", $this->_valid_wpdb_data_types)
4700
+				)
4701
+			);
4702
+		}
4703
+		return $wpdb->prepare($field_obj, $value);
4704
+	}
4705
+
4706
+
4707
+	/**
4708
+	 * Takes the input parameter and finds the model field that it indicates.
4709
+	 *
4710
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4711
+	 * @return EE_Model_Field_Base
4712
+	 * @throws EE_Error
4713
+	 */
4714
+	protected function _deduce_field_from_query_param($query_param_name)
4715
+	{
4716
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4717
+		// which will help us find the database table and column
4718
+		$query_param_parts = explode(".", $query_param_name);
4719
+		if (empty($query_param_parts)) {
4720
+			throw new EE_Error(
4721
+				sprintf(
4722
+					esc_html__(
4723
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4724
+						'event_espresso'
4725
+					),
4726
+					$query_param_name
4727
+				)
4728
+			);
4729
+		}
4730
+		$number_of_parts       = count($query_param_parts);
4731
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4732
+		if ($number_of_parts === 1) {
4733
+			$field_name = $last_query_param_part;
4734
+			$model_obj  = $this;
4735
+		} else {// $number_of_parts >= 2
4736
+			// the last part is the column name, and there are only 2parts. therefore...
4737
+			$field_name = $last_query_param_part;
4738
+			$model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4739
+		}
4740
+		try {
4741
+			return $model_obj->field_settings_for($field_name);
4742
+		} catch (EE_Error $e) {
4743
+			return null;
4744
+		}
4745
+	}
4746
+
4747
+
4748
+	/**
4749
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4750
+	 * alias and column which corresponds to it
4751
+	 *
4752
+	 * @param string $field_name
4753
+	 * @return string
4754
+	 * @throws EE_Error
4755
+	 */
4756
+	public function _get_qualified_column_for_field($field_name)
4757
+	{
4758
+		$all_fields = $this->field_settings();
4759
+		$field      = $all_fields[ $field_name ] ?? false;
4760
+		if ($field) {
4761
+			return $field->get_qualified_column();
4762
+		}
4763
+		throw new EE_Error(
4764
+			sprintf(
4765
+				esc_html__(
4766
+					"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.",
4767
+					'event_espresso'
4768
+				),
4769
+				$field_name,
4770
+				get_class($this)
4771
+			)
4772
+		);
4773
+	}
4774
+
4775
+
4776
+	/**
4777
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4778
+	 * Example usage:
4779
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4780
+	 *      array(),
4781
+	 *      ARRAY_A,
4782
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4783
+	 *  );
4784
+	 * is equivalent to
4785
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4786
+	 * and
4787
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4788
+	 *      array(
4789
+	 *          array(
4790
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4791
+	 *          ),
4792
+	 *          ARRAY_A,
4793
+	 *          implode(
4794
+	 *              ', ',
4795
+	 *              array_merge(
4796
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4797
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4798
+	 *              )
4799
+	 *          )
4800
+	 *      )
4801
+	 *  );
4802
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4803
+	 *
4804
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4805
+	 *                                            and the one whose fields you are selecting for example: when querying
4806
+	 *                                            tickets model and selecting fields from the tickets model you would
4807
+	 *                                            leave this parameter empty, because no models are needed to join
4808
+	 *                                            between the queried model and the selected one. Likewise when
4809
+	 *                                            querying the datetime model and selecting fields from the tickets
4810
+	 *                                            model, it would also be left empty, because there is a direct
4811
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4812
+	 *                                            them together. However, when querying from the event model and
4813
+	 *                                            selecting fields from the ticket model, you should provide the string
4814
+	 *                                            'Datetime', indicating that the event model must first join to the
4815
+	 *                                            datetime model in order to find its relation to ticket model.
4816
+	 *                                            Also, when querying from the venue model and selecting fields from
4817
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4818
+	 *                                            indicating you need to join the venue model to the event model,
4819
+	 *                                            to the datetime model, in order to find its relation to the ticket
4820
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4821
+	 *                                            the models' tables qualified columns
4822
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4823
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4824
+	 *                                            qualified column names
4825
+	 * @return array|string
4826
+	 */
4827
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4828
+	{
4829
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4830
+				? ''
4831
+				: '__');
4832
+		$qualified_columns = [];
4833
+		foreach ($this->field_settings() as $field_name => $field) {
4834
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4835
+		}
4836
+		return $return_string
4837
+			? implode(', ', $qualified_columns)
4838
+			: $qualified_columns;
4839
+	}
4840
+
4841
+
4842
+	/**
4843
+	 * constructs the select use on special limit joins
4844
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4845
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4846
+	 * (as that is typically where the limits would be set).
4847
+	 *
4848
+	 * @param string       $table_alias The table the select is being built for
4849
+	 * @param mixed|string $limit       The limit for this select
4850
+	 * @return string                The final select join element for the query.
4851
+	 * @throws EE_Error
4852
+	 * @throws EE_Error
4853
+	 */
4854
+	public function _construct_limit_join_select($table_alias, $limit)
4855
+	{
4856
+		$SQL = '';
4857
+		foreach ($this->_tables as $table_obj) {
4858
+			if ($table_obj instanceof EE_Primary_Table) {
4859
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4860
+					? $table_obj->get_select_join_limit($limit)
4861
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4862
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4863
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4864
+					? $table_obj->get_select_join_limit_join($limit)
4865
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4866
+			}
4867
+		}
4868
+		return $SQL;
4869
+	}
4870
+
4871
+
4872
+	/**
4873
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4874
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4875
+	 *
4876
+	 * @return string SQL
4877
+	 * @throws EE_Error
4878
+	 */
4879
+	public function _construct_internal_join()
4880
+	{
4881
+		$SQL = $this->_get_main_table()->get_table_sql();
4882
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4883
+		return $SQL;
4884
+	}
4885
+
4886
+
4887
+	/**
4888
+	 * Constructs the SQL for joining all the tables on this model.
4889
+	 * Normally $alias should be the primary table's alias, but in cases where
4890
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4891
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4892
+	 * alias, this will construct SQL like:
4893
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4894
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4895
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4896
+	 *
4897
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4898
+	 * @return string
4899
+	 * @throws EE_Error
4900
+	 * @throws EE_Error
4901
+	 */
4902
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4903
+	{
4904
+		$SQL               = '';
4905
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4906
+		foreach ($this->_tables as $table_obj) {
4907
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4908
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4909
+					// so we're joining to this table, meaning the table is already in
4910
+					// the FROM statement, BUT the primary table isn't. So we want
4911
+					// to add the inverse join sql
4912
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4913
+				} else {
4914
+					// just add a regular JOIN to this table from the primary table
4915
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4916
+				}
4917
+			}// if it's a primary table, dont add any SQL. it should already be in the FROM statement
4918
+		}
4919
+		return $SQL;
4920
+	}
4921
+
4922
+
4923
+	/**
4924
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4925
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4926
+	 * their data type (eg, '%s', '%d', etc)
4927
+	 *
4928
+	 * @return array
4929
+	 */
4930
+	public function _get_data_types()
4931
+	{
4932
+		$data_types = [];
4933
+		foreach ($this->field_settings() as $field_obj) {
4934
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4935
+			/** @var $field_obj EE_Model_Field_Base */
4936
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4937
+		}
4938
+		return $data_types;
4939
+	}
4940
+
4941
+
4942
+	/**
4943
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4944
+	 *
4945
+	 * @param string $model_name
4946
+	 * @return EEM_Base
4947
+	 * @throws EE_Error
4948
+	 */
4949
+	public function get_related_model_obj($model_name)
4950
+	{
4951
+		$model_classname = "EEM_" . $model_name;
4952
+		if (! class_exists($model_classname)) {
4953
+			throw new EE_Error(
4954
+				sprintf(
4955
+					esc_html__(
4956
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4957
+						'event_espresso'
4958
+					),
4959
+					$model_name,
4960
+					$model_classname
4961
+				)
4962
+			);
4963
+		}
4964
+		return call_user_func($model_classname . "::instance");
4965
+	}
4966
+
4967
+
4968
+	/**
4969
+	 * Returns the array of EE_ModelRelations for this model.
4970
+	 *
4971
+	 * @return EE_Model_Relation_Base[]
4972
+	 */
4973
+	public function relation_settings()
4974
+	{
4975
+		return $this->_model_relations;
4976
+	}
4977
+
4978
+
4979
+	/**
4980
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4981
+	 * because without THOSE models, this model probably doesn't have much purpose.
4982
+	 * (Eg, without an event, datetimes have little purpose.)
4983
+	 *
4984
+	 * @return EE_Belongs_To_Relation[]
4985
+	 */
4986
+	public function belongs_to_relations()
4987
+	{
4988
+		$belongs_to_relations = [];
4989
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4990
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4991
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4992
+			}
4993
+		}
4994
+		return $belongs_to_relations;
4995
+	}
4996
+
4997
+
4998
+	/**
4999
+	 * Returns the specified EE_Model_Relation, or throws an exception
5000
+	 *
5001
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
5002
+	 * @return EE_Model_Relation_Base
5003
+	 * @throws EE_Error
5004
+	 */
5005
+	public function related_settings_for($relation_name)
5006
+	{
5007
+		$relatedModels = $this->relation_settings();
5008
+		if (! array_key_exists($relation_name, $relatedModels)) {
5009
+			throw new EE_Error(
5010
+				sprintf(
5011
+					esc_html__(
5012
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
5013
+						'event_espresso'
5014
+					),
5015
+					$relation_name,
5016
+					$this->_get_class_name(),
5017
+					implode(', ', array_keys($relatedModels))
5018
+				)
5019
+			);
5020
+		}
5021
+		return $relatedModels[ $relation_name ];
5022
+	}
5023
+
5024
+
5025
+	/**
5026
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
5027
+	 * fields
5028
+	 *
5029
+	 * @param string  $fieldName
5030
+	 * @param boolean $include_db_only_fields
5031
+	 * @return EE_Model_Field_Base
5032
+	 * @throws EE_Error
5033
+	 */
5034
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
5035
+	{
5036
+		$fieldSettings = $this->field_settings($include_db_only_fields);
5037
+		if (! array_key_exists($fieldName, $fieldSettings)) {
5038
+			throw new EE_Error(
5039
+				sprintf(
5040
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
5041
+					$fieldName,
5042
+					get_class($this)
5043
+				)
5044
+			);
5045
+		}
5046
+		return $fieldSettings[ $fieldName ];
5047
+	}
5048
+
5049
+
5050
+	/**
5051
+	 * Checks if this field exists on this model
5052
+	 *
5053
+	 * @param string $fieldName a key in the model's _field_settings array
5054
+	 * @return boolean
5055
+	 */
5056
+	public function has_field($fieldName)
5057
+	{
5058
+		$fieldSettings = $this->field_settings(true);
5059
+		if (isset($fieldSettings[ $fieldName ])) {
5060
+			return true;
5061
+		}
5062
+		return false;
5063
+	}
5064
+
5065
+
5066
+	/**
5067
+	 * Returns whether or not this model has a relation to the specified model
5068
+	 *
5069
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
5070
+	 * @return boolean
5071
+	 */
5072
+	public function has_relation($relation_name)
5073
+	{
5074
+		$relations = $this->relation_settings();
5075
+		if (isset($relations[ $relation_name ])) {
5076
+			return true;
5077
+		}
5078
+		return false;
5079
+	}
5080
+
5081
+
5082
+	/**
5083
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5084
+	 * Eg, on EE_Answer that would be ANS_ID field object
5085
+	 *
5086
+	 * @param $field_obj
5087
+	 * @return boolean
5088
+	 */
5089
+	public function is_primary_key_field($field_obj): bool
5090
+	{
5091
+		return $field_obj instanceof EE_Primary_Key_Field_Base;
5092
+	}
5093
+
5094
+
5095
+	/**
5096
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5097
+	 * Eg, on EE_Answer that would be ANS_ID field object
5098
+	 *
5099
+	 * @return EE_Primary_Key_Field_Base
5100
+	 * @throws EE_Error
5101
+	 */
5102
+	public function get_primary_key_field()
5103
+	{
5104
+		if ($this->_primary_key_field === null) {
5105
+			foreach ($this->field_settings(true) as $field_obj) {
5106
+				if ($this->is_primary_key_field($field_obj)) {
5107
+					$this->_primary_key_field = $field_obj;
5108
+					break;
5109
+				}
5110
+			}
5111
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5112
+				throw new EE_Error(
5113
+					sprintf(
5114
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5115
+						get_class($this)
5116
+					)
5117
+				);
5118
+			}
5119
+		}
5120
+		return $this->_primary_key_field;
5121
+	}
5122
+
5123
+
5124
+	/**
5125
+	 * Returns whether or not not there is a primary key on this model.
5126
+	 * Internally does some caching.
5127
+	 *
5128
+	 * @return boolean
5129
+	 */
5130
+	public function has_primary_key_field()
5131
+	{
5132
+		if ($this->_has_primary_key_field === null) {
5133
+			try {
5134
+				$this->get_primary_key_field();
5135
+				$this->_has_primary_key_field = true;
5136
+			} catch (EE_Error $e) {
5137
+				$this->_has_primary_key_field = false;
5138
+			}
5139
+		}
5140
+		return $this->_has_primary_key_field;
5141
+	}
5142
+
5143
+
5144
+	/**
5145
+	 * Finds the first field of type $field_class_name.
5146
+	 *
5147
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5148
+	 *                                 EE_Foreign_Key_Field, etc
5149
+	 * @return EE_Model_Field_Base or null if none is found
5150
+	 */
5151
+	public function get_a_field_of_type($field_class_name)
5152
+	{
5153
+		foreach ($this->field_settings() as $field) {
5154
+			if ($field instanceof $field_class_name) {
5155
+				return $field;
5156
+			}
5157
+		}
5158
+		return null;
5159
+	}
5160
+
5161
+
5162
+	/**
5163
+	 * Gets a foreign key field pointing to model.
5164
+	 *
5165
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5166
+	 * @return EE_Foreign_Key_Field_Base
5167
+	 * @throws EE_Error
5168
+	 */
5169
+	public function get_foreign_key_to($model_name)
5170
+	{
5171
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5172
+			foreach ($this->field_settings() as $field) {
5173
+				if (
5174
+					$field instanceof EE_Foreign_Key_Field_Base
5175
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5176
+				) {
5177
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5178
+					break;
5179
+				}
5180
+			}
5181
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5182
+				throw new EE_Error(
5183
+					sprintf(
5184
+						esc_html__(
5185
+							"There is no foreign key field pointing to model %s on model %s",
5186
+							'event_espresso'
5187
+						),
5188
+						$model_name,
5189
+						get_class($this)
5190
+					)
5191
+				);
5192
+			}
5193
+		}
5194
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5195
+	}
5196
+
5197
+
5198
+	/**
5199
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5200
+	 *
5201
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5202
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5203
+	 *                            Either one works
5204
+	 * @return string
5205
+	 */
5206
+	public function get_table_for_alias($table_alias)
5207
+	{
5208
+		$table_alias_sans_model_relation_chain_prefix =
5209
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5210
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5211
+	}
5212
+
5213
+
5214
+	/**
5215
+	 * Returns a flat array of all field son this model, instead of organizing them
5216
+	 * by table_alias as they are in the constructor.
5217
+	 *
5218
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5219
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5220
+	 */
5221
+	public function field_settings($include_db_only_fields = false)
5222
+	{
5223
+		if ($include_db_only_fields) {
5224
+			if ($this->_cached_fields === null) {
5225
+				$this->_cached_fields = [];
5226
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5227
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5228
+						$this->_cached_fields[ $field_name ] = $field_obj;
5229
+					}
5230
+				}
5231
+			}
5232
+			return $this->_cached_fields;
5233
+		}
5234
+		if ($this->_cached_fields_non_db_only === null) {
5235
+			$this->_cached_fields_non_db_only = [];
5236
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5237
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5238
+					/** @var $field_obj EE_Model_Field_Base */
5239
+					if (! $field_obj->is_db_only_field()) {
5240
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5241
+					}
5242
+				}
5243
+			}
5244
+		}
5245
+		return $this->_cached_fields_non_db_only;
5246
+	}
5247
+
5248
+
5249
+	/**
5250
+	 *        cycle though array of attendees and create objects out of each item
5251
+	 *
5252
+	 * @access        private
5253
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5254
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5255
+	 *                           numerically indexed)
5256
+	 * @throws EE_Error
5257
+	 * @throws ReflectionException
5258
+	 */
5259
+	protected function _create_objects($rows = [])
5260
+	{
5261
+		$array_of_objects = [];
5262
+		if (empty($rows)) {
5263
+			return [];
5264
+		}
5265
+		$count_if_model_has_no_primary_key = 0;
5266
+		$has_primary_key                   = $this->has_primary_key_field();
5267
+		$primary_key_field                 = $has_primary_key
5268
+			? $this->get_primary_key_field()
5269
+			: null;
5270
+		foreach ((array) $rows as $row) {
5271
+			if (empty($row)) {
5272
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5273
+				return [];
5274
+			}
5275
+			// check if we've already set this object in the results array,
5276
+			// in which case there's no need to process it further (again)
5277
+			if ($has_primary_key) {
5278
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5279
+					$row,
5280
+					$primary_key_field->get_qualified_column(),
5281
+					$primary_key_field->get_table_column()
5282
+				);
5283
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5284
+					continue;
5285
+				}
5286
+			}
5287
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5288
+			if (! $classInstance) {
5289
+				throw new EE_Error(
5290
+					sprintf(
5291
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5292
+						$this->get_this_model_name(),
5293
+						http_build_query($row)
5294
+					)
5295
+				);
5296
+			}
5297
+			// set the timezone on the instantiated objects
5298
+			$classInstance->set_timezone($this->_timezone);
5299
+			// make sure if there is any timezone setting present that we set the timezone for the object
5300
+			$key                      = $has_primary_key
5301
+				? $classInstance->ID()
5302
+				: $count_if_model_has_no_primary_key++;
5303
+			$array_of_objects[ $key ] = $classInstance;
5304
+			// also, for all the relations of type BelongsTo, see if we can cache
5305
+			// those related models
5306
+			// (we could do this for other relations too, but if there are conditions
5307
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5308
+			// so it requires a little more thought than just caching them immediately...)
5309
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5310
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5311
+					// check if this model's INFO is present. If so, cache it on the model
5312
+					$other_model           = $relation_obj->get_other_model();
5313
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5314
+					// if we managed to make a model object from the results, cache it on the main model object
5315
+					if ($other_model_obj_maybe) {
5316
+						// set timezone on these other model objects if they are present
5317
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5318
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5319
+					}
5320
+				}
5321
+			}
5322
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5323
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5324
+			// the field in the CustomSelects object
5325
+			if ($this->_custom_selections instanceof CustomSelects) {
5326
+				$classInstance->setCustomSelectsValues(
5327
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5328
+				);
5329
+			}
5330
+		}
5331
+		return $array_of_objects;
5332
+	}
5333
+
5334
+
5335
+	/**
5336
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5337
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5338
+	 *
5339
+	 * @param array $db_results_row
5340
+	 * @return array
5341
+	 */
5342
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5343
+	{
5344
+		$results = [];
5345
+		if ($this->_custom_selections instanceof CustomSelects) {
5346
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5347
+				if (isset($db_results_row[ $alias ])) {
5348
+					$results[ $alias ] = $this->convertValueToDataType(
5349
+						$db_results_row[ $alias ],
5350
+						$this->_custom_selections->getDataTypeForAlias($alias)
5351
+					);
5352
+				}
5353
+			}
5354
+		}
5355
+		return $results;
5356
+	}
5357
+
5358
+
5359
+	/**
5360
+	 * This will set the value for the given alias
5361
+	 *
5362
+	 * @param string $value
5363
+	 * @param string $datatype (one of %d, %s, %f)
5364
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5365
+	 */
5366
+	protected function convertValueToDataType($value, $datatype)
5367
+	{
5368
+		switch ($datatype) {
5369
+			case '%f':
5370
+				return (float) $value;
5371
+			case '%d':
5372
+				return (int) $value;
5373
+			default:
5374
+				return (string) $value;
5375
+		}
5376
+	}
5377
+
5378
+
5379
+	/**
5380
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5381
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5382
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5383
+	 * object (as set in the model_field!).
5384
+	 *
5385
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5386
+	 * @throws EE_Error
5387
+	 * @throws ReflectionException
5388
+	 */
5389
+	public function create_default_object()
5390
+	{
5391
+		$this_model_fields_and_values = [];
5392
+		// setup the row using default values;
5393
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5394
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5395
+		}
5396
+		$className = $this->_get_class_name();
5397
+		return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5398
+	}
5399
+
5400
+
5401
+	/**
5402
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5403
+	 *                             or an stdClass where each property is the name of a column,
5404
+	 * @return EE_Base_Class
5405
+	 * @throws EE_Error
5406
+	 * @throws ReflectionException
5407
+	 */
5408
+	public function instantiate_class_from_array_or_object($cols_n_values)
5409
+	{
5410
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5411
+			$cols_n_values = get_object_vars($cols_n_values);
5412
+		}
5413
+		$primary_key = null;
5414
+		// make sure the array only has keys that are fields/columns on this model
5415
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5416
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5417
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5418
+		}
5419
+		$className = $this->_get_class_name();
5420
+		// check we actually found results that we can use to build our model object
5421
+		// if not, return null
5422
+		if ($this->has_primary_key_field()) {
5423
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5424
+				return null;
5425
+			}
5426
+		} elseif ($this->unique_indexes()) {
5427
+			$first_column = reset($this_model_fields_n_values);
5428
+			if (empty($first_column)) {
5429
+				return null;
5430
+			}
5431
+		}
5432
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5433
+		if ($primary_key) {
5434
+			$classInstance = $this->get_from_entity_map($primary_key);
5435
+			if (! $classInstance) {
5436
+				$classInstance = EE_Registry::instance()
5437
+											->load_class(
5438
+												$className,
5439
+												[$this_model_fields_n_values, $this->_timezone],
5440
+												true,
5441
+												false
5442
+											);
5443
+				// add this new object to the entity map
5444
+				$classInstance = $this->add_to_entity_map($classInstance);
5445
+			}
5446
+		} else {
5447
+			$classInstance = EE_Registry::instance()->load_class(
5448
+				$className,
5449
+				[$this_model_fields_n_values, $this->_timezone],
5450
+				true,
5451
+				false
5452
+			);
5453
+		}
5454
+		return $classInstance;
5455
+	}
5456
+
5457
+
5458
+	/**
5459
+	 * Gets the model object from the  entity map if it exists
5460
+	 *
5461
+	 * @param int|string $id the ID of the model object
5462
+	 * @return EE_Base_Class
5463
+	 */
5464
+	public function get_from_entity_map($id)
5465
+	{
5466
+		return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5467
+	}
5468
+
5469
+
5470
+	/**
5471
+	 * add_to_entity_map
5472
+	 * Adds the object to the model's entity mappings
5473
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5474
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5475
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5476
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5477
+	 *        then this method should be called immediately after the update query
5478
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5479
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5480
+	 *
5481
+	 * @param EE_Base_Class $object
5482
+	 * @return EE_Base_Class
5483
+	 * @throws EE_Error
5484
+	 * @throws ReflectionException
5485
+	 */
5486
+	public function add_to_entity_map(EE_Base_Class $object)
5487
+	{
5488
+		$className = $this->_get_class_name();
5489
+		if (! $object instanceof $className) {
5490
+			throw new EE_Error(
5491
+				sprintf(
5492
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5493
+					is_object($object)
5494
+						? get_class($object)
5495
+						: $object,
5496
+					$className
5497
+				)
5498
+			);
5499
+		}
5500
+
5501
+		if (! $object->ID()) {
5502
+			throw new EE_Error(
5503
+				sprintf(
5504
+					esc_html__(
5505
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5506
+						"event_espresso"
5507
+					),
5508
+					get_class($this)
5509
+				)
5510
+			);
5511
+		}
5512
+		// double check it's not already there
5513
+		$classInstance = $this->get_from_entity_map($object->ID());
5514
+		if ($classInstance) {
5515
+			return $classInstance;
5516
+		}
5517
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5518
+		return $object;
5519
+	}
5520
+
5521
+
5522
+	/**
5523
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5524
+	 * if no identifier is provided, then the entire entity map is emptied
5525
+	 *
5526
+	 * @param int|string $id the ID of the model object
5527
+	 * @return boolean
5528
+	 */
5529
+	public function clear_entity_map($id = null)
5530
+	{
5531
+		if (empty($id)) {
5532
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5533
+			return true;
5534
+		}
5535
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5536
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5537
+			return true;
5538
+		}
5539
+		return false;
5540
+	}
5541
+
5542
+
5543
+	/**
5544
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5545
+	 * Given an array where keys are column (or column alias) names and values,
5546
+	 * returns an array of their corresponding field names and database values
5547
+	 *
5548
+	 * @param array $cols_n_values
5549
+	 * @return array
5550
+	 * @throws EE_Error
5551
+	 * @throws ReflectionException
5552
+	 */
5553
+	public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5554
+	{
5555
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5556
+	}
5557
+
5558
+
5559
+	/**
5560
+	 * _deduce_fields_n_values_from_cols_n_values
5561
+	 * Given an array where keys are column (or column alias) names and values,
5562
+	 * returns an array of their corresponding field names and database values
5563
+	 *
5564
+	 * @param array|stdClass $cols_n_values
5565
+	 * @return array
5566
+	 * @throws EE_Error
5567
+	 * @throws ReflectionException
5568
+	 */
5569
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5570
+	{
5571
+		if ($cols_n_values instanceof stdClass) {
5572
+			$cols_n_values = get_object_vars($cols_n_values);
5573
+		}
5574
+		$this_model_fields_n_values = [];
5575
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5576
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5577
+				$cols_n_values,
5578
+				$table_obj->get_fully_qualified_pk_column(),
5579
+				$table_obj->get_pk_column()
5580
+			);
5581
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5582
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5583
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5584
+					if (! $field_obj->is_db_only_field()) {
5585
+						// prepare field as if its coming from db
5586
+						$prepared_value                            =
5587
+							$field_obj->prepare_for_set($field_obj->get_default_value());
5588
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5589
+					}
5590
+				}
5591
+			} else {
5592
+				// the table's rows existed. Use their values
5593
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5594
+					if (! $field_obj->is_db_only_field()) {
5595
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5596
+							$cols_n_values,
5597
+							$field_obj->get_qualified_column(),
5598
+							$field_obj->get_table_column()
5599
+						);
5600
+					}
5601
+				}
5602
+			}
5603
+		}
5604
+		return $this_model_fields_n_values;
5605
+	}
5606
+
5607
+
5608
+	/**
5609
+	 * @param $cols_n_values
5610
+	 * @param $qualified_column
5611
+	 * @param $regular_column
5612
+	 * @return null
5613
+	 * @throws EE_Error
5614
+	 * @throws ReflectionException
5615
+	 */
5616
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5617
+	{
5618
+		$value = null;
5619
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5620
+		// does the field on the model relate to this column retrieved from the db?
5621
+		// or is it a db-only field? (not relating to the model)
5622
+		if (isset($cols_n_values[ $qualified_column ])) {
5623
+			$value = $cols_n_values[ $qualified_column ];
5624
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5625
+			$value = $cols_n_values[ $regular_column ];
5626
+		} elseif (! empty($this->foreign_key_aliases)) {
5627
+			// no PK?  ok check if there is a foreign key alias set for this table
5628
+			// then check if that alias exists in the incoming data
5629
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5630
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5631
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5632
+					$value = $cols_n_values[ $FK_alias ];
5633
+					[$pk_class] = explode('.', $PK_column);
5634
+					$pk_model_name = "EEM_{$pk_class}";
5635
+					/** @var EEM_Base $pk_model */
5636
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5637
+					if ($pk_model instanceof EEM_Base) {
5638
+						// make sure object is pulled from db and added to entity map
5639
+						$pk_model->get_one_by_ID($value);
5640
+					}
5641
+					break;
5642
+				}
5643
+			}
5644
+		}
5645
+		return $value;
5646
+	}
5647
+
5648
+
5649
+	/**
5650
+	 * refresh_entity_map_from_db
5651
+	 * Makes sure the model object in the entity map at $id assumes the values
5652
+	 * of the database (opposite of EE_base_Class::save())
5653
+	 *
5654
+	 * @param int|string $id
5655
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5656
+	 * @throws EE_Error
5657
+	 * @throws ReflectionException
5658
+	 */
5659
+	public function refresh_entity_map_from_db($id)
5660
+	{
5661
+		$obj_in_map = $this->get_from_entity_map($id);
5662
+		if ($obj_in_map) {
5663
+			$wpdb_results = $this->_get_all_wpdb_results(
5664
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5665
+			);
5666
+			if ($wpdb_results && is_array($wpdb_results)) {
5667
+				$one_row = reset($wpdb_results);
5668
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5669
+					$obj_in_map->set_from_db($field_name, $db_value);
5670
+				}
5671
+				// clear the cache of related model objects
5672
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5673
+					$obj_in_map->clear_cache($relation_name, null, true);
5674
+				}
5675
+			}
5676
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5677
+			return $obj_in_map;
5678
+		}
5679
+		return $this->get_one_by_ID($id);
5680
+	}
5681
+
5682
+
5683
+	/**
5684
+	 * refresh_entity_map_with
5685
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5686
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5687
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5688
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5689
+	 *
5690
+	 * @param int|string    $id
5691
+	 * @param EE_Base_Class $replacing_model_obj
5692
+	 * @return EE_Base_Class
5693
+	 * @throws EE_Error
5694
+	 * @throws ReflectionException
5695
+	 */
5696
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5697
+	{
5698
+		$obj_in_map = $this->get_from_entity_map($id);
5699
+		if ($obj_in_map) {
5700
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5701
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5702
+					$obj_in_map->set($field_name, $value);
5703
+				}
5704
+				// make the model object in the entity map's cache match the $replacing_model_obj
5705
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5706
+					$obj_in_map->clear_cache($relation_name, null, true);
5707
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5708
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5709
+					}
5710
+				}
5711
+			}
5712
+			return $obj_in_map;
5713
+		}
5714
+		$this->add_to_entity_map($replacing_model_obj);
5715
+		return $replacing_model_obj;
5716
+	}
5717
+
5718
+
5719
+	/**
5720
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5721
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5722
+	 * require_once($this->_getClassName().".class.php");
5723
+	 *
5724
+	 * @return string
5725
+	 */
5726
+	private function _get_class_name()
5727
+	{
5728
+		return "EE_" . $this->get_this_model_name();
5729
+	}
5730
+
5731
+
5732
+	/**
5733
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5734
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5735
+	 * it would be 'Events'.
5736
+	 *
5737
+	 * @param int|float|null $quantity
5738
+	 * @return string
5739
+	 */
5740
+	public function item_name($quantity = 1): string
5741
+	{
5742
+		$quantity = floor($quantity);
5743
+		return apply_filters(
5744
+			'FHEE__EEM_Base__item_name__plural_or_singular',
5745
+			$quantity > 1
5746
+				? $this->plural_item
5747
+				: $this->singular_item,
5748
+			$quantity,
5749
+			$this->plural_item,
5750
+			$this->singular_item
5751
+		);
5752
+	}
5753
+
5754
+
5755
+	/**
5756
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5757
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5758
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5759
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5760
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5761
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5762
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5763
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5764
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5765
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5766
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5767
+	 *        return $previousReturnValue.$returnString;
5768
+	 * }
5769
+	 * require('EEM_Answer.model.php');
5770
+	 * echo EEM_Answer::instance()->my_callback('monkeys',100);
5771
+	 * // will output "you called my_callback! and passed args:monkeys,100"
5772
+	 *
5773
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5774
+	 * @param array  $args       array of original arguments passed to the function
5775
+	 * @return mixed whatever the plugin which calls add_filter decides
5776
+	 * @throws EE_Error
5777
+	 */
5778
+	public function __call($methodName, $args)
5779
+	{
5780
+		$className = get_class($this);
5781
+		$tagName   = "FHEE__{$className}__{$methodName}";
5782
+		if (! has_filter($tagName)) {
5783
+			throw new EE_Error(
5784
+				sprintf(
5785
+					esc_html__(
5786
+						'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 );',
5787
+						'event_espresso'
5788
+					),
5789
+					$methodName,
5790
+					$className,
5791
+					$tagName,
5792
+					'<br />'
5793
+				)
5794
+			);
5795
+		}
5796
+		return apply_filters($tagName, null, $this, $args);
5797
+	}
5798
+
5799
+
5800
+	/**
5801
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5802
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5803
+	 *
5804
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5805
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5806
+	 *                                                       the object's class name
5807
+	 *                                                       or object's ID
5808
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5809
+	 *                                                       exists in the database. If it does not, we add it
5810
+	 * @return EE_Base_Class
5811
+	 * @throws EE_Error
5812
+	 * @throws ReflectionException
5813
+	 */
5814
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5815
+	{
5816
+		$className = $this->_get_class_name();
5817
+		if ($base_class_obj_or_id instanceof $className) {
5818
+			$model_object = $base_class_obj_or_id;
5819
+		} else {
5820
+			$primary_key_field = $this->get_primary_key_field();
5821
+			if (
5822
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5823
+				&& (
5824
+					is_int($base_class_obj_or_id)
5825
+					|| is_string($base_class_obj_or_id)
5826
+				)
5827
+			) {
5828
+				// assume it's an ID.
5829
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5830
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5831
+			} elseif (
5832
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5833
+				&& is_string($base_class_obj_or_id)
5834
+			) {
5835
+				// assume its a string representation of the object
5836
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5837
+			} else {
5838
+				throw new EE_Error(
5839
+					sprintf(
5840
+						esc_html__(
5841
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5842
+							'event_espresso'
5843
+						),
5844
+						$base_class_obj_or_id,
5845
+						$this->_get_class_name(),
5846
+						print_r($base_class_obj_or_id, true)
5847
+					)
5848
+				);
5849
+			}
5850
+		}
5851
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5852
+			$model_object->save();
5853
+		}
5854
+		return $model_object;
5855
+	}
5856
+
5857
+
5858
+	/**
5859
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5860
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5861
+	 * returns it ID.
5862
+	 *
5863
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5864
+	 * @return int|string depending on the type of this model object's ID
5865
+	 * @throws EE_Error
5866
+	 * @throws ReflectionException
5867
+	 */
5868
+	public function ensure_is_ID($base_class_obj_or_id)
5869
+	{
5870
+		$className = $this->_get_class_name();
5871
+		if ($base_class_obj_or_id instanceof $className) {
5872
+			/** @var $base_class_obj_or_id EE_Base_Class */
5873
+			$id = $base_class_obj_or_id->ID();
5874
+		} elseif (is_int($base_class_obj_or_id)) {
5875
+			// assume it's an ID
5876
+			$id = $base_class_obj_or_id;
5877
+		} elseif (is_string($base_class_obj_or_id)) {
5878
+			// assume its a string representation of the object
5879
+			$id = $base_class_obj_or_id;
5880
+		} else {
5881
+			throw new EE_Error(
5882
+				sprintf(
5883
+					esc_html__(
5884
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5885
+						'event_espresso'
5886
+					),
5887
+					$base_class_obj_or_id,
5888
+					$this->_get_class_name(),
5889
+					print_r($base_class_obj_or_id, true)
5890
+				)
5891
+			);
5892
+		}
5893
+		return $id;
5894
+	}
5895
+
5896
+
5897
+	/**
5898
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5899
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5900
+	 * been sanitized and converted into the appropriate domain.
5901
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5902
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5903
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5904
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5905
+	 * $EVT = EEM_Event::instance(); $old_setting =
5906
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5907
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5908
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5909
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5910
+	 *
5911
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5912
+	 * @return void
5913
+	 */
5914
+	public function assume_values_already_prepared_by_model_object(
5915
+		$values_already_prepared = self::not_prepared_by_model_object
5916
+	) {
5917
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5918
+	}
5919
+
5920
+
5921
+	/**
5922
+	 * Read comments for assume_values_already_prepared_by_model_object()
5923
+	 *
5924
+	 * @return int
5925
+	 */
5926
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5927
+	{
5928
+		return $this->_values_already_prepared_by_model_object;
5929
+	}
5930
+
5931
+
5932
+	/**
5933
+	 * Gets all the indexes on this model
5934
+	 *
5935
+	 * @return EE_Index[]
5936
+	 */
5937
+	public function indexes()
5938
+	{
5939
+		return $this->_indexes;
5940
+	}
5941
+
5942
+
5943
+	/**
5944
+	 * Gets all the Unique Indexes on this model
5945
+	 *
5946
+	 * @return EE_Unique_Index[]
5947
+	 */
5948
+	public function unique_indexes()
5949
+	{
5950
+		$unique_indexes = [];
5951
+		foreach ($this->_indexes as $name => $index) {
5952
+			if ($index instanceof EE_Unique_Index) {
5953
+				$unique_indexes [ $name ] = $index;
5954
+			}
5955
+		}
5956
+		return $unique_indexes;
5957
+	}
5958
+
5959
+
5960
+	/**
5961
+	 * Gets all the fields which, when combined, make the primary key.
5962
+	 * This is usually just an array with 1 element (the primary key), but in cases
5963
+	 * where there is no primary key, it's a combination of fields as defined
5964
+	 * on a primary index
5965
+	 *
5966
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5967
+	 * @throws EE_Error
5968
+	 */
5969
+	public function get_combined_primary_key_fields()
5970
+	{
5971
+		foreach ($this->indexes() as $index) {
5972
+			if ($index instanceof EE_Primary_Key_Index) {
5973
+				return $index->fields();
5974
+			}
5975
+		}
5976
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5977
+	}
5978
+
5979
+
5980
+	/**
5981
+	 * Used to build a primary key string (when the model has no primary key),
5982
+	 * which can be used a unique string to identify this model object.
5983
+	 *
5984
+	 * @param array $fields_n_values keys are field names, values are their values.
5985
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5986
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5987
+	 *                               before passing it to this function (that will convert it from columns-n-values
5988
+	 *                               to field-names-n-values).
5989
+	 * @return string
5990
+	 * @throws EE_Error
5991
+	 */
5992
+	public function get_index_primary_key_string($fields_n_values)
5993
+	{
5994
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5995
+			$fields_n_values,
5996
+			$this->get_combined_primary_key_fields()
5997
+		);
5998
+		return http_build_query($cols_n_values_for_primary_key_index);
5999
+	}
6000
+
6001
+
6002
+	/**
6003
+	 * Gets the field values from the primary key string
6004
+	 *
6005
+	 * @param string $index_primary_key_string
6006
+	 * @return null|array
6007
+	 * @throws EE_Error
6008
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
6009
+	 */
6010
+	public function parse_index_primary_key_string($index_primary_key_string)
6011
+	{
6012
+		$key_fields = $this->get_combined_primary_key_fields();
6013
+		// check all of them are in the $id
6014
+		$key_vals_in_combined_pk = [];
6015
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6016
+		foreach ($key_fields as $key_field_name => $field_obj) {
6017
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6018
+				return null;
6019
+			}
6020
+		}
6021
+		return $key_vals_in_combined_pk;
6022
+	}
6023
+
6024
+
6025
+	/**
6026
+	 * verifies that an array of key-value pairs for model fields has a key
6027
+	 * for each field comprising the primary key index
6028
+	 *
6029
+	 * @param array $key_vals
6030
+	 * @return boolean
6031
+	 * @throws EE_Error
6032
+	 */
6033
+	public function has_all_combined_primary_key_fields($key_vals)
6034
+	{
6035
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6036
+		foreach ($keys_it_should_have as $key) {
6037
+			if (! isset($key_vals[ $key ])) {
6038
+				return false;
6039
+			}
6040
+		}
6041
+		return true;
6042
+	}
6043
+
6044
+
6045
+	/**
6046
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
6047
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
6048
+	 *
6049
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
6050
+	 * @param array               $query_params                     @see
6051
+	 *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
6052
+	 * @throws EE_Error
6053
+	 * @throws ReflectionException
6054
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
6055
+	 *                                                              indexed)
6056
+	 */
6057
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
6058
+	{
6059
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
6060
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
6061
+		} elseif (is_array($model_object_or_attributes_array)) {
6062
+			$attributes_array = $model_object_or_attributes_array;
6063
+		} else {
6064
+			throw new EE_Error(
6065
+				sprintf(
6066
+					esc_html__(
6067
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
6068
+						"event_espresso"
6069
+					),
6070
+					$model_object_or_attributes_array
6071
+				)
6072
+			);
6073
+		}
6074
+		// even copies obviously won't have the same ID, so remove the primary key
6075
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
6076
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6077
+			unset($attributes_array[ $this->primary_key_name() ]);
6078
+		}
6079
+		if (isset($query_params[0])) {
6080
+			$query_params[0] = array_merge($attributes_array, $query_params);
6081
+		} else {
6082
+			$query_params[0] = $attributes_array;
6083
+		}
6084
+		return $this->get_all($query_params);
6085
+	}
6086
+
6087
+
6088
+	/**
6089
+	 * Gets the first copy we find. See get_all_copies for more details
6090
+	 *
6091
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6092
+	 * @param array $query_params
6093
+	 * @return EE_Base_Class
6094
+	 * @throws EE_Error
6095
+	 * @throws ReflectionException
6096
+	 */
6097
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6098
+	{
6099
+		if (! is_array($query_params)) {
6100
+			EE_Error::doing_it_wrong(
6101
+				'EEM_Base::get_one_copy',
6102
+				sprintf(
6103
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6104
+					gettype($query_params)
6105
+				),
6106
+				'4.6.0'
6107
+			);
6108
+			$query_params = [];
6109
+		}
6110
+		$query_params['limit'] = 1;
6111
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6112
+		if (is_array($copies)) {
6113
+			return array_shift($copies);
6114
+		}
6115
+		return null;
6116
+	}
6117
+
6118
+
6119
+	/**
6120
+	 * Updates the item with the specified id. Ignores default query parameters because
6121
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6122
+	 *
6123
+	 * @param array      $fields_n_values keys are field names, values are their new values
6124
+	 * @param int|string $id              the value of the primary key to update
6125
+	 * @return int number of rows updated
6126
+	 * @throws EE_Error
6127
+	 * @throws ReflectionException
6128
+	 */
6129
+	public function update_by_ID($fields_n_values, $id)
6130
+	{
6131
+		$query_params = [
6132
+			0                          => [$this->get_primary_key_field()->get_name() => $id],
6133
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6134
+		];
6135
+		return $this->update($fields_n_values, $query_params);
6136
+	}
6137
+
6138
+
6139
+	/**
6140
+	 * Changes an operator which was supplied to the models into one usable in SQL
6141
+	 *
6142
+	 * @param string $operator_supplied
6143
+	 * @return string an operator which can be used in SQL
6144
+	 * @throws EE_Error
6145
+	 */
6146
+	private function _prepare_operator_for_sql($operator_supplied)
6147
+	{
6148
+		$sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6149
+		if ($sql_operator) {
6150
+			return $sql_operator;
6151
+		}
6152
+		throw new EE_Error(
6153
+			sprintf(
6154
+				esc_html__(
6155
+					"The operator '%s' is not in the list of valid operators: %s",
6156
+					"event_espresso"
6157
+				),
6158
+				$operator_supplied,
6159
+				implode(",", array_keys($this->_valid_operators))
6160
+			)
6161
+		);
6162
+	}
6163
+
6164
+
6165
+	/**
6166
+	 * Gets the valid operators
6167
+	 *
6168
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6169
+	 */
6170
+	public function valid_operators()
6171
+	{
6172
+		return $this->_valid_operators;
6173
+	}
6174
+
6175
+
6176
+	/**
6177
+	 * Gets the between-style operators (take 2 arguments).
6178
+	 *
6179
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6180
+	 */
6181
+	public function valid_between_style_operators()
6182
+	{
6183
+		return array_intersect(
6184
+			$this->valid_operators(),
6185
+			$this->_between_style_operators
6186
+		);
6187
+	}
6188
+
6189
+
6190
+	/**
6191
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6192
+	 *
6193
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6194
+	 */
6195
+	public function valid_like_style_operators()
6196
+	{
6197
+		return array_intersect(
6198
+			$this->valid_operators(),
6199
+			$this->_like_style_operators
6200
+		);
6201
+	}
6202
+
6203
+
6204
+	/**
6205
+	 * Gets the "in"-style operators
6206
+	 *
6207
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6208
+	 */
6209
+	public function valid_in_style_operators()
6210
+	{
6211
+		return array_intersect(
6212
+			$this->valid_operators(),
6213
+			$this->_in_style_operators
6214
+		);
6215
+	}
6216
+
6217
+
6218
+	/**
6219
+	 * Gets the "null"-style operators (accept no arguments)
6220
+	 *
6221
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6222
+	 */
6223
+	public function valid_null_style_operators()
6224
+	{
6225
+		return array_intersect(
6226
+			$this->valid_operators(),
6227
+			$this->_null_style_operators
6228
+		);
6229
+	}
6230
+
6231
+
6232
+	/**
6233
+	 * Gets an array where keys are the primary keys and values are their 'names'
6234
+	 * (as determined by the model object's name() function, which is often overridden)
6235
+	 *
6236
+	 * @param array $query_params like get_all's
6237
+	 * @return string[]
6238
+	 * @throws EE_Error
6239
+	 * @throws ReflectionException
6240
+	 */
6241
+	public function get_all_names($query_params = [])
6242
+	{
6243
+		$objs  = $this->get_all($query_params);
6244
+		$names = [];
6245
+		foreach ($objs as $obj) {
6246
+			$names[ $obj->ID() ] = $obj->name();
6247
+		}
6248
+		return $names;
6249
+	}
6250
+
6251
+
6252
+	/**
6253
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6254
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6255
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6256
+	 * array_keys() on $model_objects.
6257
+	 *
6258
+	 * @param \EE_Base_Class[] $model_objects
6259
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6260
+	 *                                               in the returned array
6261
+	 * @return array
6262
+	 * @throws EE_Error
6263
+	 * @throws ReflectionException
6264
+	 */
6265
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6266
+	{
6267
+		if (! $this->has_primary_key_field()) {
6268
+			if (WP_DEBUG) {
6269
+				EE_Error::add_error(
6270
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6271
+					__FILE__,
6272
+					__FUNCTION__,
6273
+					__LINE__
6274
+				);
6275
+			}
6276
+		}
6277
+		$IDs = [];
6278
+		foreach ($model_objects as $model_object) {
6279
+			$id = $model_object->ID();
6280
+			if (! $id) {
6281
+				if ($filter_out_empty_ids) {
6282
+					continue;
6283
+				}
6284
+				if (WP_DEBUG) {
6285
+					EE_Error::add_error(
6286
+						esc_html__(
6287
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6288
+							'event_espresso'
6289
+						),
6290
+						__FILE__,
6291
+						__FUNCTION__,
6292
+						__LINE__
6293
+					);
6294
+				}
6295
+			}
6296
+			$IDs[] = $id;
6297
+		}
6298
+		return $IDs;
6299
+	}
6300
+
6301
+
6302
+	/**
6303
+	 * Returns the string used in capabilities relating to this model. If there
6304
+	 * are no capabilities that relate to this model returns false
6305
+	 *
6306
+	 * @return string|false
6307
+	 */
6308
+	public function cap_slug()
6309
+	{
6310
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6311
+	}
6312
+
6313
+
6314
+	/**
6315
+	 * Returns the capability-restrictions array (@param string $context
6316
+	 *
6317
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6318
+	 * @throws EE_Error
6319
+	 * @see EEM_Base::_cap_restrictions).
6320
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6321
+	 *      only returns the cap restrictions array in that context (ie, the array
6322
+	 *      at that key)
6323
+	 */
6324
+	public function cap_restrictions($context = EEM_Base::caps_read)
6325
+	{
6326
+		EEM_Base::verify_is_valid_cap_context($context);
6327
+		// check if we ought to run the restriction generator first
6328
+		if (
6329
+			isset($this->_cap_restriction_generators[ $context ])
6330
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6331
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6332
+		) {
6333
+			$this->_cap_restrictions[ $context ] = array_merge(
6334
+				$this->_cap_restrictions[ $context ],
6335
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6336
+			);
6337
+		}
6338
+		// and make sure we've finalized the construction of each restriction
6339
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6340
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6341
+				$where_conditions_obj->_finalize_construct($this);
6342
+			}
6343
+		}
6344
+		return $this->_cap_restrictions[ $context ];
6345
+	}
6346
+
6347
+
6348
+	/**
6349
+	 * Indicating whether or not this model thinks its a wp core model
6350
+	 *
6351
+	 * @return boolean
6352
+	 */
6353
+	public function is_wp_core_model()
6354
+	{
6355
+		return $this->_wp_core_model;
6356
+	}
6357
+
6358
+
6359
+	/**
6360
+	 * Gets all the caps that are missing which impose a restriction on
6361
+	 * queries made in this context
6362
+	 *
6363
+	 * @param string $context one of EEM_Base::caps_ constants
6364
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6365
+	 * @throws EE_Error
6366
+	 */
6367
+	public function caps_missing($context = EEM_Base::caps_read)
6368
+	{
6369
+		$missing_caps     = [];
6370
+		$cap_restrictions = $this->cap_restrictions($context);
6371
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6372
+			if (
6373
+				! EE_Capabilities::instance()
6374
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6375
+			) {
6376
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6377
+			}
6378
+		}
6379
+		return $missing_caps;
6380
+	}
6381
+
6382
+
6383
+	/**
6384
+	 * Gets the mapping from capability contexts to action strings used in capability names
6385
+	 *
6386
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6387
+	 * one of 'read', 'edit', or 'delete'
6388
+	 */
6389
+	public function cap_contexts_to_cap_action_map()
6390
+	{
6391
+		return apply_filters(
6392
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6393
+			$this->_cap_contexts_to_cap_action_map,
6394
+			$this
6395
+		);
6396
+	}
6397
+
6398
+
6399
+	/**
6400
+	 * Gets the action string for the specified capability context
6401
+	 *
6402
+	 * @param string $context
6403
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6404
+	 * @throws EE_Error
6405
+	 */
6406
+	public function cap_action_for_context($context)
6407
+	{
6408
+		$mapping = $this->cap_contexts_to_cap_action_map();
6409
+		if (isset($mapping[ $context ])) {
6410
+			return $mapping[ $context ];
6411
+		}
6412
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6413
+			return $action;
6414
+		}
6415
+		throw new EE_Error(
6416
+			sprintf(
6417
+				esc_html__(
6418
+					'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6419
+					'event_espresso'
6420
+				),
6421
+				$context,
6422
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6423
+			)
6424
+		);
6425
+	}
6426
+
6427
+
6428
+	/**
6429
+	 * Returns all the capability contexts which are valid when querying models
6430
+	 *
6431
+	 * @return array
6432
+	 */
6433
+	public static function valid_cap_contexts(): array
6434
+	{
6435
+		return (array) apply_filters(
6436
+			'FHEE__EEM_Base__valid_cap_contexts',
6437
+			[
6438
+				self::caps_read,
6439
+				self::caps_read_admin,
6440
+				self::caps_edit,
6441
+				self::caps_delete,
6442
+			]
6443
+		);
6444
+	}
6445
+
6446
+
6447
+	/**
6448
+	 * Returns all valid options for 'default_where_conditions'
6449
+	 *
6450
+	 * @return array
6451
+	 */
6452
+	public static function valid_default_where_conditions(): array
6453
+	{
6454
+		return [
6455
+			EEM_Base::default_where_conditions_all,
6456
+			EEM_Base::default_where_conditions_this_only,
6457
+			EEM_Base::default_where_conditions_others_only,
6458
+			EEM_Base::default_where_conditions_minimum_all,
6459
+			EEM_Base::default_where_conditions_minimum_others,
6460
+			EEM_Base::default_where_conditions_none,
6461
+		];
6462
+	}
6463
+
6464
+	// public static function default_where_conditions_full
6465
+
6466
+
6467
+	/**
6468
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6469
+	 *
6470
+	 * @param string $context
6471
+	 * @return bool
6472
+	 * @throws EE_Error
6473
+	 */
6474
+	public static function verify_is_valid_cap_context($context): bool
6475
+	{
6476
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6477
+		if (in_array($context, $valid_cap_contexts)) {
6478
+			return true;
6479
+		}
6480
+		throw new EE_Error(
6481
+			sprintf(
6482
+				esc_html__(
6483
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6484
+					'event_espresso'
6485
+				),
6486
+				$context,
6487
+				'EEM_Base',
6488
+				implode(',', $valid_cap_contexts)
6489
+			)
6490
+		);
6491
+	}
6492
+
6493
+
6494
+	/**
6495
+	 * Clears all the models field caches. This is only useful when a sub-class
6496
+	 * might have added a field or something and these caches might be invalidated
6497
+	 */
6498
+	protected function _invalidate_field_caches()
6499
+	{
6500
+		$this->_cache_foreign_key_to_fields = [];
6501
+		$this->_cached_fields               = null;
6502
+		$this->_cached_fields_non_db_only   = null;
6503
+	}
6504
+
6505
+
6506
+	/**
6507
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6508
+	 * (eg "and", "or", "not").
6509
+	 *
6510
+	 * @return array
6511
+	 */
6512
+	public function logic_query_param_keys(): array
6513
+	{
6514
+		return $this->_logic_query_param_keys;
6515
+	}
6516
+
6517
+
6518
+	/**
6519
+	 * Determines whether or not the where query param array key is for a logic query param.
6520
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6521
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6522
+	 *
6523
+	 * @param $query_param_key
6524
+	 * @return bool
6525
+	 */
6526
+	public function is_logic_query_param_key($query_param_key): bool
6527
+	{
6528
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6529
+			if (
6530
+				$query_param_key === $logic_query_param_key
6531
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6532
+			) {
6533
+				return true;
6534
+			}
6535
+		}
6536
+		return false;
6537
+	}
6538
+
6539
+
6540
+	/**
6541
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6542
+	 *
6543
+	 * @return boolean
6544
+	 * @since 4.9.74.p
6545
+	 */
6546
+	public function hasPassword(): bool
6547
+	{
6548
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6549
+		if ($this->has_password_field === null) {
6550
+			$password_field           = $this->getPasswordField();
6551
+			$this->has_password_field = $password_field instanceof EE_Password_Field;
6552
+		}
6553
+		return $this->has_password_field;
6554
+	}
6555
+
6556
+
6557
+	/**
6558
+	 * Returns the password field on this model, if there is one
6559
+	 *
6560
+	 * @return EE_Password_Field|null
6561
+	 * @since 4.9.74.p
6562
+	 */
6563
+	public function getPasswordField()
6564
+	{
6565
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6566
+		// there's no need to search for it. If we don't know yet, then find out
6567
+		if ($this->has_password_field === null && $this->password_field === null) {
6568
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6569
+		}
6570
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6571
+		return $this->password_field;
6572
+	}
6573
+
6574
+
6575
+	/**
6576
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6577
+	 *
6578
+	 * @return EE_Model_Field_Base[]
6579
+	 * @throws EE_Error
6580
+	 * @since 4.9.74.p
6581
+	 */
6582
+	public function getPasswordProtectedFields()
6583
+	{
6584
+		$password_field = $this->getPasswordField();
6585
+		$fields         = [];
6586
+		if ($password_field instanceof EE_Password_Field) {
6587
+			$field_names = $password_field->protectedFields();
6588
+			foreach ($field_names as $field_name) {
6589
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6590
+			}
6591
+		}
6592
+		return $fields;
6593
+	}
6594
+
6595
+
6596
+	/**
6597
+	 * Checks if the current user can perform the requested action on this model
6598
+	 *
6599
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6600
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6601
+	 * @return bool
6602
+	 * @throws EE_Error
6603
+	 * @throws InvalidArgumentException
6604
+	 * @throws InvalidDataTypeException
6605
+	 * @throws InvalidInterfaceException
6606
+	 * @throws ReflectionException
6607
+	 * @throws UnexpectedEntityException
6608
+	 * @since 4.9.74.p
6609
+	 */
6610
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6611
+	{
6612
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6613
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6614
+		}
6615
+		if (! is_array($model_obj_or_fields_n_values)) {
6616
+			throw new UnexpectedEntityException(
6617
+				$model_obj_or_fields_n_values,
6618
+				'EE_Base_Class',
6619
+				sprintf(
6620
+					esc_html__(
6621
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6622
+						'event_espresso'
6623
+					),
6624
+					__FUNCTION__
6625
+				)
6626
+			);
6627
+		}
6628
+		return $this->exists(
6629
+			$this->alter_query_params_to_restrict_by_ID(
6630
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6631
+				[
6632
+					'default_where_conditions' => 'none',
6633
+					'caps'                     => $cap_to_check,
6634
+				]
6635
+			)
6636
+		);
6637
+	}
6638
+
6639
+
6640
+	/**
6641
+	 * Returns the query param where conditions key to the password affecting this model.
6642
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6643
+	 *
6644
+	 * @return null|string
6645
+	 * @throws EE_Error
6646
+	 * @throws InvalidArgumentException
6647
+	 * @throws InvalidDataTypeException
6648
+	 * @throws InvalidInterfaceException
6649
+	 * @throws ModelConfigurationException
6650
+	 * @throws ReflectionException
6651
+	 * @since 4.9.74.p
6652
+	 */
6653
+	public function modelChainAndPassword()
6654
+	{
6655
+		if ($this->model_chain_to_password === null) {
6656
+			throw new ModelConfigurationException(
6657
+				$this,
6658
+				esc_html_x(
6659
+				// @codingStandardsIgnoreStart
6660
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6661
+					// @codingStandardsIgnoreEnd
6662
+					'1: model name',
6663
+					'event_espresso'
6664
+				)
6665
+			);
6666
+		}
6667
+		if ($this->model_chain_to_password === '') {
6668
+			$model_with_password = $this;
6669
+		} else {
6670
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6671
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6672
+			} else {
6673
+				$last_model_in_chain = $this->model_chain_to_password;
6674
+			}
6675
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6676
+		}
6677
+
6678
+		$password_field = $model_with_password->getPasswordField();
6679
+		if ($password_field instanceof EE_Password_Field) {
6680
+			$password_field_name = $password_field->get_name();
6681
+		} else {
6682
+			throw new ModelConfigurationException(
6683
+				$this,
6684
+				sprintf(
6685
+					esc_html_x(
6686
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6687
+						'1: model name, 2: special string',
6688
+						'event_espresso'
6689
+					),
6690
+					$model_with_password->get_this_model_name(),
6691
+					$this->model_chain_to_password
6692
+				)
6693
+			);
6694
+		}
6695
+		return (
6696
+			   $this->model_chain_to_password
6697
+				   ? $this->model_chain_to_password . '.'
6698
+				   : ''
6699
+			   ) . $password_field_name;
6700
+	}
6701
+
6702
+
6703
+	/**
6704
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6705
+	 * or if this model itself has a password affecting access to some of its other fields.
6706
+	 *
6707
+	 * @return boolean
6708
+	 * @since 4.9.74.p
6709
+	 */
6710
+	public function restrictedByRelatedModelPassword(): bool
6711
+	{
6712
+		return $this->model_chain_to_password !== null;
6713
+	}
6714 6714
 }
Please login to merge, or discard this patch.
Spacing   +230 added lines, -230 removed lines patch added patch discarded remove patch
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
     protected function __construct($timezone = '')
566 566
     {
567 567
         // check that the model has not been loaded too soon
568
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
568
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
569 569
             throw new EE_Error(
570 570
                 sprintf(
571 571
                     esc_html__(
@@ -588,7 +588,7 @@  discard block
 block discarded – undo
588 588
          *
589 589
          * @var EE_Table_Base[] $_tables
590 590
          */
591
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
591
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
592 592
         foreach ($this->_tables as $table_alias => $table_obj) {
593 593
             /** @var $table_obj EE_Table_Base */
594 594
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -602,10 +602,10 @@  discard block
 block discarded – undo
602 602
          *
603 603
          * @param EE_Model_Field_Base[] $_fields
604 604
          */
605
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
605
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
606 606
         $this->_invalidate_field_caches();
607 607
         foreach ($this->_fields as $table_alias => $fields_for_table) {
608
-            if (! array_key_exists($table_alias, $this->_tables)) {
608
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
609 609
                 throw new EE_Error(
610 610
                     sprintf(
611 611
                         esc_html__(
@@ -642,7 +642,7 @@  discard block
 block discarded – undo
642 642
          * @param EE_Model_Relation_Base[] $_model_relations
643 643
          */
644 644
         $this->_model_relations = (array) apply_filters(
645
-            'FHEE__' . get_class($this) . '__construct__model_relations',
645
+            'FHEE__'.get_class($this).'__construct__model_relations',
646 646
             $this->_model_relations
647 647
         );
648 648
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -654,12 +654,12 @@  discard block
 block discarded – undo
654 654
         }
655 655
         $this->set_timezone($timezone);
656 656
         // finalize default where condition strategy, or set default
657
-        if (! $this->_default_where_conditions_strategy) {
657
+        if ( ! $this->_default_where_conditions_strategy) {
658 658
             // nothing was set during child constructor, so set default
659 659
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
660 660
         }
661 661
         $this->_default_where_conditions_strategy->_finalize_construct($this);
662
-        if (! $this->_minimum_where_conditions_strategy) {
662
+        if ( ! $this->_minimum_where_conditions_strategy) {
663 663
             // nothing was set during child constructor, so set default
664 664
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
665 665
         }
@@ -672,8 +672,8 @@  discard block
 block discarded – undo
672 672
         // initialize the standard cap restriction generators if none were specified by the child constructor
673 673
         if (is_array($this->_cap_restriction_generators)) {
674 674
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
675
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
676
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
675
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
676
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
677 677
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
678 678
                         new EE_Restriction_Generator_Protected(),
679 679
                         $cap_context,
@@ -685,10 +685,10 @@  discard block
 block discarded – undo
685 685
         // if there are cap restriction generators, use them to make the default cap restrictions
686 686
         if (is_array($this->_cap_restriction_generators)) {
687 687
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
688
-                if (! $generator_object) {
688
+                if ( ! $generator_object) {
689 689
                     continue;
690 690
                 }
691
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
691
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
692 692
                     throw new EE_Error(
693 693
                         sprintf(
694 694
                             esc_html__(
@@ -701,12 +701,12 @@  discard block
 block discarded – undo
701 701
                     );
702 702
                 }
703 703
                 $action = $this->cap_action_for_context($context);
704
-                if (! $generator_object->construction_finalized()) {
704
+                if ( ! $generator_object->construction_finalized()) {
705 705
                     $generator_object->_construct_finalize($this, $action);
706 706
                 }
707 707
             }
708 708
         }
709
-        do_action('AHEE__' . get_class($this) . '__construct__end');
709
+        do_action('AHEE__'.get_class($this).'__construct__end');
710 710
     }
711 711
 
712 712
 
@@ -718,7 +718,7 @@  discard block
 block discarded – undo
718 718
      */
719 719
     protected static function getLoader(): LoaderInterface
720 720
     {
721
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
721
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
722 722
             EEM_Base::$loader = LoaderFactory::getLoader();
723 723
         }
724 724
         return EEM_Base::$loader;
@@ -731,7 +731,7 @@  discard block
 block discarded – undo
731 731
      */
732 732
     private static function getMirror(): Mirror
733 733
     {
734
-        if (! EEM_Base::$mirror instanceof Mirror) {
734
+        if ( ! EEM_Base::$mirror instanceof Mirror) {
735 735
             EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
736 736
         }
737 737
         return EEM_Base::$mirror;
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
     public static function instance($timezone = '')
788 788
     {
789 789
         // check if instance of Espresso_model already exists
790
-        if (! static::$_instance instanceof static) {
790
+        if ( ! static::$_instance instanceof static) {
791 791
             $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
792 792
             $model     = new static(...$arguments);
793 793
             EEM_Base::getLoader()->share(static::class, $model, $arguments);
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
      */
817 817
     public static function reset($timezone = '')
818 818
     {
819
-        if (! static::$_instance instanceof EEM_Base) {
819
+        if ( ! static::$_instance instanceof EEM_Base) {
820 820
             return null;
821 821
         }
822 822
         // Let's NOT swap out the current instance for a new one
@@ -827,7 +827,7 @@  discard block
 block discarded – undo
827 827
         foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
828 828
             // don't set instance to null like it was originally,
829 829
             // but it's static anyways, and we're ignoring static properties (for now at least)
830
-            if (! isset($static_properties[ $property ])) {
830
+            if ( ! isset($static_properties[$property])) {
831 831
                 static::$_instance->{$property} = $value;
832 832
             }
833 833
         }
@@ -876,7 +876,7 @@  discard block
 block discarded – undo
876 876
      */
877 877
     public function status_array($translated = false)
878 878
     {
879
-        if (! array_key_exists('Status', $this->_model_relations)) {
879
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
880 880
             return [];
881 881
         }
882 882
         $model_name   = $this->get_this_model_name();
@@ -884,7 +884,7 @@  discard block
 block discarded – undo
884 884
         $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
885 885
         $status_array = [];
886 886
         foreach ($stati as $status) {
887
-            $status_array[ $status->ID() ] = $status->get('STS_code');
887
+            $status_array[$status->ID()] = $status->get('STS_code');
888 888
         }
889 889
         return $translated
890 890
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -949,7 +949,7 @@  discard block
 block discarded – undo
949 949
     {
950 950
         $wp_user_field_name = $this->wp_user_field_name();
951 951
         if ($wp_user_field_name) {
952
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
952
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
953 953
         }
954 954
         return $query_params;
955 955
     }
@@ -968,17 +968,17 @@  discard block
 block discarded – undo
968 968
     public function wp_user_field_name()
969 969
     {
970 970
         try {
971
-            if (! empty($this->_model_chain_to_wp_user)) {
971
+            if ( ! empty($this->_model_chain_to_wp_user)) {
972 972
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
973 973
                 $last_model_name              = end($models_to_follow_to_wp_users);
974 974
                 $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
975
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
975
+                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user.'.';
976 976
             } else {
977 977
                 $model_with_fk_to_wp_users = $this;
978 978
                 $model_chain_to_wp_user    = '';
979 979
             }
980 980
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
981
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
981
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
982 982
         } catch (EE_Error $e) {
983 983
             return false;
984 984
         }
@@ -1054,11 +1054,11 @@  discard block
 block discarded – undo
1054 1054
         if ($this->_custom_selections instanceof CustomSelects) {
1055 1055
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1056 1056
             $select_expressions .= $select_expressions
1057
-                ? ', ' . $custom_expressions
1057
+                ? ', '.$custom_expressions
1058 1058
                 : $custom_expressions;
1059 1059
         }
1060 1060
 
1061
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1061
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1062 1062
         return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1063 1063
     }
1064 1064
 
@@ -1075,7 +1075,7 @@  discard block
 block discarded – undo
1075 1075
      */
1076 1076
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1077 1077
     {
1078
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1078
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1079 1079
             return null;
1080 1080
         }
1081 1081
         $selects = $query_params['extra_selects'] ?? $columns_to_select;
@@ -1126,7 +1126,7 @@  discard block
 block discarded – undo
1126 1126
         if (is_array($columns_to_select)) {
1127 1127
             $select_sql_array = [];
1128 1128
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1129
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1129
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1130 1130
                     throw new EE_Error(
1131 1131
                         sprintf(
1132 1132
                             esc_html__(
@@ -1138,7 +1138,7 @@  discard block
 block discarded – undo
1138 1138
                         )
1139 1139
                     );
1140 1140
                 }
1141
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1141
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1142 1142
                     throw new EE_Error(
1143 1143
                         sprintf(
1144 1144
                             esc_html__(
@@ -1194,7 +1194,7 @@  discard block
 block discarded – undo
1194 1194
                 ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1195 1195
             )
1196 1196
         );
1197
-        $className    = $this->_get_class_name();
1197
+        $className = $this->_get_class_name();
1198 1198
         if ($model_object instanceof $className) {
1199 1199
             // make sure valid objects get added to the entity map
1200 1200
             // so that the next call to this method doesn't trigger another trip to the db
@@ -1217,12 +1217,12 @@  discard block
 block discarded – undo
1217 1217
      */
1218 1218
     public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1219 1219
     {
1220
-        if (! isset($query_params[0])) {
1220
+        if ( ! isset($query_params[0])) {
1221 1221
             $query_params[0] = [];
1222 1222
         }
1223 1223
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1224 1224
         if ($conditions_from_id === null) {
1225
-            $query_params[0][ $this->primary_key_name() ] = $id;
1225
+            $query_params[0][$this->primary_key_name()] = $id;
1226 1226
         } else {
1227 1227
             // no primary key, so the $id must be from the get_index_primary_key_string()
1228 1228
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1242,7 +1242,7 @@  discard block
 block discarded – undo
1242 1242
      */
1243 1243
     public function get_one($query_params = [])
1244 1244
     {
1245
-        if (! is_array($query_params)) {
1245
+        if ( ! is_array($query_params)) {
1246 1246
             EE_Error::doing_it_wrong(
1247 1247
                 'EEM_Base::get_one',
1248 1248
                 sprintf(
@@ -1451,7 +1451,7 @@  discard block
 block discarded – undo
1451 1451
                 return [];
1452 1452
             }
1453 1453
         }
1454
-        if (! is_array($query_params)) {
1454
+        if ( ! is_array($query_params)) {
1455 1455
             EE_Error::doing_it_wrong(
1456 1456
                 'EEM_Base::_get_consecutive',
1457 1457
                 sprintf(
@@ -1463,7 +1463,7 @@  discard block
 block discarded – undo
1463 1463
             $query_params = [];
1464 1464
         }
1465 1465
         // let's add the where query param for consecutive look up.
1466
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1466
+        $query_params[0][$field_to_order_by] = [$operand, $current_field_value];
1467 1467
         $query_params['limit']                 = $limit;
1468 1468
         // set direction
1469 1469
         $incoming_orderby         = isset($query_params['order_by'])
@@ -1489,7 +1489,7 @@  discard block
 block discarded – undo
1489 1489
      */
1490 1490
     public function set_timezone(?string $timezone = '')
1491 1491
     {
1492
-        if (! $timezone) {
1492
+        if ( ! $timezone) {
1493 1493
             return;
1494 1494
         }
1495 1495
         $this->_timezone = $timezone;
@@ -1546,7 +1546,7 @@  discard block
 block discarded – undo
1546 1546
     {
1547 1547
         $field_settings = $this->field_settings_for($field_name);
1548 1548
         // if not a valid EE_Datetime_Field then throw error
1549
-        if (! $field_settings instanceof EE_Datetime_Field) {
1549
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1550 1550
             throw new EE_Error(
1551 1551
                 sprintf(
1552 1552
                     esc_html__(
@@ -1704,7 +1704,7 @@  discard block
 block discarded – undo
1704 1704
      */
1705 1705
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1706 1706
     {
1707
-        if (! is_array($query_params)) {
1707
+        if ( ! is_array($query_params)) {
1708 1708
             EE_Error::doing_it_wrong(
1709 1709
                 'EEM_Base::update',
1710 1710
                 sprintf(
@@ -1752,7 +1752,7 @@  discard block
 block discarded – undo
1752 1752
             $wpdb_result = (array) $wpdb_result;
1753 1753
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1754 1754
             if ($this->has_primary_key_field()) {
1755
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1755
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1756 1756
             } else {
1757 1757
                 // 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)
1758 1758
                 $main_table_pk_value = null;
@@ -1768,7 +1768,7 @@  discard block
 block discarded – undo
1768 1768
                     // in this table, right? so insert a row in the current table, using any fields available
1769 1769
                     if (
1770 1770
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1771
-                           && $wpdb_result[ $this_table_pk_column ])
1771
+                           && $wpdb_result[$this_table_pk_column])
1772 1772
                     ) {
1773 1773
                         $success = $this->_insert_into_specific_table(
1774 1774
                             $table_obj,
@@ -1776,7 +1776,7 @@  discard block
 block discarded – undo
1776 1776
                             $main_table_pk_value
1777 1777
                         );
1778 1778
                         // if we died here, report the error
1779
-                        if (! $success) {
1779
+                        if ( ! $success) {
1780 1780
                             return false;
1781 1781
                         }
1782 1782
                     }
@@ -1804,10 +1804,10 @@  discard block
 block discarded – undo
1804 1804
                 $model_objs_affected_ids     = [];
1805 1805
                 foreach ($models_affected_key_columns as $row) {
1806 1806
                     $combined_index_key                             = $this->get_index_primary_key_string($row);
1807
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1807
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1808 1808
                 }
1809 1809
             }
1810
-            if (! $model_objs_affected_ids) {
1810
+            if ( ! $model_objs_affected_ids) {
1811 1811
                 // wait wait wait- if nothing was affected let's stop here
1812 1812
                 return 0;
1813 1813
             }
@@ -1836,8 +1836,8 @@  discard block
 block discarded – undo
1836 1836
         $rows_affected = $this->_do_wpdb_query(
1837 1837
             'query',
1838 1838
             [
1839
-                "UPDATE " . $model_query_info->get_full_join_sql()
1840
-                . " SET " . $this->_construct_update_sql($fields_n_values)
1839
+                "UPDATE ".$model_query_info->get_full_join_sql()
1840
+                . " SET ".$this->_construct_update_sql($fields_n_values)
1841 1841
                 . $model_query_info->get_where_sql(),
1842 1842
             ]
1843 1843
         );
@@ -1851,7 +1851,7 @@  discard block
 block discarded – undo
1851 1851
          * @param int      $rows_affected
1852 1852
          */
1853 1853
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1854
-        return $rows_affected;// how many supposedly got updated
1854
+        return $rows_affected; // how many supposedly got updated
1855 1855
     }
1856 1856
 
1857 1857
 
@@ -1884,7 +1884,7 @@  discard block
 block discarded – undo
1884 1884
         $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1885 1885
         $select_expressions = $field->get_qualified_column();
1886 1886
         $SQL                =
1887
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1887
+            "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1888 1888
         return $this->_do_wpdb_query('get_col', [$SQL]);
1889 1889
     }
1890 1890
 
@@ -1903,7 +1903,7 @@  discard block
 block discarded – undo
1903 1903
     {
1904 1904
         $query_params['limit'] = 1;
1905 1905
         $col                   = $this->get_col($query_params, $field_to_select);
1906
-        if (! empty($col)) {
1906
+        if ( ! empty($col)) {
1907 1907
             return reset($col);
1908 1908
         }
1909 1909
         return null;
@@ -1934,7 +1934,7 @@  discard block
 block discarded – undo
1934 1934
             $value_sql       = $prepared_value === null
1935 1935
                 ? 'NULL'
1936 1936
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1937
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1937
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1938 1938
         }
1939 1939
         return implode(",", $cols_n_values);
1940 1940
     }
@@ -2068,7 +2068,7 @@  discard block
 block discarded – undo
2068 2068
                                 . $model_query_info->get_full_join_sql()
2069 2069
                                 . " WHERE "
2070 2070
                                 . $deletion_where_query_part;
2071
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2071
+            $rows_deleted = $this->_do_wpdb_query('query', [$SQL]);
2072 2072
         } else {
2073 2073
             $rows_deleted = 0;
2074 2074
         }
@@ -2078,12 +2078,12 @@  discard block
 block discarded – undo
2078 2078
         if (
2079 2079
             $this->has_primary_key_field()
2080 2080
             && $rows_deleted !== false
2081
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2081
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2082 2082
         ) {
2083
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2083
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2084 2084
             foreach ($ids_for_removal as $id) {
2085
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2086
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2085
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2086
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2087 2087
                 }
2088 2088
             }
2089 2089
 
@@ -2122,7 +2122,7 @@  discard block
 block discarded – undo
2122 2122
          * @param int      $rows_deleted
2123 2123
          */
2124 2124
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2125
-        return $rows_deleted;// how many supposedly got deleted
2125
+        return $rows_deleted; // how many supposedly got deleted
2126 2126
     }
2127 2127
 
2128 2128
 
@@ -2221,15 +2221,15 @@  discard block
 block discarded – undo
2221 2221
                 if (
2222 2222
                     $allow_blocking
2223 2223
                     && $this->delete_is_blocked_by_related_models(
2224
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2224
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2225 2225
                     )
2226 2226
                 ) {
2227 2227
                     continue;
2228 2228
                 }
2229 2229
                 // primary table deletes
2230
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2231
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2232
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2230
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2231
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2232
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2233 2233
                 }
2234 2234
             }
2235 2235
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2238,8 +2238,8 @@  discard block
 block discarded – undo
2238 2238
                 $ids_to_delete_indexed_by_column_for_row = [];
2239 2239
                 foreach ($fields as $cpk_field) {
2240 2240
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2241
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2242
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2241
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2242
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2243 2243
                     }
2244 2244
                 }
2245 2245
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2277,7 +2277,7 @@  discard block
 block discarded – undo
2277 2277
         } elseif ($this->has_primary_key_field()) {
2278 2278
             $query = [];
2279 2279
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2280
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2280
+                $query[] = $column.' IN'.$this->_construct_in_value($ids, $this->_primary_key_field);
2281 2281
             }
2282 2282
             $query_part = ! empty($query)
2283 2283
                 ? implode(' AND ', $query)
@@ -2287,7 +2287,7 @@  discard block
 block discarded – undo
2287 2287
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2288 2288
                 $values_for_each_combined_primary_key_for_a_row = [];
2289 2289
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2290
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2290
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2291 2291
                 }
2292 2292
                 $ways_to_identify_a_row[] = '('
2293 2293
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2363,10 +2363,10 @@  discard block
 block discarded – undo
2363 2363
             }
2364 2364
         }
2365 2365
         $column_to_count = $distinct
2366
-            ? "DISTINCT " . $column_to_count
2366
+            ? "DISTINCT ".$column_to_count
2367 2367
             : $column_to_count;
2368 2368
         $SQL             =
2369
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2369
+            "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2370 2370
         return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2371 2371
     }
2372 2372
 
@@ -2391,7 +2391,7 @@  discard block
 block discarded – undo
2391 2391
         }
2392 2392
         $column_to_count = $field_obj->get_qualified_column();
2393 2393
         $SQL             =
2394
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2394
+            "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2395 2395
         $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2396 2396
         $data_type       = $field_obj->get_wpdb_data_type();
2397 2397
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2417,7 +2417,7 @@  discard block
 block discarded – undo
2417 2417
         // if we're in maintenance mode level 2, DON'T run any queries
2418 2418
         // because level 2 indicates the database needs updating and
2419 2419
         // is probably out of sync with the code
2420
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2420
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2421 2421
             throw new RuntimeException(
2422 2422
                 esc_html__(
2423 2423
                     "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.",
@@ -2427,7 +2427,7 @@  discard block
 block discarded – undo
2427 2427
         }
2428 2428
         /** @type WPDB $wpdb */
2429 2429
         global $wpdb;
2430
-        if (! method_exists($wpdb, $wpdb_method)) {
2430
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2431 2431
             throw new DomainException(
2432 2432
                 sprintf(
2433 2433
                     esc_html__(
@@ -2446,7 +2446,7 @@  discard block
 block discarded – undo
2446 2446
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2447 2447
         if (WP_DEBUG) {
2448 2448
             $wpdb->show_errors($old_show_errors_value);
2449
-            if (! empty($wpdb->last_error)) {
2449
+            if ( ! empty($wpdb->last_error)) {
2450 2450
                 throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2451 2451
             }
2452 2452
             if ($result === false) {
@@ -2516,7 +2516,7 @@  discard block
 block discarded – undo
2516 2516
                     // ummmm... you in trouble
2517 2517
                     return $result;
2518 2518
             }
2519
-            if (! empty($error_message)) {
2519
+            if ( ! empty($error_message)) {
2520 2520
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2521 2521
                 trigger_error($error_message);
2522 2522
             }
@@ -2597,11 +2597,11 @@  discard block
 block discarded – undo
2597 2597
      */
2598 2598
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2599 2599
     {
2600
-        return " FROM " . $model_query_info->get_full_join_sql() .
2601
-               $model_query_info->get_where_sql() .
2602
-               $model_query_info->get_group_by_sql() .
2603
-               $model_query_info->get_having_sql() .
2604
-               $model_query_info->get_order_by_sql() .
2600
+        return " FROM ".$model_query_info->get_full_join_sql().
2601
+               $model_query_info->get_where_sql().
2602
+               $model_query_info->get_group_by_sql().
2603
+               $model_query_info->get_having_sql().
2604
+               $model_query_info->get_order_by_sql().
2605 2605
                $model_query_info->get_limit_sql();
2606 2606
     }
2607 2607
 
@@ -2798,12 +2798,12 @@  discard block
 block discarded – undo
2798 2798
         $related_model = $this->get_related_model_obj($model_name);
2799 2799
         // we're just going to use the query params on the related model's normal get_all query,
2800 2800
         // except add a condition to say to match the current mod
2801
-        if (! isset($query_params['default_where_conditions'])) {
2801
+        if ( ! isset($query_params['default_where_conditions'])) {
2802 2802
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2803 2803
         }
2804 2804
         $this_model_name                                                 = $this->get_this_model_name();
2805 2805
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2806
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2806
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2807 2807
         return $related_model->count($query_params, $field_to_count, $distinct);
2808 2808
     }
2809 2809
 
@@ -2824,7 +2824,7 @@  discard block
 block discarded – undo
2824 2824
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2825 2825
     {
2826 2826
         $related_model = $this->get_related_model_obj($model_name);
2827
-        if (! is_array($query_params)) {
2827
+        if ( ! is_array($query_params)) {
2828 2828
             EE_Error::doing_it_wrong(
2829 2829
                 'EEM_Base::sum_related',
2830 2830
                 sprintf(
@@ -2837,12 +2837,12 @@  discard block
 block discarded – undo
2837 2837
         }
2838 2838
         // we're just going to use the query params on the related model's normal get_all query,
2839 2839
         // except add a condition to say to match the current mod
2840
-        if (! isset($query_params['default_where_conditions'])) {
2840
+        if ( ! isset($query_params['default_where_conditions'])) {
2841 2841
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2842 2842
         }
2843 2843
         $this_model_name                                                 = $this->get_this_model_name();
2844 2844
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2845
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2845
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2846 2846
         return $related_model->sum($query_params, $field_to_sum);
2847 2847
     }
2848 2848
 
@@ -2894,7 +2894,7 @@  discard block
 block discarded – undo
2894 2894
                 $field_with_model_name = $field;
2895 2895
             }
2896 2896
         }
2897
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2897
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2898 2898
             throw new EE_Error(
2899 2899
                 sprintf(
2900 2900
                     esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
@@ -3033,14 +3033,14 @@  discard block
 block discarded – undo
3033 3033
                 || $this->get_primary_key_field()
3034 3034
                    instanceof
3035 3035
                    EE_Primary_Key_String_Field)
3036
-            && isset($fields_n_values[ $this->primary_key_name() ])
3036
+            && isset($fields_n_values[$this->primary_key_name()])
3037 3037
         ) {
3038
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3038
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
3039 3039
         }
3040 3040
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3041 3041
             $uniqueness_where_params                              =
3042 3042
                 array_intersect_key($fields_n_values, $unique_index->fields());
3043
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3043
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
3044 3044
         }
3045 3045
         // if there is nothing to base this search on, then we shouldn't find anything
3046 3046
         if (empty($query_params)) {
@@ -3117,16 +3117,16 @@  discard block
 block discarded – undo
3117 3117
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3118 3118
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3119 3119
             if ($prepared_value !== null) {
3120
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3120
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3121 3121
                 $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3122 3122
             }
3123 3123
         }
3124 3124
         if ($table instanceof EE_Secondary_Table && $new_id) {
3125 3125
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3126 3126
             // so add the fk to the main table as a column
3127
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3127
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3128 3128
             $format_for_insertion[]                              =
3129
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3129
+                '%d'; // yes right now we're only allowing these foreign keys to be INTs
3130 3130
         }
3131 3131
 
3132 3132
         // insert the new entry
@@ -3144,7 +3144,7 @@  discard block
 block discarded – undo
3144 3144
             }
3145 3145
             // it's not an auto-increment primary key, so
3146 3146
             // it must have been supplied
3147
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3147
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3148 3148
         }
3149 3149
         // we can't return a  primary key because there is none. instead return
3150 3150
         // a unique string indicating this model
@@ -3166,10 +3166,10 @@  discard block
 block discarded – undo
3166 3166
     {
3167 3167
         $field_name = $field_obj->get_name();
3168 3168
         // if this field doesn't allow nullable, don't allow it
3169
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3170
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3169
+        if ( ! $field_obj->is_nullable() && ! isset($fields_n_values[$field_name])) {
3170
+            $fields_n_values[$field_name] = $field_obj->get_default_value();
3171 3171
         }
3172
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3172
+        $unprepared_value = $fields_n_values[$field_name] ?? null;
3173 3173
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3174 3174
     }
3175 3175
 
@@ -3272,7 +3272,7 @@  discard block
 block discarded – undo
3272 3272
      */
3273 3273
     public function get_table_obj_by_alias($table_alias = '')
3274 3274
     {
3275
-        return $this->_tables[ $table_alias ] ?? null;
3275
+        return $this->_tables[$table_alias] ?? null;
3276 3276
     }
3277 3277
 
3278 3278
 
@@ -3286,7 +3286,7 @@  discard block
 block discarded – undo
3286 3286
         $other_tables = [];
3287 3287
         foreach ($this->_tables as $table_alias => $table) {
3288 3288
             if ($table instanceof EE_Secondary_Table) {
3289
-                $other_tables[ $table_alias ] = $table;
3289
+                $other_tables[$table_alias] = $table;
3290 3290
             }
3291 3291
         }
3292 3292
         return $other_tables;
@@ -3301,7 +3301,7 @@  discard block
 block discarded – undo
3301 3301
      */
3302 3302
     public function _get_fields_for_table($table_alias)
3303 3303
     {
3304
-        return $this->_fields[ $table_alias ];
3304
+        return $this->_fields[$table_alias];
3305 3305
     }
3306 3306
 
3307 3307
 
@@ -3330,7 +3330,7 @@  discard block
 block discarded – undo
3330 3330
                     $query_info_carrier,
3331 3331
                     'group_by'
3332 3332
                 );
3333
-            } elseif (! empty($query_params['group_by'])) {
3333
+            } elseif ( ! empty($query_params['group_by'])) {
3334 3334
                 $this->_extract_related_model_info_from_query_param(
3335 3335
                     $query_params['group_by'],
3336 3336
                     $query_info_carrier,
@@ -3352,7 +3352,7 @@  discard block
 block discarded – undo
3352 3352
                     $query_info_carrier,
3353 3353
                     'order_by'
3354 3354
                 );
3355
-            } elseif (! empty($query_params['order_by'])) {
3355
+            } elseif ( ! empty($query_params['order_by'])) {
3356 3356
                 $this->_extract_related_model_info_from_query_param(
3357 3357
                     $query_params['order_by'],
3358 3358
                     $query_info_carrier,
@@ -3387,7 +3387,7 @@  discard block
 block discarded – undo
3387 3387
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3388 3388
         $query_param_type
3389 3389
     ) {
3390
-        if (! empty($sub_query_params)) {
3390
+        if ( ! empty($sub_query_params)) {
3391 3391
             $sub_query_params = (array) $sub_query_params;
3392 3392
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3393 3393
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3403,7 +3403,7 @@  discard block
 block discarded – undo
3403 3403
                 $query_param_sans_stars =
3404 3404
                     $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3405 3405
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3406
-                    if (! is_array($possibly_array_of_params)) {
3406
+                    if ( ! is_array($possibly_array_of_params)) {
3407 3407
                         throw new EE_Error(
3408 3408
                             sprintf(
3409 3409
                                 esc_html__(
@@ -3429,7 +3429,7 @@  discard block
 block discarded – undo
3429 3429
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3430 3430
                     // indicating that $possible_array_of_params[1] is actually a field name,
3431 3431
                     // from which we should extract query parameters!
3432
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3432
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3433 3433
                         throw new EE_Error(
3434 3434
                             sprintf(
3435 3435
                                 esc_html__(
@@ -3469,8 +3469,8 @@  discard block
 block discarded – undo
3469 3469
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3470 3470
         $query_param_type
3471 3471
     ) {
3472
-        if (! empty($sub_query_params)) {
3473
-            if (! is_array($sub_query_params)) {
3472
+        if ( ! empty($sub_query_params)) {
3473
+            if ( ! is_array($sub_query_params)) {
3474 3474
                 throw new EE_Error(
3475 3475
                     sprintf(
3476 3476
                         esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
@@ -3508,7 +3508,7 @@  discard block
 block discarded – undo
3508 3508
      */
3509 3509
     public function _create_model_query_info_carrier($query_params)
3510 3510
     {
3511
-        if (! is_array($query_params)) {
3511
+        if ( ! is_array($query_params)) {
3512 3512
             EE_Error::doing_it_wrong(
3513 3513
                 'EEM_Base::_create_model_query_info_carrier',
3514 3514
                 sprintf(
@@ -3539,7 +3539,7 @@  discard block
 block discarded – undo
3539 3539
             // only include if related to a cpt where no password has been set
3540 3540
             $query_params[0]['OR*nopassword'] = [
3541 3541
                 $where_param_key_for_password       => '',
3542
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3542
+                $where_param_key_for_password.'*' => ['IS_NULL'],
3543 3543
             ];
3544 3544
         }
3545 3545
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3593,7 +3593,7 @@  discard block
 block discarded – undo
3593 3593
         // set limit
3594 3594
         if (array_key_exists('limit', $query_params)) {
3595 3595
             if (is_array($query_params['limit'])) {
3596
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3596
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3597 3597
                     $e = sprintf(
3598 3598
                         esc_html__(
3599 3599
                             "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)",
@@ -3601,12 +3601,12 @@  discard block
 block discarded – undo
3601 3601
                         ),
3602 3602
                         http_build_query($query_params['limit'])
3603 3603
                     );
3604
-                    throw new EE_Error($e . "|" . $e);
3604
+                    throw new EE_Error($e."|".$e);
3605 3605
                 }
3606 3606
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3607
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3608
-            } elseif (! empty($query_params['limit'])) {
3609
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3607
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3608
+            } elseif ( ! empty($query_params['limit'])) {
3609
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3610 3610
             }
3611 3611
         }
3612 3612
         // set order by
@@ -3638,10 +3638,10 @@  discard block
 block discarded – undo
3638 3638
                 $order_array = [];
3639 3639
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3640 3640
                     $order         = $this->_extract_order($order);
3641
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3641
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3642 3642
                 }
3643
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3644
-            } elseif (! empty($query_params['order_by'])) {
3643
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3644
+            } elseif ( ! empty($query_params['order_by'])) {
3645 3645
                 $this->_extract_related_model_info_from_query_param(
3646 3646
                     $query_params['order_by'],
3647 3647
                     $query_object,
@@ -3652,7 +3652,7 @@  discard block
 block discarded – undo
3652 3652
                     ? $this->_extract_order($query_params['order'])
3653 3653
                     : 'DESC';
3654 3654
                 $query_object->set_order_by_sql(
3655
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3655
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3656 3656
                 );
3657 3657
             }
3658 3658
         }
@@ -3664,7 +3664,7 @@  discard block
 block discarded – undo
3664 3664
         ) {
3665 3665
             $pk_field = $this->get_primary_key_field();
3666 3666
             $order    = $this->_extract_order($query_params['order']);
3667
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3667
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3668 3668
         }
3669 3669
         // set group by
3670 3670
         if (array_key_exists('group_by', $query_params)) {
@@ -3674,10 +3674,10 @@  discard block
 block discarded – undo
3674 3674
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3675 3675
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3676 3676
                 }
3677
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3678
-            } elseif (! empty($query_params['group_by'])) {
3677
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3678
+            } elseif ( ! empty($query_params['group_by'])) {
3679 3679
                 $query_object->set_group_by_sql(
3680
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3680
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3681 3681
                 );
3682 3682
             }
3683 3683
         }
@@ -3687,7 +3687,7 @@  discard block
 block discarded – undo
3687 3687
         }
3688 3688
         // now, just verify they didn't pass anything wack
3689 3689
         foreach ($query_params as $query_key => $query_value) {
3690
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3690
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3691 3691
                 throw new EE_Error(
3692 3692
                     sprintf(
3693 3693
                         esc_html__(
@@ -3792,7 +3792,7 @@  discard block
 block discarded – undo
3792 3792
         $where_query_params = []
3793 3793
     ) {
3794 3794
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3795
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3795
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3796 3796
             throw new EE_Error(
3797 3797
                 sprintf(
3798 3798
                     esc_html__(
@@ -3822,7 +3822,7 @@  discard block
 block discarded – undo
3822 3822
                 // we don't want to add full or even minimum default where conditions from this model, so just continue
3823 3823
                 continue;
3824 3824
             }
3825
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3825
+            $overrides = $this->_override_defaults_or_make_null_friendly(
3826 3826
                 $related_model_universal_where_params,
3827 3827
                 $where_query_params,
3828 3828
                 $related_model,
@@ -3931,19 +3931,19 @@  discard block
 block discarded – undo
3931 3931
     ) {
3932 3932
         $null_friendly_where_conditions = [];
3933 3933
         $none_overridden                = true;
3934
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3934
+        $or_condition_key_for_defaults  = 'OR*'.get_class($model);
3935 3935
         foreach ($default_where_conditions as $key => $val) {
3936
-            if (isset($provided_where_conditions[ $key ])) {
3936
+            if (isset($provided_where_conditions[$key])) {
3937 3937
                 $none_overridden = false;
3938 3938
             } else {
3939
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3939
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3940 3940
             }
3941 3941
         }
3942 3942
         if ($none_overridden && $default_where_conditions) {
3943 3943
             if ($model->has_primary_key_field()) {
3944
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3944
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3945 3945
                                                                                    . "."
3946
-                                                                                   . $model->primary_key_name() ] =
3946
+                                                                                   . $model->primary_key_name()] =
3947 3947
                     ['IS NULL'];
3948 3948
             }/*else{
3949 3949
                 //@todo NO PK, use other defaults
@@ -4054,7 +4054,7 @@  discard block
 block discarded – undo
4054 4054
             foreach ($tables as $table_obj) {
4055 4055
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4056 4056
                                        . $table_obj->get_fully_qualified_pk_column();
4057
-                if (! in_array($qualified_pk_column, $selects)) {
4057
+                if ( ! in_array($qualified_pk_column, $selects)) {
4058 4058
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4059 4059
                 }
4060 4060
             }
@@ -4206,9 +4206,9 @@  discard block
 block discarded – undo
4206 4206
         $query_parameter_type
4207 4207
     ) {
4208 4208
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4209
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4209
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4210 4210
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4211
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4211
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4212 4212
                 if ($possible_join_string === '') {
4213 4213
                     // nothing left to $query_param
4214 4214
                     // we should actually end in a field name, not a model like this!
@@ -4341,7 +4341,7 @@  discard block
 block discarded – undo
4341 4341
     {
4342 4342
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4343 4343
         if ($SQL) {
4344
-            return " WHERE " . $SQL;
4344
+            return " WHERE ".$SQL;
4345 4345
         }
4346 4346
         return '';
4347 4347
     }
@@ -4359,7 +4359,7 @@  discard block
 block discarded – undo
4359 4359
     {
4360 4360
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4361 4361
         if ($SQL) {
4362
-            return " HAVING " . $SQL;
4362
+            return " HAVING ".$SQL;
4363 4363
         }
4364 4364
         return '';
4365 4365
     }
@@ -4413,7 +4413,7 @@  discard block
 block discarded – undo
4413 4413
             } else {
4414 4414
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4415 4415
                 // if it's not a normal field, maybe it's a custom selection?
4416
-                if (! $field_obj) {
4416
+                if ( ! $field_obj) {
4417 4417
                     if ($this->_custom_selections instanceof CustomSelects) {
4418 4418
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4419 4419
                     } else {
@@ -4429,7 +4429,7 @@  discard block
 block discarded – undo
4429 4429
                     }
4430 4430
                 }
4431 4431
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4432
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4432
+                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4433 4433
             }
4434 4434
         }
4435 4435
         return $where_clauses
@@ -4453,7 +4453,7 @@  discard block
 block discarded – undo
4453 4453
                 $field->get_model_name(),
4454 4454
                 $query_param
4455 4455
             );
4456
-            return $table_alias_prefix . $field->get_qualified_column();
4456
+            return $table_alias_prefix.$field->get_qualified_column();
4457 4457
         }
4458 4458
         if (
4459 4459
             $this->_custom_selections instanceof CustomSelects
@@ -4514,7 +4514,7 @@  discard block
 block discarded – undo
4514 4514
             $operator = isset($op_and_value[0])
4515 4515
                 ? $this->_prepare_operator_for_sql($op_and_value[0])
4516 4516
                 : null;
4517
-            if (! $operator) {
4517
+            if ( ! $operator) {
4518 4518
                 $php_array_like_string = [];
4519 4519
                 foreach ($op_and_value as $key => $value) {
4520 4520
                     $php_array_like_string[] = "$key=>$value";
@@ -4534,14 +4534,14 @@  discard block
 block discarded – undo
4534 4534
 
4535 4535
         // check to see if the value is actually another field
4536 4536
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4537
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4537
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4538 4538
         }
4539 4539
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4540 4540
             // in this case, the value should be an array, or at least a comma-separated list
4541 4541
             // it will need to handle a little differently
4542 4542
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4543 4543
             // note: $cleaned_value has already been run through $wpdb->prepare()
4544
-            return $operator . SP . $cleaned_value;
4544
+            return $operator.SP.$cleaned_value;
4545 4545
         }
4546 4546
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4547 4547
             // the value should be an array with count of two.
@@ -4557,7 +4557,7 @@  discard block
 block discarded – undo
4557 4557
                 );
4558 4558
             }
4559 4559
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4560
-            return $operator . SP . $cleaned_value;
4560
+            return $operator.SP.$cleaned_value;
4561 4561
         }
4562 4562
         if (in_array($operator, $this->valid_null_style_operators())) {
4563 4563
             if ($value !== null) {
@@ -4577,10 +4577,10 @@  discard block
 block discarded – undo
4577 4577
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4578 4578
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4579 4579
             // remove other junk. So just treat it as a string.
4580
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4580
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4581 4581
         }
4582
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4583
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4582
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4583
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4584 4584
         }
4585 4585
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4586 4586
             throw new EE_Error(
@@ -4594,7 +4594,7 @@  discard block
 block discarded – undo
4594 4594
                 )
4595 4595
             );
4596 4596
         }
4597
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4597
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4598 4598
             throw new EE_Error(
4599 4599
                 sprintf(
4600 4600
                     esc_html__(
@@ -4633,7 +4633,7 @@  discard block
 block discarded – undo
4633 4633
         foreach ($values as $value) {
4634 4634
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4635 4635
         }
4636
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4636
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4637 4637
     }
4638 4638
 
4639 4639
 
@@ -4671,7 +4671,7 @@  discard block
 block discarded – undo
4671 4671
             $main_table  = $this->_get_main_table();
4672 4672
             $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4673 4673
         }
4674
-        return '(' . implode(',', $prepped) . ')';
4674
+        return '('.implode(',', $prepped).')';
4675 4675
     }
4676 4676
 
4677 4677
 
@@ -4691,7 +4691,7 @@  discard block
 block discarded – undo
4691 4691
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4692 4692
             );
4693 4693
         } //$field_obj should really just be a data type
4694
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4694
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4695 4695
             throw new EE_Error(
4696 4696
                 sprintf(
4697 4697
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4728,14 +4728,14 @@  discard block
 block discarded – undo
4728 4728
             );
4729 4729
         }
4730 4730
         $number_of_parts       = count($query_param_parts);
4731
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4731
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4732 4732
         if ($number_of_parts === 1) {
4733 4733
             $field_name = $last_query_param_part;
4734 4734
             $model_obj  = $this;
4735 4735
         } else {// $number_of_parts >= 2
4736 4736
             // the last part is the column name, and there are only 2parts. therefore...
4737 4737
             $field_name = $last_query_param_part;
4738
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4738
+            $model_obj  = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4739 4739
         }
4740 4740
         try {
4741 4741
             return $model_obj->field_settings_for($field_name);
@@ -4756,7 +4756,7 @@  discard block
 block discarded – undo
4756 4756
     public function _get_qualified_column_for_field($field_name)
4757 4757
     {
4758 4758
         $all_fields = $this->field_settings();
4759
-        $field      = $all_fields[ $field_name ] ?? false;
4759
+        $field      = $all_fields[$field_name] ?? false;
4760 4760
         if ($field) {
4761 4761
             return $field->get_qualified_column();
4762 4762
         }
@@ -4826,12 +4826,12 @@  discard block
 block discarded – undo
4826 4826
      */
4827 4827
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4828 4828
     {
4829
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4829
+        $table_prefix      = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain)
4830 4830
                 ? ''
4831 4831
                 : '__');
4832 4832
         $qualified_columns = [];
4833 4833
         foreach ($this->field_settings() as $field_name => $field) {
4834
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4834
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4835 4835
         }
4836 4836
         return $return_string
4837 4837
             ? implode(', ', $qualified_columns)
@@ -4858,11 +4858,11 @@  discard block
 block discarded – undo
4858 4858
             if ($table_obj instanceof EE_Primary_Table) {
4859 4859
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4860 4860
                     ? $table_obj->get_select_join_limit($limit)
4861
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4861
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4862 4862
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4863 4863
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4864 4864
                     ? $table_obj->get_select_join_limit_join($limit)
4865
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4865
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4866 4866
             }
4867 4867
         }
4868 4868
         return $SQL;
@@ -4933,7 +4933,7 @@  discard block
 block discarded – undo
4933 4933
         foreach ($this->field_settings() as $field_obj) {
4934 4934
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4935 4935
             /** @var $field_obj EE_Model_Field_Base */
4936
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4936
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4937 4937
         }
4938 4938
         return $data_types;
4939 4939
     }
@@ -4948,8 +4948,8 @@  discard block
 block discarded – undo
4948 4948
      */
4949 4949
     public function get_related_model_obj($model_name)
4950 4950
     {
4951
-        $model_classname = "EEM_" . $model_name;
4952
-        if (! class_exists($model_classname)) {
4951
+        $model_classname = "EEM_".$model_name;
4952
+        if ( ! class_exists($model_classname)) {
4953 4953
             throw new EE_Error(
4954 4954
                 sprintf(
4955 4955
                     esc_html__(
@@ -4961,7 +4961,7 @@  discard block
 block discarded – undo
4961 4961
                 )
4962 4962
             );
4963 4963
         }
4964
-        return call_user_func($model_classname . "::instance");
4964
+        return call_user_func($model_classname."::instance");
4965 4965
     }
4966 4966
 
4967 4967
 
@@ -4988,7 +4988,7 @@  discard block
 block discarded – undo
4988 4988
         $belongs_to_relations = [];
4989 4989
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4990 4990
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4991
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4991
+                $belongs_to_relations[$model_name] = $relation_obj;
4992 4992
             }
4993 4993
         }
4994 4994
         return $belongs_to_relations;
@@ -5005,7 +5005,7 @@  discard block
 block discarded – undo
5005 5005
     public function related_settings_for($relation_name)
5006 5006
     {
5007 5007
         $relatedModels = $this->relation_settings();
5008
-        if (! array_key_exists($relation_name, $relatedModels)) {
5008
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
5009 5009
             throw new EE_Error(
5010 5010
                 sprintf(
5011 5011
                     esc_html__(
@@ -5018,7 +5018,7 @@  discard block
 block discarded – undo
5018 5018
                 )
5019 5019
             );
5020 5020
         }
5021
-        return $relatedModels[ $relation_name ];
5021
+        return $relatedModels[$relation_name];
5022 5022
     }
5023 5023
 
5024 5024
 
@@ -5034,7 +5034,7 @@  discard block
 block discarded – undo
5034 5034
     public function field_settings_for($fieldName, $include_db_only_fields = true)
5035 5035
     {
5036 5036
         $fieldSettings = $this->field_settings($include_db_only_fields);
5037
-        if (! array_key_exists($fieldName, $fieldSettings)) {
5037
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
5038 5038
             throw new EE_Error(
5039 5039
                 sprintf(
5040 5040
                     esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
@@ -5043,7 +5043,7 @@  discard block
 block discarded – undo
5043 5043
                 )
5044 5044
             );
5045 5045
         }
5046
-        return $fieldSettings[ $fieldName ];
5046
+        return $fieldSettings[$fieldName];
5047 5047
     }
5048 5048
 
5049 5049
 
@@ -5056,7 +5056,7 @@  discard block
 block discarded – undo
5056 5056
     public function has_field($fieldName)
5057 5057
     {
5058 5058
         $fieldSettings = $this->field_settings(true);
5059
-        if (isset($fieldSettings[ $fieldName ])) {
5059
+        if (isset($fieldSettings[$fieldName])) {
5060 5060
             return true;
5061 5061
         }
5062 5062
         return false;
@@ -5072,7 +5072,7 @@  discard block
 block discarded – undo
5072 5072
     public function has_relation($relation_name)
5073 5073
     {
5074 5074
         $relations = $this->relation_settings();
5075
-        if (isset($relations[ $relation_name ])) {
5075
+        if (isset($relations[$relation_name])) {
5076 5076
             return true;
5077 5077
         }
5078 5078
         return false;
@@ -5108,7 +5108,7 @@  discard block
 block discarded – undo
5108 5108
                     break;
5109 5109
                 }
5110 5110
             }
5111
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5111
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5112 5112
                 throw new EE_Error(
5113 5113
                     sprintf(
5114 5114
                         esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
@@ -5168,17 +5168,17 @@  discard block
 block discarded – undo
5168 5168
      */
5169 5169
     public function get_foreign_key_to($model_name)
5170 5170
     {
5171
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5171
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5172 5172
             foreach ($this->field_settings() as $field) {
5173 5173
                 if (
5174 5174
                     $field instanceof EE_Foreign_Key_Field_Base
5175 5175
                     && in_array($model_name, $field->get_model_names_pointed_to())
5176 5176
                 ) {
5177
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5177
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5178 5178
                     break;
5179 5179
                 }
5180 5180
             }
5181
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5181
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5182 5182
                 throw new EE_Error(
5183 5183
                     sprintf(
5184 5184
                         esc_html__(
@@ -5191,7 +5191,7 @@  discard block
 block discarded – undo
5191 5191
                 );
5192 5192
             }
5193 5193
         }
5194
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5194
+        return $this->_cache_foreign_key_to_fields[$model_name];
5195 5195
     }
5196 5196
 
5197 5197
 
@@ -5207,7 +5207,7 @@  discard block
 block discarded – undo
5207 5207
     {
5208 5208
         $table_alias_sans_model_relation_chain_prefix =
5209 5209
             EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5210
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5210
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5211 5211
     }
5212 5212
 
5213 5213
 
@@ -5225,7 +5225,7 @@  discard block
 block discarded – undo
5225 5225
                 $this->_cached_fields = [];
5226 5226
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5227 5227
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5228
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5228
+                        $this->_cached_fields[$field_name] = $field_obj;
5229 5229
                     }
5230 5230
                 }
5231 5231
             }
@@ -5236,8 +5236,8 @@  discard block
 block discarded – undo
5236 5236
             foreach ($this->_fields as $fields_corresponding_to_table) {
5237 5237
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5238 5238
                     /** @var $field_obj EE_Model_Field_Base */
5239
-                    if (! $field_obj->is_db_only_field()) {
5240
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5239
+                    if ( ! $field_obj->is_db_only_field()) {
5240
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5241 5241
                     }
5242 5242
                 }
5243 5243
             }
@@ -5280,12 +5280,12 @@  discard block
 block discarded – undo
5280 5280
                     $primary_key_field->get_qualified_column(),
5281 5281
                     $primary_key_field->get_table_column()
5282 5282
                 );
5283
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5283
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5284 5284
                     continue;
5285 5285
                 }
5286 5286
             }
5287 5287
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5288
-            if (! $classInstance) {
5288
+            if ( ! $classInstance) {
5289 5289
                 throw new EE_Error(
5290 5290
                     sprintf(
5291 5291
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5300,7 +5300,7 @@  discard block
 block discarded – undo
5300 5300
             $key                      = $has_primary_key
5301 5301
                 ? $classInstance->ID()
5302 5302
                 : $count_if_model_has_no_primary_key++;
5303
-            $array_of_objects[ $key ] = $classInstance;
5303
+            $array_of_objects[$key] = $classInstance;
5304 5304
             // also, for all the relations of type BelongsTo, see if we can cache
5305 5305
             // those related models
5306 5306
             // (we could do this for other relations too, but if there are conditions
@@ -5344,9 +5344,9 @@  discard block
 block discarded – undo
5344 5344
         $results = [];
5345 5345
         if ($this->_custom_selections instanceof CustomSelects) {
5346 5346
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5347
-                if (isset($db_results_row[ $alias ])) {
5348
-                    $results[ $alias ] = $this->convertValueToDataType(
5349
-                        $db_results_row[ $alias ],
5347
+                if (isset($db_results_row[$alias])) {
5348
+                    $results[$alias] = $this->convertValueToDataType(
5349
+                        $db_results_row[$alias],
5350 5350
                         $this->_custom_selections->getDataTypeForAlias($alias)
5351 5351
                     );
5352 5352
                 }
@@ -5391,7 +5391,7 @@  discard block
 block discarded – undo
5391 5391
         $this_model_fields_and_values = [];
5392 5392
         // setup the row using default values;
5393 5393
         foreach ($this->field_settings() as $field_name => $field_obj) {
5394
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5394
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5395 5395
         }
5396 5396
         $className = $this->_get_class_name();
5397 5397
         return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
@@ -5407,20 +5407,20 @@  discard block
 block discarded – undo
5407 5407
      */
5408 5408
     public function instantiate_class_from_array_or_object($cols_n_values)
5409 5409
     {
5410
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5410
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5411 5411
             $cols_n_values = get_object_vars($cols_n_values);
5412 5412
         }
5413 5413
         $primary_key = null;
5414 5414
         // make sure the array only has keys that are fields/columns on this model
5415 5415
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5416
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5417
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5416
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5417
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5418 5418
         }
5419 5419
         $className = $this->_get_class_name();
5420 5420
         // check we actually found results that we can use to build our model object
5421 5421
         // if not, return null
5422 5422
         if ($this->has_primary_key_field()) {
5423
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5423
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5424 5424
                 return null;
5425 5425
             }
5426 5426
         } elseif ($this->unique_indexes()) {
@@ -5432,7 +5432,7 @@  discard block
 block discarded – undo
5432 5432
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5433 5433
         if ($primary_key) {
5434 5434
             $classInstance = $this->get_from_entity_map($primary_key);
5435
-            if (! $classInstance) {
5435
+            if ( ! $classInstance) {
5436 5436
                 $classInstance = EE_Registry::instance()
5437 5437
                                             ->load_class(
5438 5438
                                                 $className,
@@ -5463,7 +5463,7 @@  discard block
 block discarded – undo
5463 5463
      */
5464 5464
     public function get_from_entity_map($id)
5465 5465
     {
5466
-        return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5466
+        return $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] ?? null;
5467 5467
     }
5468 5468
 
5469 5469
 
@@ -5486,7 +5486,7 @@  discard block
 block discarded – undo
5486 5486
     public function add_to_entity_map(EE_Base_Class $object)
5487 5487
     {
5488 5488
         $className = $this->_get_class_name();
5489
-        if (! $object instanceof $className) {
5489
+        if ( ! $object instanceof $className) {
5490 5490
             throw new EE_Error(
5491 5491
                 sprintf(
5492 5492
                     esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
@@ -5498,7 +5498,7 @@  discard block
 block discarded – undo
5498 5498
             );
5499 5499
         }
5500 5500
 
5501
-        if (! $object->ID()) {
5501
+        if ( ! $object->ID()) {
5502 5502
             throw new EE_Error(
5503 5503
                 sprintf(
5504 5504
                     esc_html__(
@@ -5514,7 +5514,7 @@  discard block
 block discarded – undo
5514 5514
         if ($classInstance) {
5515 5515
             return $classInstance;
5516 5516
         }
5517
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5517
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5518 5518
         return $object;
5519 5519
     }
5520 5520
 
@@ -5529,11 +5529,11 @@  discard block
 block discarded – undo
5529 5529
     public function clear_entity_map($id = null)
5530 5530
     {
5531 5531
         if (empty($id)) {
5532
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5532
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = [];
5533 5533
             return true;
5534 5534
         }
5535
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5536
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5535
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5536
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5537 5537
             return true;
5538 5538
         }
5539 5539
         return false;
@@ -5581,18 +5581,18 @@  discard block
 block discarded – undo
5581 5581
             // there is a primary key on this table and its not set. Use defaults for all its columns
5582 5582
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5583 5583
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5584
-                    if (! $field_obj->is_db_only_field()) {
5584
+                    if ( ! $field_obj->is_db_only_field()) {
5585 5585
                         // prepare field as if its coming from db
5586 5586
                         $prepared_value                            =
5587 5587
                             $field_obj->prepare_for_set($field_obj->get_default_value());
5588
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5588
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5589 5589
                     }
5590 5590
                 }
5591 5591
             } else {
5592 5592
                 // the table's rows existed. Use their values
5593 5593
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5594
-                    if (! $field_obj->is_db_only_field()) {
5595
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5594
+                    if ( ! $field_obj->is_db_only_field()) {
5595
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5596 5596
                             $cols_n_values,
5597 5597
                             $field_obj->get_qualified_column(),
5598 5598
                             $field_obj->get_table_column()
@@ -5619,17 +5619,17 @@  discard block
 block discarded – undo
5619 5619
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5620 5620
         // does the field on the model relate to this column retrieved from the db?
5621 5621
         // or is it a db-only field? (not relating to the model)
5622
-        if (isset($cols_n_values[ $qualified_column ])) {
5623
-            $value = $cols_n_values[ $qualified_column ];
5624
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5625
-            $value = $cols_n_values[ $regular_column ];
5626
-        } elseif (! empty($this->foreign_key_aliases)) {
5622
+        if (isset($cols_n_values[$qualified_column])) {
5623
+            $value = $cols_n_values[$qualified_column];
5624
+        } elseif (isset($cols_n_values[$regular_column])) {
5625
+            $value = $cols_n_values[$regular_column];
5626
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5627 5627
             // no PK?  ok check if there is a foreign key alias set for this table
5628 5628
             // then check if that alias exists in the incoming data
5629 5629
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5630 5630
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5631
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5632
-                    $value = $cols_n_values[ $FK_alias ];
5631
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5632
+                    $value = $cols_n_values[$FK_alias];
5633 5633
                     [$pk_class] = explode('.', $PK_column);
5634 5634
                     $pk_model_name = "EEM_{$pk_class}";
5635 5635
                     /** @var EEM_Base $pk_model */
@@ -5673,7 +5673,7 @@  discard block
 block discarded – undo
5673 5673
                     $obj_in_map->clear_cache($relation_name, null, true);
5674 5674
                 }
5675 5675
             }
5676
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5676
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5677 5677
             return $obj_in_map;
5678 5678
         }
5679 5679
         return $this->get_one_by_ID($id);
@@ -5725,7 +5725,7 @@  discard block
 block discarded – undo
5725 5725
      */
5726 5726
     private function _get_class_name()
5727 5727
     {
5728
-        return "EE_" . $this->get_this_model_name();
5728
+        return "EE_".$this->get_this_model_name();
5729 5729
     }
5730 5730
 
5731 5731
 
@@ -5779,7 +5779,7 @@  discard block
 block discarded – undo
5779 5779
     {
5780 5780
         $className = get_class($this);
5781 5781
         $tagName   = "FHEE__{$className}__{$methodName}";
5782
-        if (! has_filter($tagName)) {
5782
+        if ( ! has_filter($tagName)) {
5783 5783
             throw new EE_Error(
5784 5784
                 sprintf(
5785 5785
                     esc_html__(
@@ -5950,7 +5950,7 @@  discard block
 block discarded – undo
5950 5950
         $unique_indexes = [];
5951 5951
         foreach ($this->_indexes as $name => $index) {
5952 5952
             if ($index instanceof EE_Unique_Index) {
5953
-                $unique_indexes [ $name ] = $index;
5953
+                $unique_indexes [$name] = $index;
5954 5954
             }
5955 5955
         }
5956 5956
         return $unique_indexes;
@@ -6014,7 +6014,7 @@  discard block
 block discarded – undo
6014 6014
         $key_vals_in_combined_pk = [];
6015 6015
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6016 6016
         foreach ($key_fields as $key_field_name => $field_obj) {
6017
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6017
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
6018 6018
                 return null;
6019 6019
             }
6020 6020
         }
@@ -6034,7 +6034,7 @@  discard block
 block discarded – undo
6034 6034
     {
6035 6035
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6036 6036
         foreach ($keys_it_should_have as $key) {
6037
-            if (! isset($key_vals[ $key ])) {
6037
+            if ( ! isset($key_vals[$key])) {
6038 6038
                 return false;
6039 6039
             }
6040 6040
         }
@@ -6073,8 +6073,8 @@  discard block
 block discarded – undo
6073 6073
         }
6074 6074
         // even copies obviously won't have the same ID, so remove the primary key
6075 6075
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
6076
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6077
-            unset($attributes_array[ $this->primary_key_name() ]);
6076
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
6077
+            unset($attributes_array[$this->primary_key_name()]);
6078 6078
         }
6079 6079
         if (isset($query_params[0])) {
6080 6080
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -6096,7 +6096,7 @@  discard block
 block discarded – undo
6096 6096
      */
6097 6097
     public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6098 6098
     {
6099
-        if (! is_array($query_params)) {
6099
+        if ( ! is_array($query_params)) {
6100 6100
             EE_Error::doing_it_wrong(
6101 6101
                 'EEM_Base::get_one_copy',
6102 6102
                 sprintf(
@@ -6145,7 +6145,7 @@  discard block
 block discarded – undo
6145 6145
      */
6146 6146
     private function _prepare_operator_for_sql($operator_supplied)
6147 6147
     {
6148
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6148
+        $sql_operator = $this->_valid_operators[$operator_supplied] ?? null;
6149 6149
         if ($sql_operator) {
6150 6150
             return $sql_operator;
6151 6151
         }
@@ -6243,7 +6243,7 @@  discard block
 block discarded – undo
6243 6243
         $objs  = $this->get_all($query_params);
6244 6244
         $names = [];
6245 6245
         foreach ($objs as $obj) {
6246
-            $names[ $obj->ID() ] = $obj->name();
6246
+            $names[$obj->ID()] = $obj->name();
6247 6247
         }
6248 6248
         return $names;
6249 6249
     }
@@ -6264,7 +6264,7 @@  discard block
 block discarded – undo
6264 6264
      */
6265 6265
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6266 6266
     {
6267
-        if (! $this->has_primary_key_field()) {
6267
+        if ( ! $this->has_primary_key_field()) {
6268 6268
             if (WP_DEBUG) {
6269 6269
                 EE_Error::add_error(
6270 6270
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6277,7 +6277,7 @@  discard block
 block discarded – undo
6277 6277
         $IDs = [];
6278 6278
         foreach ($model_objects as $model_object) {
6279 6279
             $id = $model_object->ID();
6280
-            if (! $id) {
6280
+            if ( ! $id) {
6281 6281
                 if ($filter_out_empty_ids) {
6282 6282
                     continue;
6283 6283
                 }
@@ -6326,22 +6326,22 @@  discard block
 block discarded – undo
6326 6326
         EEM_Base::verify_is_valid_cap_context($context);
6327 6327
         // check if we ought to run the restriction generator first
6328 6328
         if (
6329
-            isset($this->_cap_restriction_generators[ $context ])
6330
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6331
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6329
+            isset($this->_cap_restriction_generators[$context])
6330
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6331
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6332 6332
         ) {
6333
-            $this->_cap_restrictions[ $context ] = array_merge(
6334
-                $this->_cap_restrictions[ $context ],
6335
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6333
+            $this->_cap_restrictions[$context] = array_merge(
6334
+                $this->_cap_restrictions[$context],
6335
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6336 6336
             );
6337 6337
         }
6338 6338
         // and make sure we've finalized the construction of each restriction
6339
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6339
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6340 6340
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6341 6341
                 $where_conditions_obj->_finalize_construct($this);
6342 6342
             }
6343 6343
         }
6344
-        return $this->_cap_restrictions[ $context ];
6344
+        return $this->_cap_restrictions[$context];
6345 6345
     }
6346 6346
 
6347 6347
 
@@ -6371,9 +6371,9 @@  discard block
 block discarded – undo
6371 6371
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6372 6372
             if (
6373 6373
                 ! EE_Capabilities::instance()
6374
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6374
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6375 6375
             ) {
6376
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6376
+                $missing_caps[$cap] = $restriction_if_no_cap;
6377 6377
             }
6378 6378
         }
6379 6379
         return $missing_caps;
@@ -6406,8 +6406,8 @@  discard block
 block discarded – undo
6406 6406
     public function cap_action_for_context($context)
6407 6407
     {
6408 6408
         $mapping = $this->cap_contexts_to_cap_action_map();
6409
-        if (isset($mapping[ $context ])) {
6410
-            return $mapping[ $context ];
6409
+        if (isset($mapping[$context])) {
6410
+            return $mapping[$context];
6411 6411
         }
6412 6412
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6413 6413
             return $action;
@@ -6528,7 +6528,7 @@  discard block
 block discarded – undo
6528 6528
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6529 6529
             if (
6530 6530
                 $query_param_key === $logic_query_param_key
6531
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6531
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6532 6532
             ) {
6533 6533
                 return true;
6534 6534
             }
@@ -6586,7 +6586,7 @@  discard block
 block discarded – undo
6586 6586
         if ($password_field instanceof EE_Password_Field) {
6587 6587
             $field_names = $password_field->protectedFields();
6588 6588
             foreach ($field_names as $field_name) {
6589
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6589
+                $fields[$field_name] = $this->field_settings_for($field_name);
6590 6590
             }
6591 6591
         }
6592 6592
         return $fields;
@@ -6612,7 +6612,7 @@  discard block
 block discarded – undo
6612 6612
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6613 6613
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6614 6614
         }
6615
-        if (! is_array($model_obj_or_fields_n_values)) {
6615
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6616 6616
             throw new UnexpectedEntityException(
6617 6617
                 $model_obj_or_fields_n_values,
6618 6618
                 'EE_Base_Class',
@@ -6694,9 +6694,9 @@  discard block
 block discarded – undo
6694 6694
         }
6695 6695
         return (
6696 6696
                $this->model_chain_to_password
6697
-                   ? $this->model_chain_to_password . '.'
6697
+                   ? $this->model_chain_to_password.'.'
6698 6698
                    : ''
6699
-               ) . $password_field_name;
6699
+               ).$password_field_name;
6700 6700
     }
6701 6701
 
6702 6702
 
Please login to merge, or discard this patch.
core/db_models/EEM_System_Status.model.php 2 patches
Indentation   +378 added lines, -378 removed lines patch added patch discarded remove patch
@@ -5,383 +5,383 @@
 block discarded – undo
5 5
  */
6 6
 class EEM_System_Status
7 7
 {
8
-    // private instance of the EEM_System_Status object
9
-    protected static $_instance = null;
10
-
11
-
12
-    /**
13
-     * This function is a singleton method used to instantiate the EEM_Attendee object
14
-     *
15
-     * @return EEM_System_Status
16
-     */
17
-    public static function instance()
18
-    {
19
-        // check if instance of EEM_System_Status already exists
20
-        if (self::$_instance === null) {
21
-            // instantiate EEM_System_Status
22
-            self::$_instance = new self();
23
-        }
24
-        return self::$_instance;
25
-    }
26
-
27
-
28
-    private function __construct()
29
-    {
30
-    }
31
-
32
-
33
-    /**
34
-     * @return array where each key is a function name on this class, and each value is SOMETHING--
35
-     * it might be a value, an array, or an object
36
-     */
37
-    public function get_system_stati()
38
-    {
39
-        return apply_filters(
40
-            'FHEE__EEM_System_Status__get_system_stati',
41
-            [
42
-                'ee_version'            => $this->get_ee_version(),
43
-                'ee_activation_history' => $this->get_ee_activation_history(),
44
-                'ee_config'             => $this->get_ee_config(),
45
-                'ee_migration_history'  => $this->get_ee_migration_history(),
46
-                'active_plugins'        => $this->get_active_plugins(),
47
-                'wp_settings'           => $this->get_wp_settings(),
48
-                'wp_maintenance_mode'   => $this->get_wp_maintenance_mode(),
49
-                'https_enabled'         => $this->get_https_enabled(),
50
-                'logging_enabled'       => $this->get_logging_enabled(),
51
-                'remote_posting'        => $this->get_remote_posting(),
52
-                'php_version'           => $this->php_version(),
53
-                'php.ini_settings'      => $this->get_php_ini_all(),
54
-                'php_info'              => $this->get_php_info(),
55
-            ],
56
-            $this
57
-        );
58
-    }
59
-
60
-
61
-    /**
62
-     * @return string
63
-     */
64
-    public function get_ee_version()
65
-    {
66
-        return espresso_version();
67
-    }
68
-
69
-
70
-    /**
71
-     * @return string
72
-     */
73
-    public function php_version()
74
-    {
75
-        return phpversion();
76
-    }
77
-
78
-
79
-    /**
80
-     * @return array, where each key is a plugin name (lower-cased), values are sub-arrays.
81
-     * Sub-arrays like described in wp function get_plugin_data. Ie,     *
82
-     *  'Name' => 'Plugin Name',
83
-     * 'PluginURI' => 'Plugin URI',
84
-     * 'Version' => 'Version',
85
-     * 'Description' => 'Description',
86
-     * 'Author' => 'Author',
87
-     * 'AuthorURI' => 'Author URI',
88
-     * 'TextDomain' => 'Text Domain',
89
-     * 'DomainPath' => 'Domain Path',
90
-     * 'Network' => 'Network',
91
-     */
92
-    public function get_active_plugins()
93
-    {
94
-        $active_plugins = (array) get_option('active_plugins', []);
95
-        if (is_multisite()) {
96
-            $active_plugins = array_merge($active_plugins, get_site_option('active_sitewide_plugins', []));
97
-        }
98
-        $active_plugins = array_map('strtolower', $active_plugins);
99
-        $plugin_info    = [];
100
-        foreach ($active_plugins as $plugin) {
101
-            $plugin_data = @get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin);
102
-
103
-            $plugin_info[ $plugin ] = $plugin_data;
104
-        }
105
-        return $plugin_info;
106
-    }
107
-
108
-
109
-    /**
110
-     * @return array with keys 'home_url' and 'site_url'
111
-     */
112
-    public function get_wp_settings()
113
-    {
114
-        $wp_memory_int = $this->let_to_num(WP_MEMORY_LIMIT);
115
-        if ($wp_memory_int < 67108864) {
116
-            $wp_memory_to_display = '<mark class="error">';
117
-            $wp_memory_to_display .= sprintf(
118
-                esc_html__(
119
-                    '%s - We recommend setting memory to at least 64MB. See: %s Increasing memory allocated to PHP %s',
120
-                    'event_espresso'
121
-                ),
122
-                WP_MEMORY_LIMIT,
123
-                '<a href="http://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP">',
124
-                '</a>"'
125
-            );
126
-            $wp_memory_to_display .= '</mark>';
127
-        } else {
128
-            $wp_memory_to_display = '<mark class="yes">' . size_format($wp_memory_int) . '</mark>';
129
-        }
130
-        return [
131
-            'name'                => get_bloginfo('name', 'display'),
132
-            'is_multisite'        => is_multisite(),
133
-            'version'             => get_bloginfo('version', 'display'),
134
-            'home_url'            => home_url(),
135
-            'site_url'            => site_url(),
136
-            'WP_DEBUG'            => WP_DEBUG,
137
-            'permalink_structure' => get_option('permalink_structure'),
138
-            'theme'               => wp_get_theme(),
139
-            'gmt_offset'          => get_option('gmt_offset'),
140
-            'timezone_string'     => get_option('timezone_string'),
141
-            'admin_email'         => get_bloginfo('admin_email', 'display'),
142
-            'language'            => get_bloginfo('language', 'display'),
143
-            'wp_max_upload_size'  => size_format(wp_max_upload_size()),
144
-            'wp_memory'           => $wp_memory_to_display,
145
-        ];
146
-    }
147
-
148
-
149
-    /**
150
-     * Gets an array of information about the history of ee versions installed
151
-     *
152
-     * @return array
153
-     */
154
-    public function get_ee_activation_history()
155
-    {
156
-        return get_option('espresso_db_update');
157
-    }
158
-
159
-
160
-    /**
161
-     * Gets an array where keys are ee versions, and their values are arrays indicating all the different times that
162
-     * version was installed
163
-     *
164
-     * @return EE_Data_Migration_Script_Base[]
165
-     */
166
-    public function get_ee_migration_history()
167
-    {
168
-        $options                       = EE_Data_Migration_Manager::instance()->get_all_migration_script_options();
169
-        $presentable_migration_scripts = [];
170
-        foreach ($options as $option_array) {
171
-            $presentable_migration_scripts[ str_replace(
172
-                EE_Data_Migration_Manager::data_migration_script_option_prefix,
173
-                "",
174
-                $option_array['option_name']
175
-            ) ] = maybe_unserialize($option_array['option_value']);
176
-        }
177
-        return $presentable_migration_scripts;
8
+	// private instance of the EEM_System_Status object
9
+	protected static $_instance = null;
10
+
11
+
12
+	/**
13
+	 * This function is a singleton method used to instantiate the EEM_Attendee object
14
+	 *
15
+	 * @return EEM_System_Status
16
+	 */
17
+	public static function instance()
18
+	{
19
+		// check if instance of EEM_System_Status already exists
20
+		if (self::$_instance === null) {
21
+			// instantiate EEM_System_Status
22
+			self::$_instance = new self();
23
+		}
24
+		return self::$_instance;
25
+	}
26
+
27
+
28
+	private function __construct()
29
+	{
30
+	}
31
+
32
+
33
+	/**
34
+	 * @return array where each key is a function name on this class, and each value is SOMETHING--
35
+	 * it might be a value, an array, or an object
36
+	 */
37
+	public function get_system_stati()
38
+	{
39
+		return apply_filters(
40
+			'FHEE__EEM_System_Status__get_system_stati',
41
+			[
42
+				'ee_version'            => $this->get_ee_version(),
43
+				'ee_activation_history' => $this->get_ee_activation_history(),
44
+				'ee_config'             => $this->get_ee_config(),
45
+				'ee_migration_history'  => $this->get_ee_migration_history(),
46
+				'active_plugins'        => $this->get_active_plugins(),
47
+				'wp_settings'           => $this->get_wp_settings(),
48
+				'wp_maintenance_mode'   => $this->get_wp_maintenance_mode(),
49
+				'https_enabled'         => $this->get_https_enabled(),
50
+				'logging_enabled'       => $this->get_logging_enabled(),
51
+				'remote_posting'        => $this->get_remote_posting(),
52
+				'php_version'           => $this->php_version(),
53
+				'php.ini_settings'      => $this->get_php_ini_all(),
54
+				'php_info'              => $this->get_php_info(),
55
+			],
56
+			$this
57
+		);
58
+	}
59
+
60
+
61
+	/**
62
+	 * @return string
63
+	 */
64
+	public function get_ee_version()
65
+	{
66
+		return espresso_version();
67
+	}
68
+
69
+
70
+	/**
71
+	 * @return string
72
+	 */
73
+	public function php_version()
74
+	{
75
+		return phpversion();
76
+	}
77
+
78
+
79
+	/**
80
+	 * @return array, where each key is a plugin name (lower-cased), values are sub-arrays.
81
+	 * Sub-arrays like described in wp function get_plugin_data. Ie,     *
82
+	 *  'Name' => 'Plugin Name',
83
+	 * 'PluginURI' => 'Plugin URI',
84
+	 * 'Version' => 'Version',
85
+	 * 'Description' => 'Description',
86
+	 * 'Author' => 'Author',
87
+	 * 'AuthorURI' => 'Author URI',
88
+	 * 'TextDomain' => 'Text Domain',
89
+	 * 'DomainPath' => 'Domain Path',
90
+	 * 'Network' => 'Network',
91
+	 */
92
+	public function get_active_plugins()
93
+	{
94
+		$active_plugins = (array) get_option('active_plugins', []);
95
+		if (is_multisite()) {
96
+			$active_plugins = array_merge($active_plugins, get_site_option('active_sitewide_plugins', []));
97
+		}
98
+		$active_plugins = array_map('strtolower', $active_plugins);
99
+		$plugin_info    = [];
100
+		foreach ($active_plugins as $plugin) {
101
+			$plugin_data = @get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin);
102
+
103
+			$plugin_info[ $plugin ] = $plugin_data;
104
+		}
105
+		return $plugin_info;
106
+	}
107
+
108
+
109
+	/**
110
+	 * @return array with keys 'home_url' and 'site_url'
111
+	 */
112
+	public function get_wp_settings()
113
+	{
114
+		$wp_memory_int = $this->let_to_num(WP_MEMORY_LIMIT);
115
+		if ($wp_memory_int < 67108864) {
116
+			$wp_memory_to_display = '<mark class="error">';
117
+			$wp_memory_to_display .= sprintf(
118
+				esc_html__(
119
+					'%s - We recommend setting memory to at least 64MB. See: %s Increasing memory allocated to PHP %s',
120
+					'event_espresso'
121
+				),
122
+				WP_MEMORY_LIMIT,
123
+				'<a href="http://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP">',
124
+				'</a>"'
125
+			);
126
+			$wp_memory_to_display .= '</mark>';
127
+		} else {
128
+			$wp_memory_to_display = '<mark class="yes">' . size_format($wp_memory_int) . '</mark>';
129
+		}
130
+		return [
131
+			'name'                => get_bloginfo('name', 'display'),
132
+			'is_multisite'        => is_multisite(),
133
+			'version'             => get_bloginfo('version', 'display'),
134
+			'home_url'            => home_url(),
135
+			'site_url'            => site_url(),
136
+			'WP_DEBUG'            => WP_DEBUG,
137
+			'permalink_structure' => get_option('permalink_structure'),
138
+			'theme'               => wp_get_theme(),
139
+			'gmt_offset'          => get_option('gmt_offset'),
140
+			'timezone_string'     => get_option('timezone_string'),
141
+			'admin_email'         => get_bloginfo('admin_email', 'display'),
142
+			'language'            => get_bloginfo('language', 'display'),
143
+			'wp_max_upload_size'  => size_format(wp_max_upload_size()),
144
+			'wp_memory'           => $wp_memory_to_display,
145
+		];
146
+	}
147
+
148
+
149
+	/**
150
+	 * Gets an array of information about the history of ee versions installed
151
+	 *
152
+	 * @return array
153
+	 */
154
+	public function get_ee_activation_history()
155
+	{
156
+		return get_option('espresso_db_update');
157
+	}
158
+
159
+
160
+	/**
161
+	 * Gets an array where keys are ee versions, and their values are arrays indicating all the different times that
162
+	 * version was installed
163
+	 *
164
+	 * @return EE_Data_Migration_Script_Base[]
165
+	 */
166
+	public function get_ee_migration_history()
167
+	{
168
+		$options                       = EE_Data_Migration_Manager::instance()->get_all_migration_script_options();
169
+		$presentable_migration_scripts = [];
170
+		foreach ($options as $option_array) {
171
+			$presentable_migration_scripts[ str_replace(
172
+				EE_Data_Migration_Manager::data_migration_script_option_prefix,
173
+				"",
174
+				$option_array['option_name']
175
+			) ] = maybe_unserialize($option_array['option_value']);
176
+		}
177
+		return $presentable_migration_scripts;
178 178
 //      return get_option(EE_Data_Migration_Manager::data_migrations_option_name);//EE_Data_Migration_Manager::instance()->get_data_migrations_ran();
179
-    }
180
-
181
-
182
-    /**
183
-     * @return array like EE_Config class
184
-     */
185
-    public function get_ee_config()
186
-    {
187
-        return EE_Config::instance();
188
-    }
189
-
190
-
191
-    /**
192
-     * Gets an array of php setup info, pilfered from http://www.php.net/manual/en/function.phpinfo.php#87463
193
-     *
194
-     * @return array like the output of phpinfo(), but in an array
195
-     */
196
-    public function get_php_info()
197
-    {
198
-        ob_start();
199
-        phpinfo(-1);
200
-
201
-        $pi = preg_replace(
202
-            [
203
-                '#^.*<body>(.*)</body>.*$#ms',
204
-                '#<h2>PHP License</h2>.*$#ms',
205
-                '#<h1>Configuration</h1>#',
206
-                "#\r?\n#",
207
-                "#</(h1|h2|h3|tr)>#",
208
-                '# +<#',
209
-                "#[ \t]+#",
210
-                '#&nbsp;#',
211
-                '#  +#',
212
-                '# class=".*?"#',
213
-                '%&#039;%',
214
-                '#<tr>(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" /></a>'
215
-                . '<h1>PHP Version (.*?)</h1>(?:\n+?)</td></tr>#',
216
-                '#<h1><a href="(?:.*?)\?=(.*?)">PHP Credits</a></h1>#',
217
-                '#<tr>(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)</tr>#',
218
-                "# +#",
219
-                '#<tr>#',
220
-                '#</tr>#',
221
-            ],
222
-            [
223
-                '$1',
224
-                '',
225
-                '',
226
-                '',
227
-                '</$1>' . "\n",
228
-                '<',
229
-                ' ',
230
-                ' ',
231
-                ' ',
232
-                '',
233
-                ' ',
234
-                '<h2>PHP Configuration</h2>' . "\n" . '<tr><td>PHP Version</td><td>$2</td></tr>' .
235
-                "\n" . '<tr><td>PHP Egg</td><td>$1</td></tr>',
236
-                '<tr><td>PHP Credits Egg</td><td>$1</td></tr>',
237
-                '<tr><td>Zend Engine</td><td>$2</td></tr>' . "\n" .
238
-                '<tr><td>Zend Egg</td><td>$1</td></tr>',
239
-                ' ',
240
-                '%S%',
241
-                '%E%',
242
-            ],
243
-            ob_get_clean()
244
-        );
245
-
246
-        $sections = explode('<h2>', strip_tags((string) $pi, '<h2><th><td>'));
247
-        unset($sections[0]);
248
-
249
-        $pi = [];
250
-        foreach ($sections as $section) {
251
-            $n = substr($section, 0, strpos($section, '</h2>'));
252
-            preg_match_all(
253
-                '#%S%(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?%E%#',
254
-                $section,
255
-                $askapache,
256
-                PREG_SET_ORDER
257
-            );
258
-            foreach ($askapache as $m) {
259
-                $m2 = isset($m[2]) ? $m[2] : null;
260
-            }
261
-            $pi[ $n ][ $m[1] ] = (! isset($m[3]) || $m2 == $m[3]) ? $m2 : array_slice($m, 2);
262
-        }
263
-
264
-        return $pi;
265
-    }
266
-
267
-
268
-    /**
269
-     * Checks if site responds ot HTTPS
270
-     *
271
-     * @return boolean
272
-     */
273
-    public function get_https_enabled()
274
-    {
275
-        $home     = str_replace("http://", "https://", home_url());
276
-        $response = wp_remote_get($home);
277
-        if ($response instanceof WP_Error) {
278
-            $error_string = '';
279
-            foreach ($response->errors as $short_name => $description_array) {
280
-                $error_string .= "<b>$short_name</b>: " . implode(", ", $description_array);
281
-            }
282
-            return $error_string;
283
-        }
284
-        return "ok!";
285
-    }
286
-
287
-
288
-    /**
289
-     * Whether or not a .maintenance file is detected
290
-     *
291
-     * @return string descripting wp_maintenance_mode status
292
-     */
293
-    public function get_wp_maintenance_mode()
294
-    {
295
-        $opened = file_exists(ABSPATH . '.maintenance');
296
-        return $opened ? sprintf(
297
-            esc_html__(
298
-                '%s.maintenance file detected.%s Wordpress may have a failed auto-update which could prevent Event Espresso from updating the database correctly.',
299
-                'event_espresso'
300
-            ),
301
-            '<strong>',
302
-            '</strong>'
303
-        ) : esc_html__('.maintenance file not detected. WordPress is not in maintenance mode.', 'event_espresso');
304
-    }
305
-
306
-
307
-    /**
308
-     * Whether or not logging is enabled
309
-     *
310
-     * @return string descripting logging's status
311
-     */
312
-    public function get_logging_enabled()
313
-    {
314
-        $opened = @fopen(EVENT_ESPRESSO_UPLOAD_DIR . '/logs/espresso_log.txt', 'a');
315
-        return $opened
316
-            ? esc_html__('Log Directory is writable', 'event_espresso')
317
-            : sprintf(
318
-                esc_html__('%sLog directory is NOT writable%s', 'event_espresso'),
319
-                '<mark class="error"',
320
-                '</mark>'
321
-            );
322
-    }
323
-
324
-
325
-    /**
326
-     *  Whether curl ro fsock works
327
-     *
328
-     * @return string describing posting's status
329
-     */
330
-    public function get_remote_posting()
331
-    {
332
-        $fsock_works = function_exists('fsockopen');
333
-        $curl_works  = function_exists('curl_init');
334
-        if ($fsock_works && $curl_works) {
335
-            $status = esc_html__('Your server has fsockopen and cURL enabled.', 'event_espresso');
336
-        } elseif ($fsock_works) {
337
-            $status = esc_html__('Your server has fsockopen enabled, cURL is disabled.', 'event_espresso');
338
-        } elseif ($curl_works) {
339
-            $status = esc_html__('Your server has cURL enabled, fsockopen is disabled.', 'event_espresso');
340
-        } else {
341
-            $status = esc_html__(
342
-                          'Your server does not have fsockopen or cURL enabled - PayPal IPN and other scripts which communicate with other servers will not work. Contact your hosting provider.',
343
-                          'event_espresso'
344
-                      ) . '</mark>';
345
-        }
346
-        return $status;
347
-    }
348
-
349
-
350
-    /**
351
-     * Gets all the php.ini settings
352
-     *
353
-     * @return array
354
-     */
355
-    public function get_php_ini_all()
356
-    {
357
-        return ini_get_all();
358
-    }
359
-
360
-
361
-    /**
362
-     * Transforms the php.ini notation for numbers (like '2M') to an integer.
363
-     *
364
-     * @param type $size
365
-     * @return int
366
-     */
367
-    public function let_to_num($size)
368
-    {
369
-        $l   = substr($size, -1);
370
-        $ret = substr($size, 0, -1);
371
-        // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
372
-        switch (strtoupper($l)) {
373
-            case 'P':
374
-                $ret *= 1024;
375
-            case 'T':
376
-                $ret *= 1024;
377
-            case 'G':
378
-                $ret *= 1024;
379
-            case 'M':
380
-                $ret *= 1024;
381
-            case 'K':
382
-                $ret *= 1024;
383
-        }
384
-        // phpcs:enable
385
-        return $ret;
386
-    }
179
+	}
180
+
181
+
182
+	/**
183
+	 * @return array like EE_Config class
184
+	 */
185
+	public function get_ee_config()
186
+	{
187
+		return EE_Config::instance();
188
+	}
189
+
190
+
191
+	/**
192
+	 * Gets an array of php setup info, pilfered from http://www.php.net/manual/en/function.phpinfo.php#87463
193
+	 *
194
+	 * @return array like the output of phpinfo(), but in an array
195
+	 */
196
+	public function get_php_info()
197
+	{
198
+		ob_start();
199
+		phpinfo(-1);
200
+
201
+		$pi = preg_replace(
202
+			[
203
+				'#^.*<body>(.*)</body>.*$#ms',
204
+				'#<h2>PHP License</h2>.*$#ms',
205
+				'#<h1>Configuration</h1>#',
206
+				"#\r?\n#",
207
+				"#</(h1|h2|h3|tr)>#",
208
+				'# +<#',
209
+				"#[ \t]+#",
210
+				'#&nbsp;#',
211
+				'#  +#',
212
+				'# class=".*?"#',
213
+				'%&#039;%',
214
+				'#<tr>(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" /></a>'
215
+				. '<h1>PHP Version (.*?)</h1>(?:\n+?)</td></tr>#',
216
+				'#<h1><a href="(?:.*?)\?=(.*?)">PHP Credits</a></h1>#',
217
+				'#<tr>(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)</tr>#',
218
+				"# +#",
219
+				'#<tr>#',
220
+				'#</tr>#',
221
+			],
222
+			[
223
+				'$1',
224
+				'',
225
+				'',
226
+				'',
227
+				'</$1>' . "\n",
228
+				'<',
229
+				' ',
230
+				' ',
231
+				' ',
232
+				'',
233
+				' ',
234
+				'<h2>PHP Configuration</h2>' . "\n" . '<tr><td>PHP Version</td><td>$2</td></tr>' .
235
+				"\n" . '<tr><td>PHP Egg</td><td>$1</td></tr>',
236
+				'<tr><td>PHP Credits Egg</td><td>$1</td></tr>',
237
+				'<tr><td>Zend Engine</td><td>$2</td></tr>' . "\n" .
238
+				'<tr><td>Zend Egg</td><td>$1</td></tr>',
239
+				' ',
240
+				'%S%',
241
+				'%E%',
242
+			],
243
+			ob_get_clean()
244
+		);
245
+
246
+		$sections = explode('<h2>', strip_tags((string) $pi, '<h2><th><td>'));
247
+		unset($sections[0]);
248
+
249
+		$pi = [];
250
+		foreach ($sections as $section) {
251
+			$n = substr($section, 0, strpos($section, '</h2>'));
252
+			preg_match_all(
253
+				'#%S%(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?%E%#',
254
+				$section,
255
+				$askapache,
256
+				PREG_SET_ORDER
257
+			);
258
+			foreach ($askapache as $m) {
259
+				$m2 = isset($m[2]) ? $m[2] : null;
260
+			}
261
+			$pi[ $n ][ $m[1] ] = (! isset($m[3]) || $m2 == $m[3]) ? $m2 : array_slice($m, 2);
262
+		}
263
+
264
+		return $pi;
265
+	}
266
+
267
+
268
+	/**
269
+	 * Checks if site responds ot HTTPS
270
+	 *
271
+	 * @return boolean
272
+	 */
273
+	public function get_https_enabled()
274
+	{
275
+		$home     = str_replace("http://", "https://", home_url());
276
+		$response = wp_remote_get($home);
277
+		if ($response instanceof WP_Error) {
278
+			$error_string = '';
279
+			foreach ($response->errors as $short_name => $description_array) {
280
+				$error_string .= "<b>$short_name</b>: " . implode(", ", $description_array);
281
+			}
282
+			return $error_string;
283
+		}
284
+		return "ok!";
285
+	}
286
+
287
+
288
+	/**
289
+	 * Whether or not a .maintenance file is detected
290
+	 *
291
+	 * @return string descripting wp_maintenance_mode status
292
+	 */
293
+	public function get_wp_maintenance_mode()
294
+	{
295
+		$opened = file_exists(ABSPATH . '.maintenance');
296
+		return $opened ? sprintf(
297
+			esc_html__(
298
+				'%s.maintenance file detected.%s Wordpress may have a failed auto-update which could prevent Event Espresso from updating the database correctly.',
299
+				'event_espresso'
300
+			),
301
+			'<strong>',
302
+			'</strong>'
303
+		) : esc_html__('.maintenance file not detected. WordPress is not in maintenance mode.', 'event_espresso');
304
+	}
305
+
306
+
307
+	/**
308
+	 * Whether or not logging is enabled
309
+	 *
310
+	 * @return string descripting logging's status
311
+	 */
312
+	public function get_logging_enabled()
313
+	{
314
+		$opened = @fopen(EVENT_ESPRESSO_UPLOAD_DIR . '/logs/espresso_log.txt', 'a');
315
+		return $opened
316
+			? esc_html__('Log Directory is writable', 'event_espresso')
317
+			: sprintf(
318
+				esc_html__('%sLog directory is NOT writable%s', 'event_espresso'),
319
+				'<mark class="error"',
320
+				'</mark>'
321
+			);
322
+	}
323
+
324
+
325
+	/**
326
+	 *  Whether curl ro fsock works
327
+	 *
328
+	 * @return string describing posting's status
329
+	 */
330
+	public function get_remote_posting()
331
+	{
332
+		$fsock_works = function_exists('fsockopen');
333
+		$curl_works  = function_exists('curl_init');
334
+		if ($fsock_works && $curl_works) {
335
+			$status = esc_html__('Your server has fsockopen and cURL enabled.', 'event_espresso');
336
+		} elseif ($fsock_works) {
337
+			$status = esc_html__('Your server has fsockopen enabled, cURL is disabled.', 'event_espresso');
338
+		} elseif ($curl_works) {
339
+			$status = esc_html__('Your server has cURL enabled, fsockopen is disabled.', 'event_espresso');
340
+		} else {
341
+			$status = esc_html__(
342
+						  'Your server does not have fsockopen or cURL enabled - PayPal IPN and other scripts which communicate with other servers will not work. Contact your hosting provider.',
343
+						  'event_espresso'
344
+					  ) . '</mark>';
345
+		}
346
+		return $status;
347
+	}
348
+
349
+
350
+	/**
351
+	 * Gets all the php.ini settings
352
+	 *
353
+	 * @return array
354
+	 */
355
+	public function get_php_ini_all()
356
+	{
357
+		return ini_get_all();
358
+	}
359
+
360
+
361
+	/**
362
+	 * Transforms the php.ini notation for numbers (like '2M') to an integer.
363
+	 *
364
+	 * @param type $size
365
+	 * @return int
366
+	 */
367
+	public function let_to_num($size)
368
+	{
369
+		$l   = substr($size, -1);
370
+		$ret = substr($size, 0, -1);
371
+		// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
372
+		switch (strtoupper($l)) {
373
+			case 'P':
374
+				$ret *= 1024;
375
+			case 'T':
376
+				$ret *= 1024;
377
+			case 'G':
378
+				$ret *= 1024;
379
+			case 'M':
380
+				$ret *= 1024;
381
+			case 'K':
382
+				$ret *= 1024;
383
+		}
384
+		// phpcs:enable
385
+		return $ret;
386
+	}
387 387
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -98,9 +98,9 @@  discard block
 block discarded – undo
98 98
         $active_plugins = array_map('strtolower', $active_plugins);
99 99
         $plugin_info    = [];
100 100
         foreach ($active_plugins as $plugin) {
101
-            $plugin_data = @get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin);
101
+            $plugin_data = @get_plugin_data(WP_PLUGIN_DIR.'/'.$plugin);
102 102
 
103
-            $plugin_info[ $plugin ] = $plugin_data;
103
+            $plugin_info[$plugin] = $plugin_data;
104 104
         }
105 105
         return $plugin_info;
106 106
     }
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
             );
126 126
             $wp_memory_to_display .= '</mark>';
127 127
         } else {
128
-            $wp_memory_to_display = '<mark class="yes">' . size_format($wp_memory_int) . '</mark>';
128
+            $wp_memory_to_display = '<mark class="yes">'.size_format($wp_memory_int).'</mark>';
129 129
         }
130 130
         return [
131 131
             'name'                => get_bloginfo('name', 'display'),
@@ -168,11 +168,11 @@  discard block
 block discarded – undo
168 168
         $options                       = EE_Data_Migration_Manager::instance()->get_all_migration_script_options();
169 169
         $presentable_migration_scripts = [];
170 170
         foreach ($options as $option_array) {
171
-            $presentable_migration_scripts[ str_replace(
171
+            $presentable_migration_scripts[str_replace(
172 172
                 EE_Data_Migration_Manager::data_migration_script_option_prefix,
173 173
                 "",
174 174
                 $option_array['option_name']
175
-            ) ] = maybe_unserialize($option_array['option_value']);
175
+            )] = maybe_unserialize($option_array['option_value']);
176 176
         }
177 177
         return $presentable_migration_scripts;
178 178
 //      return get_option(EE_Data_Migration_Manager::data_migrations_option_name);//EE_Data_Migration_Manager::instance()->get_data_migrations_ran();
@@ -224,17 +224,17 @@  discard block
 block discarded – undo
224 224
                 '',
225 225
                 '',
226 226
                 '',
227
-                '</$1>' . "\n",
227
+                '</$1>'."\n",
228 228
                 '<',
229 229
                 ' ',
230 230
                 ' ',
231 231
                 ' ',
232 232
                 '',
233 233
                 ' ',
234
-                '<h2>PHP Configuration</h2>' . "\n" . '<tr><td>PHP Version</td><td>$2</td></tr>' .
235
-                "\n" . '<tr><td>PHP Egg</td><td>$1</td></tr>',
234
+                '<h2>PHP Configuration</h2>'."\n".'<tr><td>PHP Version</td><td>$2</td></tr>'.
235
+                "\n".'<tr><td>PHP Egg</td><td>$1</td></tr>',
236 236
                 '<tr><td>PHP Credits Egg</td><td>$1</td></tr>',
237
-                '<tr><td>Zend Engine</td><td>$2</td></tr>' . "\n" .
237
+                '<tr><td>Zend Engine</td><td>$2</td></tr>'."\n".
238 238
                 '<tr><td>Zend Egg</td><td>$1</td></tr>',
239 239
                 ' ',
240 240
                 '%S%',
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
             foreach ($askapache as $m) {
259 259
                 $m2 = isset($m[2]) ? $m[2] : null;
260 260
             }
261
-            $pi[ $n ][ $m[1] ] = (! isset($m[3]) || $m2 == $m[3]) ? $m2 : array_slice($m, 2);
261
+            $pi[$n][$m[1]] = ( ! isset($m[3]) || $m2 == $m[3]) ? $m2 : array_slice($m, 2);
262 262
         }
263 263
 
264 264
         return $pi;
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
         if ($response instanceof WP_Error) {
278 278
             $error_string = '';
279 279
             foreach ($response->errors as $short_name => $description_array) {
280
-                $error_string .= "<b>$short_name</b>: " . implode(", ", $description_array);
280
+                $error_string .= "<b>$short_name</b>: ".implode(", ", $description_array);
281 281
             }
282 282
             return $error_string;
283 283
         }
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
      */
293 293
     public function get_wp_maintenance_mode()
294 294
     {
295
-        $opened = file_exists(ABSPATH . '.maintenance');
295
+        $opened = file_exists(ABSPATH.'.maintenance');
296 296
         return $opened ? sprintf(
297 297
             esc_html__(
298 298
                 '%s.maintenance file detected.%s Wordpress may have a failed auto-update which could prevent Event Espresso from updating the database correctly.',
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
      */
312 312
     public function get_logging_enabled()
313 313
     {
314
-        $opened = @fopen(EVENT_ESPRESSO_UPLOAD_DIR . '/logs/espresso_log.txt', 'a');
314
+        $opened = @fopen(EVENT_ESPRESSO_UPLOAD_DIR.'/logs/espresso_log.txt', 'a');
315 315
         return $opened
316 316
             ? esc_html__('Log Directory is writable', 'event_espresso')
317 317
             : sprintf(
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
             $status = esc_html__(
342 342
                           'Your server does not have fsockopen or cURL enabled - PayPal IPN and other scripts which communicate with other servers will not work. Contact your hosting provider.',
343 343
                           'event_espresso'
344
-                      ) . '</mark>';
344
+                      ).'</mark>';
345 345
         }
346 346
         return $status;
347 347
     }
Please login to merge, or discard this patch.
core/db_models/EEM_Datetime.model.php 1 patch
Indentation   +839 added lines, -839 removed lines patch added patch discarded remove patch
@@ -16,843 +16,843 @@
 block discarded – undo
16 16
  */
17 17
 class EEM_Datetime extends EEM_Soft_Delete_Base
18 18
 {
19
-    /**
20
-     * @var EEM_Datetime $_instance
21
-     */
22
-    protected static $_instance;
23
-
24
-
25
-    /**
26
-     * private constructor to prevent direct creation
27
-     *
28
-     * @param string|null $timezone A string representing the timezone we want to set for returned Date Time Strings
29
-     *                              (and any incoming timezone data that gets saved).
30
-     *                              Note this just sends the timezone info to the date time model field objects.
31
-     *                              Default is NULL
32
-     *                              (and will be assumed using the set timezone in the 'timezone_string' wp option)
33
-     * @throws EE_Error
34
-     */
35
-    protected function __construct(?string $timezone = '')
36
-    {
37
-        $this->singular_item           = esc_html__('Datetime', 'event_espresso');
38
-        $this->plural_item             = esc_html__('Datetimes', 'event_espresso');
39
-        $this->_tables                 = [
40
-            'Datetime' => new EE_Primary_Table('esp_datetime', 'DTT_ID'),
41
-        ];
42
-        $this->_fields                 = [
43
-            'Datetime' => [
44
-                'DTT_ID'          => new EE_Primary_Key_Int_Field(
45
-                    'DTT_ID',
46
-                    esc_html__('Datetime ID', 'event_espresso')
47
-                ),
48
-                'EVT_ID'          => new EE_Foreign_Key_Int_Field(
49
-                    'EVT_ID',
50
-                    esc_html__('Event ID', 'event_espresso'),
51
-                    false,
52
-                    0,
53
-                    'Event'
54
-                ),
55
-                'VNU_ID'          => new EE_Foreign_Key_Int_Field(
56
-                    'VNU_ID',
57
-                    __('Venue ID', 'event_espresso'),
58
-                    false,
59
-                    0,
60
-                    'Venue'
61
-                ),
62
-                'DTT_name'        => new EE_Plain_Text_Field(
63
-                    'DTT_name',
64
-                    esc_html__('Datetime Name', 'event_espresso'),
65
-                    false,
66
-                    ''
67
-                ),
68
-                'DTT_description' => new EE_Post_Content_Field(
69
-                    'DTT_description',
70
-                    esc_html__('Description for Datetime', 'event_espresso'),
71
-                    false,
72
-                    ''
73
-                ),
74
-                'DTT_EVT_start'   => new EE_Datetime_Field(
75
-                    'DTT_EVT_start',
76
-                    esc_html__('Start time/date of Event', 'event_espresso'),
77
-                    false,
78
-                    EE_Datetime_Field::now,
79
-                    $timezone
80
-                ),
81
-                'DTT_EVT_end'     => new EE_Datetime_Field(
82
-                    'DTT_EVT_end',
83
-                    esc_html__('End time/date of Event', 'event_espresso'),
84
-                    false,
85
-                    EE_Datetime_Field::now,
86
-                    $timezone
87
-                ),
88
-                'DTT_reg_limit'   => new EE_Infinite_Integer_Field(
89
-                    'DTT_reg_limit',
90
-                    esc_html__('Registration Limit for this time', 'event_espresso'),
91
-                    false,
92
-                    EE_INF
93
-                ),
94
-                'DTT_sold'        => new EE_Integer_Field(
95
-                    'DTT_sold',
96
-                    esc_html__('How many sales for this Datetime that have occurred', 'event_espresso'),
97
-                    false,
98
-                    0
99
-                ),
100
-                'DTT_reserved'    => new EE_Integer_Field(
101
-                    'DTT_reserved',
102
-                    esc_html__('Quantity of tickets reserved, but not yet fully purchased', 'event_espresso'),
103
-                    false,
104
-                    0
105
-                ),
106
-                'DTT_is_primary'  => new EE_Boolean_Field(
107
-                    'DTT_is_primary',
108
-                    esc_html__('Flag indicating datetime is primary one for event', 'event_espresso'),
109
-                    false,
110
-                    false
111
-                ),
112
-                'DTT_order'       => new EE_Integer_Field(
113
-                    'DTT_order',
114
-                    esc_html__('The order in which the Datetime is displayed', 'event_espresso'),
115
-                    false,
116
-                    0
117
-                ),
118
-                'DTT_parent'      => new EE_Integer_Field(
119
-                    'DTT_parent',
120
-                    esc_html__('Indicates what DTT_ID is the parent of this DTT_ID', 'event_espresso'),
121
-                    true,
122
-                    0
123
-                ),
124
-                'DTT_deleted'     => new EE_Trashed_Flag_Field(
125
-                    'DTT_deleted',
126
-                    esc_html__('Flag indicating datetime is archived', 'event_espresso'),
127
-                    false,
128
-                    false
129
-                ),
130
-            ],
131
-        ];
132
-        $this->_model_relations        = [
133
-            'Ticket'          => new EE_HABTM_Relation('Datetime_Ticket'),
134
-            'Event'           => new EE_Belongs_To_Relation(),
135
-            'Checkin'         => new EE_Has_Many_Relation(),
136
-            'Datetime_Ticket' => new EE_Has_Many_Relation(),
137
-            'Venue'           => new EE_Belongs_To_Relation(),
138
-        ];
139
-        $path_to_event_model           = 'Event';
140
-        $this->model_chain_to_password = $path_to_event_model;
141
-        $this->_model_chain_to_wp_user = $path_to_event_model;
142
-        // this model is generally available for reading
143
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ]       =
144
-            new EE_Restriction_Generator_Event_Related_Public(
145
-                $path_to_event_model
146
-            );
147
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
148
-            new EE_Restriction_Generator_Event_Related_Protected(
149
-                $path_to_event_model
150
-            );
151
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
152
-            new EE_Restriction_Generator_Event_Related_Protected(
153
-                $path_to_event_model
154
-            );
155
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
156
-            new EE_Restriction_Generator_Event_Related_Protected(
157
-                $path_to_event_model,
158
-                EEM_Base::caps_edit
159
-            );
160
-        parent::__construct($timezone);
161
-    }
162
-
163
-
164
-    /**
165
-     * create new blank datetime
166
-     *
167
-     * @access public
168
-     * @return EE_Datetime[] array on success, FALSE on fail
169
-     * @throws EE_Error
170
-     * @throws InvalidArgumentException
171
-     * @throws InvalidDataTypeException
172
-     * @throws ReflectionException
173
-     * @throws InvalidInterfaceException
174
-     */
175
-    public function create_new_blank_datetime()
176
-    {
177
-        // makes sure timezone is always set.
178
-        $timezone_string = $this->get_timezone();
179
-        /**
180
-         * Filters the initial start date for the new datetime.
181
-         * Any time included in this value will be overridden later so use additional filters to modify the time.
182
-         *
183
-         * @param int $start_date Unix timestamp representing now + 30 days in seconds.
184
-         * @return int Unix timestamp
185
-         */
186
-        $start_date = apply_filters(
187
-            'FHEE__EEM_Datetime__create_new_blank_datetime__start_date',
188
-            $this->current_time_for_query('DTT_EVT_start', true) + MONTH_IN_SECONDS
189
-        );
190
-        /**
191
-         * Filters the initial end date for the new datetime.
192
-         * Any time included in this value will be overridden later so use additional filters to modify the time.
193
-         *
194
-         * @param int $end_data Unix timestamp representing now + 30 days in seconds.
195
-         * @return int Unix timestamp
196
-         */
197
-        $end_date       = apply_filters(
198
-            'FHEE__EEM_Datetime__create_new_blank_datetime__end_date',
199
-            $this->current_time_for_query('DTT_EVT_end', true) + MONTH_IN_SECONDS
200
-        );
201
-        $blank_datetime = EE_Datetime::new_instance(
202
-            [
203
-                'DTT_EVT_start' => $start_date,
204
-                'DTT_EVT_end'   => $end_date,
205
-                'DTT_order'     => 1,
206
-                'DTT_reg_limit' => EE_INF_IN_DB,
207
-            ],
208
-            $timezone_string
209
-        );
210
-        /**
211
-         * Filters the initial start time and format for the new EE_Datetime instance.
212
-         *
213
-         * @param array $start_time An array having size 2.  First element is the time, second element is the time
214
-         *                          format.
215
-         * @return array
216
-         */
217
-        $start_time = apply_filters(
218
-            'FHEE__EEM_Datetime__create_new_blank_datetime__start_time',
219
-            ['8am', 'ga']
220
-        );
221
-        /**
222
-         * Filters the initial end time and format for the new EE_Datetime instance.
223
-         *
224
-         * @param array $end_time An array having size 2.  First element is the time, second element is the time
225
-         *                        format
226
-         * @return array
227
-         */
228
-        $end_time = apply_filters(
229
-            'FHEE__EEM_Datetime__create_new_blank_datetime__end_time',
230
-            ['5pm', 'ga']
231
-        );
232
-        $this->validateStartAndEndTimeForBlankDate($start_time, $end_time);
233
-        $blank_datetime->set_start_time(
234
-            $this->convert_datetime_for_query(
235
-                'DTT_EVT_start',
236
-                $start_time[0],
237
-                $start_time[1],
238
-                $timezone_string
239
-            )
240
-        );
241
-        $blank_datetime->set_end_time(
242
-            $this->convert_datetime_for_query(
243
-                'DTT_EVT_end',
244
-                $end_time[0],
245
-                $end_time[1],
246
-                $timezone_string
247
-            )
248
-        );
249
-        return [$blank_datetime];
250
-    }
251
-
252
-
253
-    /**
254
-     * Validates whether the start_time and end_time are in the expected format.
255
-     *
256
-     * @param array $start_time
257
-     * @param array $end_time
258
-     * @throws InvalidArgumentException
259
-     * @throws InvalidDataTypeException
260
-     */
261
-    private function validateStartAndEndTimeForBlankDate(array $start_time, array $end_time)
262
-    {
263
-        if (! is_array($start_time)) {
264
-            throw new InvalidDataTypeException('start_time', $start_time, 'array');
265
-        }
266
-        if (! is_array($end_time)) {
267
-            throw new InvalidDataTypeException('end_time', $end_time, 'array');
268
-        }
269
-        if (count($start_time) !== 2) {
270
-            throw new InvalidArgumentException(
271
-                sprintf(
272
-                    'The variable %1$s is expected to be an array with two elements.  The first item in the '
273
-                    . 'array should be a valid time string, the second item in the array should be a valid time format',
274
-                    '$start_time'
275
-                )
276
-            );
277
-        }
278
-        if (count($end_time) !== 2) {
279
-            throw new InvalidArgumentException(
280
-                sprintf(
281
-                    'The variable %1$s is expected to be an array with two elements.  The first item in the '
282
-                    . 'array should be a valid time string, the second item in the array should be a valid time format',
283
-                    '$end_time'
284
-                )
285
-            );
286
-        }
287
-    }
288
-
289
-
290
-    /**
291
-     * get event start date from db
292
-     *
293
-     * @access public
294
-     * @param int $EVT_ID
295
-     * @return EE_Datetime[] array on success, FALSE on fail
296
-     * @throws EE_Error
297
-     * @throws ReflectionException
298
-     */
299
-    public function get_all_event_dates($EVT_ID = 0)
300
-    {
301
-        if (! $EVT_ID) { // on add_new_event event_id gets set to 0
302
-            return $this->create_new_blank_datetime();
303
-        }
304
-        $results = $this->get_datetimes_for_event_ordered_by_DTT_order($EVT_ID);
305
-        if (empty($results)) {
306
-            return $this->create_new_blank_datetime();
307
-        }
308
-        return $results;
309
-    }
310
-
311
-
312
-    /**
313
-     * get all datetimes attached to an event ordered by the DTT_order field
314
-     *
315
-     * @public
316
-     * @param int     $EVT_ID     event id
317
-     * @param boolean $include_expired
318
-     * @param boolean $include_deleted
319
-     * @param int     $limit      If included then limit the count of results by
320
-     *                            the given number
321
-     * @return EE_Datetime[]
322
-     * @throws EE_Error
323
-     */
324
-    public function get_datetimes_for_event_ordered_by_DTT_order(
325
-        int $EVT_ID,
326
-        bool $include_expired = true,
327
-        bool $include_deleted = true,
328
-        $limit = 0
329
-    ) {
330
-        $prev_data_prep_value = $this->prepModelForQuery();
331
-        $where_params         = ['Event.EVT_ID' => absint($EVT_ID)];
332
-        $query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
333
-        $query_params         = $this->addDefaultWhereConditions($query_params);
334
-        $query_params         = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
335
-        return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
336
-    }
337
-
338
-
339
-    /**
340
-     * Gets the datetimes for the event (with the given limit), and orders them by "importance".
341
-     * By importance, we mean that the primary datetimes are most important (DEPRECATED FOR NOW),
342
-     * and then the earlier datetimes are the most important.
343
-     * Maybe we'll want this to take into account datetimes that haven't already passed, but we don't yet.
344
-     *
345
-     * @param int $EVT_ID
346
-     * @param int $limit
347
-     * @return EE_Datetime[]|EE_Base_Class[]
348
-     * @throws EE_Error
349
-     */
350
-    public function get_datetimes_for_event_ordered_by_importance(int $EVT_ID, $limit = 0)
351
-    {
352
-        $query_params[0] = ['Event.EVT_ID' => absint($EVT_ID)];
353
-        $query_params    = $this->addDefaultWhereConditions($query_params);
354
-        $query_params    = $this->addDefaultQueryParams($query_params, $limit);
355
-        return $this->get_all($query_params);
356
-    }
357
-
358
-
359
-    /**
360
-     * @param int     $EVT_ID
361
-     * @param boolean $include_expired
362
-     * @param boolean $include_deleted
363
-     * @return EE_Datetime
364
-     * @throws EE_Error
365
-     */
366
-    public function get_oldest_datetime_for_event(
367
-        int $EVT_ID,
368
-        bool $include_expired = false,
369
-        bool $include_deleted = false
370
-    ) {
371
-        $results = $this->get_datetimes_for_event_ordered_by_start_time(
372
-            $EVT_ID,
373
-            $include_expired,
374
-            $include_deleted,
375
-            1
376
-        );
377
-        if ($results) {
378
-            return array_shift($results);
379
-        }
380
-        return null;
381
-    }
382
-
383
-
384
-    /**
385
-     * Gets the 'primary' datetime for an event.
386
-     *
387
-     * @param int  $EVT_ID
388
-     * @param bool $try_to_exclude_expired
389
-     * @param bool $try_to_exclude_deleted
390
-     * @return EE_Datetime
391
-     * @throws EE_Error
392
-     */
393
-    public function get_primary_datetime_for_event(
394
-        int $EVT_ID,
395
-        bool $try_to_exclude_expired = true,
396
-        bool $try_to_exclude_deleted = true
397
-    ) {
398
-        if ($try_to_exclude_expired) {
399
-            $non_expired = $this->get_oldest_datetime_for_event($EVT_ID, false, false);
400
-            if ($non_expired) {
401
-                return $non_expired;
402
-            }
403
-        }
404
-        if ($try_to_exclude_deleted) {
405
-            $expired_even = $this->get_oldest_datetime_for_event($EVT_ID, true);
406
-            if ($expired_even) {
407
-                return $expired_even;
408
-            }
409
-        }
410
-        return $this->get_oldest_datetime_for_event($EVT_ID, true, true);
411
-    }
412
-
413
-
414
-    /**
415
-     * Gets ALL the datetimes for an event (including trashed ones, for now), ordered
416
-     * only by start date
417
-     *
418
-     * @param int     $EVT_ID
419
-     * @param boolean $include_expired
420
-     * @param boolean $include_deleted
421
-     * @param int     $limit
422
-     * @return EE_Datetime[]
423
-     * @throws EE_Error
424
-     */
425
-    public function get_datetimes_for_event_ordered_by_start_time(
426
-        int $EVT_ID,
427
-        bool $include_expired = true,
428
-        bool $include_deleted = true,
429
-        $limit = 0
430
-    ) {
431
-        $prev_data_prep_value = $this->prepModelForQuery();
432
-        $where_params         = ['Event.EVT_ID' => absint($EVT_ID)];
433
-        $query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
434
-        $query_params         = $this->addDefaultWhereConditions(
435
-            $query_params,
436
-            EEM_Base::default_where_conditions_this_only
437
-        );
438
-        $query_params         = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
439
-        return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
440
-    }
441
-
442
-
443
-    /**
444
-     * Gets ALL the datetimes for an ticket (including trashed ones, for now), ordered
445
-     * only by start date
446
-     *
447
-     * @param int     $TKT_ID
448
-     * @param boolean $include_expired
449
-     * @param boolean $include_deleted
450
-     * @param int     $limit
451
-     * @return EE_Datetime[]
452
-     * @throws EE_Error
453
-     */
454
-    public function get_datetimes_for_ticket_ordered_by_start_time(
455
-        int $TKT_ID,
456
-        bool $include_expired = true,
457
-        bool $include_deleted = true,
458
-        $limit = 0
459
-    ) {
460
-        $prev_data_prep_value = $this->prepModelForQuery();
461
-        $where_params         = ['Ticket.TKT_ID' => absint($TKT_ID)];
462
-        $query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
463
-        $query_params         = $this->addDefaultQueryParams($query_params, $limit);
464
-        return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
465
-    }
466
-
467
-
468
-    /**
469
-     * Gets all the datetimes for a ticket (including trashed ones, for now), ordered by the DTT_order for the
470
-     * datetimes.
471
-     *
472
-     * @param int      $TKT_ID           ID of ticket to retrieve the datetimes for
473
-     * @param boolean  $include_expired  whether to include expired datetimes or not
474
-     * @param boolean  $include_deleted  whether to include trashed datetimes or not.
475
-     * @param int|null $limit            if null, no limit, if int then limit results by
476
-     *                                   that number
477
-     * @return EE_Datetime[]
478
-     * @throws EE_Error
479
-     */
480
-    public function get_datetimes_for_ticket_ordered_by_DTT_order(
481
-        int $TKT_ID,
482
-        bool $include_expired = true,
483
-        bool $include_deleted = true,
484
-        $limit = 0
485
-    ) {
486
-        $prev_data_prep_value = $this->prepModelForQuery();
487
-        $where_params         = ['Ticket.TKT_ID' => absint($TKT_ID)];
488
-        $query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
489
-        $query_params         = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
490
-        return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
491
-    }
492
-
493
-
494
-    /**
495
-     * Gets the most important datetime for a particular event (ie, the primary event usually. But if for some WACK
496
-     * reason it doesn't exist, we consider the earliest event the most important)
497
-     *
498
-     * @param int $EVT_ID
499
-     * @return EE_Datetime
500
-     * @throws EE_Error
501
-     */
502
-    public function get_most_important_datetime_for_event(int $EVT_ID)
503
-    {
504
-        $results = $this->get_datetimes_for_event_ordered_by_importance($EVT_ID, 1);
505
-        if ($results) {
506
-            return array_shift($results);
507
-        }
508
-        return null;
509
-    }
510
-
511
-
512
-    /**
513
-     * This returns a wpdb->results        Array of all DTT month and years matching the incoming query params and
514
-     * grouped by month and year.
515
-     *
516
-     * @param array  $where_params       @see
517
-     *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
518
-     * @param string $evt_active_status  A string representing the evt active status to filter the months by.
519
-     *                                   Can be:
520
-     *                                   - '' = no filter
521
-     *                                   - upcoming = Published events with at least one upcoming datetime.
522
-     *                                   - expired = Events with all datetimes expired.
523
-     *                                   - active = Events that are published and have at least one datetime that
524
-     *                                   starts before now and ends after now.
525
-     *                                   - inactive = Events that are either not published.
526
-     * @return stdClass[]
527
-     * @throws EE_Error
528
-     * @throws InvalidArgumentException
529
-     * @throws InvalidArgumentException
530
-     */
531
-    public function get_dtt_months_and_years(array $where_params, $evt_active_status = '')
532
-    {
533
-        $current_time_for_DTT_EVT_start = $this->current_time_for_query('DTT_EVT_start');
534
-        $current_time_for_DTT_EVT_end   = $this->current_time_for_query('DTT_EVT_end');
535
-        switch ($evt_active_status) {
536
-            case 'upcoming':
537
-                $where_params['Event.status'] = 'publish';
538
-                // if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
539
-                if (isset($where_params['DTT_EVT_start'])) {
540
-                    $where_params['DTT_EVT_start*****'] = $where_params['DTT_EVT_start'];
541
-                }
542
-                $where_params['DTT_EVT_start'] = ['>', $current_time_for_DTT_EVT_start];
543
-                break;
544
-            case 'expired':
545
-                if (isset($where_params['Event.status'])) {
546
-                    unset($where_params['Event.status']);
547
-                }
548
-                // get events to exclude
549
-                $exclude_query[0] = array_merge(
550
-                    $where_params,
551
-                    ['DTT_EVT_end' => ['>', $current_time_for_DTT_EVT_end]]
552
-                );
553
-                // first get all events that have datetimes where its not expired.
554
-                $event_ids = $this->_get_all_wpdb_results(
555
-                    $exclude_query,
556
-                    OBJECT_K,
557
-                    'Datetime.EVT_ID'
558
-                );
559
-                $event_ids = array_keys($event_ids);
560
-                if (isset($where_params['DTT_EVT_end'])) {
561
-                    $where_params['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
562
-                }
563
-                $where_params['DTT_EVT_end']  = ['<', $current_time_for_DTT_EVT_end];
564
-                $where_params['Event.EVT_ID'] = ['NOT IN', $event_ids];
565
-                break;
566
-            case 'active':
567
-                $where_params['Event.status'] = 'publish';
568
-                if (isset($where_params['DTT_EVT_start'])) {
569
-                    $where_params['Datetime.DTT_EVT_start******'] = $where_params['DTT_EVT_start'];
570
-                }
571
-                if (isset($where_params['Datetime.DTT_EVT_end'])) {
572
-                    $where_params['Datetime.DTT_EVT_end*****'] = $where_params['DTT_EVT_end'];
573
-                }
574
-                $where_params['DTT_EVT_start'] = ['<', $current_time_for_DTT_EVT_start];
575
-                $where_params['DTT_EVT_end']   = ['>', $current_time_for_DTT_EVT_end];
576
-                break;
577
-            case 'inactive':
578
-                if (isset($where_params['Event.status'])) {
579
-                    unset($where_params['Event.status']);
580
-                }
581
-                if (isset($where_params['OR'])) {
582
-                    $where_params['AND']['OR'] = $where_params['OR'];
583
-                }
584
-                if (isset($where_params['DTT_EVT_end'])) {
585
-                    $where_params['AND']['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
586
-                    unset($where_params['DTT_EVT_end']);
587
-                }
588
-                if (isset($where_params['DTT_EVT_start'])) {
589
-                    $where_params['AND']['DTT_EVT_start'] = $where_params['DTT_EVT_start'];
590
-                    unset($where_params['DTT_EVT_start']);
591
-                }
592
-                $where_params['AND']['Event.status'] = ['!=', 'publish'];
593
-                break;
594
-        }
595
-        $query_params[0]          = $where_params;
596
-        $query_params['group_by'] = ['dtt_year', 'dtt_month'];
597
-        $query_params             = $this->addOrderByQueryParams($query_params, 'DTT_EVT_start', 'DESC');
598
-
599
-        $query_interval    = EEH_DTT_Helper::get_sql_query_interval_for_offset(
600
-            $this->get_timezone(),
601
-            'DTT_EVT_start'
602
-        );
603
-        $columns_to_select = [
604
-            'dtt_year'      => ['YEAR(' . $query_interval . ')', '%s'],
605
-            'dtt_month'     => ['MONTHNAME(' . $query_interval . ')', '%s'],
606
-            'dtt_month_num' => ['MONTH(' . $query_interval . ')', '%s'],
607
-        ];
608
-        return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
609
-    }
610
-
611
-
612
-    /**
613
-     * Updates the DTT_sold attribute on each datetime (based on the registrations
614
-     * for the tickets for each datetime)
615
-     *
616
-     * @param EE_Base_Class[]|EE_Datetime[] $datetimes
617
-     * @throws EE_Error
618
-     * @throws ReflectionException
619
-     */
620
-    public function update_sold(array $datetimes)
621
-    {
622
-        EE_Error::doing_it_wrong(
623
-            __FUNCTION__,
624
-            esc_html__(
625
-                'Please use \EEM_Ticket::update_tickets_sold() instead which will in turn correctly update both the Ticket AND Datetime counts.',
626
-                'event_espresso'
627
-            ),
628
-            '4.9.32.rc.005'
629
-        );
630
-        foreach ($datetimes as $datetime) {
631
-            $datetime->update_sold();
632
-        }
633
-    }
634
-
635
-
636
-    /**
637
-     *    Gets the total number of tickets available at a particular datetime
638
-     *    (does NOT take into account the datetime's spaces available)
639
-     *
640
-     * @param int   $DTT_ID
641
-     * @param array $query_params
642
-     * @return int of tickets available. If sold out, return less than 1. If infinite, returns EE_INF,  IF there are NO
643
-     *             tickets attached to datetime then FALSE is returned.
644
-     * @throws EE_Error
645
-     * @throws ReflectionException
646
-     */
647
-    public function sum_tickets_currently_available_at_datetime(int $DTT_ID, array $query_params = [])
648
-    {
649
-        $datetime = $this->get_one_by_ID($DTT_ID);
650
-        if ($datetime instanceof EE_Datetime) {
651
-            return $datetime->tickets_remaining($query_params);
652
-        }
653
-        return 0;
654
-    }
655
-
656
-
657
-    /**
658
-     * This returns an array of counts of datetimes in the database for each Datetime status that can be queried.
659
-     *
660
-     * @param array $stati_to_include  If included you can restrict the statuses we return counts for by including the
661
-     *                                 stati you want counts for as values in the array.  An empty array returns counts
662
-     *                                 for all valid stati.
663
-     * @param array $query_params      If included can be used to refine the conditions for returning the count (i.e.
664
-     *                                 only for Datetimes connected to a specific event, or specific ticket.
665
-     * @return array  The value returned is an array indexed by Datetime Status and the values are the counts.  The
666
-     * @throws EE_Error
667
-     *                                 stati used as index keys are: EE_Datetime::active EE_Datetime::upcoming
668
-     *                                 EE_Datetime::expired
669
-     */
670
-    public function get_datetime_counts_by_status(array $stati_to_include = [], array $query_params = [])
671
-    {
672
-        // only accept where conditions for this query.
673
-        $_where            = isset($query_params[0]) ? $query_params[0] : [];
674
-        $status_query_args = [
675
-            EE_Datetime::active   => array_merge(
676
-                $_where,
677
-                ['DTT_EVT_start' => ['<', time()], 'DTT_EVT_end' => ['>', time()]]
678
-            ),
679
-            EE_Datetime::upcoming => array_merge(
680
-                $_where,
681
-                ['DTT_EVT_start' => ['>', time()]]
682
-            ),
683
-            EE_Datetime::expired  => array_merge(
684
-                $_where,
685
-                ['DTT_EVT_end' => ['<', time()]]
686
-            ),
687
-        ];
688
-        if (! empty($stati_to_include)) {
689
-            foreach (array_keys($status_query_args) as $status) {
690
-                if (! in_array($status, $stati_to_include, true)) {
691
-                    unset($status_query_args[ $status ]);
692
-                }
693
-            }
694
-        }
695
-        // loop through and query counts for each stati.
696
-        $status_query_results = [];
697
-        foreach ($status_query_args as $status => $status_where_conditions) {
698
-            $status_query_results[ $status ] = EEM_Datetime::count(
699
-                [$status_where_conditions],
700
-                'DTT_ID',
701
-                true
702
-            );
703
-        }
704
-        return $status_query_results;
705
-    }
706
-
707
-
708
-    /**
709
-     * Returns the specific count for a given Datetime status matching any given query_params.
710
-     *
711
-     * @param string $status Valid string representation for Datetime status requested. (Defaults to Active).
712
-     * @param array  $query_params
713
-     * @return int
714
-     * @throws EE_Error
715
-     */
716
-    public function get_datetime_count_for_status($status = EE_Datetime::active, array $query_params = [])
717
-    {
718
-        $count = $this->get_datetime_counts_by_status([$status], $query_params);
719
-        return ! empty($count[ $status ]) ? $count[ $status ] : 0;
720
-    }
721
-
722
-
723
-    /**
724
-     * @return bool|int
725
-     * @since   5.0.0.p
726
-     */
727
-    private function prepModelForQuery()
728
-    {
729
-        $prev_data_prep_value = $this->get_assumption_concerning_values_already_prepared_by_model_object();
730
-        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
731
-        return $prev_data_prep_value;
732
-    }
733
-
734
-
735
-    /**
736
-     * @param array    $query_params
737
-     * @param bool|int $prev_data_prep_value
738
-     * @return EE_Base_Class[]|EE_Datetime[]
739
-     * @throws EE_Error
740
-     * @since   5.0.0.p
741
-     */
742
-    private function getDatetimesAndRestoreModel(array $query_params, $prev_data_prep_value)
743
-    {
744
-        $result = $this->get_all($query_params);
745
-        $this->assume_values_already_prepared_by_model_object($prev_data_prep_value);
746
-        return $result;
747
-    }
748
-
749
-
750
-    /**
751
-     * @param array  $query_params
752
-     * @param int    $limit
753
-     * @param string $order_by
754
-     * @param string $order
755
-     * @return array
756
-     * @since   5.0.0.p
757
-     */
758
-    private function addDefaultQueryParams(array $query_params, $limit = 0, $order_by = 'DTT_EVT_start', $order = 'ASC')
759
-    {
760
-        $query_params = $this->addOrderByQueryParams($query_params, $order_by, $order);
761
-        $query_params = $this->addLimitQueryParams($query_params, $limit);
762
-        return $query_params;
763
-    }
764
-
765
-
766
-    /**
767
-     * @param array  $query_params
768
-     * @param string $default_where_conditions
769
-     * @return array
770
-     * @since   5.0.0.p
771
-     */
772
-    private function addDefaultWhereConditions(
773
-        array $query_params,
774
-        $default_where_conditions = EEM_Base::default_where_conditions_none
775
-    ) {
776
-        $query_params['default_where_conditions'] = $default_where_conditions;
777
-        return $query_params;
778
-    }
779
-
780
-
781
-    /**
782
-     * @param array $where_params
783
-     * @param bool  $include_deleted
784
-     * @param bool  $include_expired
785
-     * @return array
786
-     * @since   5.0.0.p
787
-     */
788
-    private function addDefaultWhereParams(
789
-        array $where_params,
790
-        bool $include_deleted = true,
791
-        bool $include_expired = true
792
-    ) {
793
-        $where_params = $this->addExpiredWhereParams($where_params, $include_expired);
794
-        $where_params = $this->addDeletedWhereParams($where_params, $include_deleted);
795
-        return $where_params;
796
-    }
797
-
798
-
799
-    /**
800
-     * @param array $where_params
801
-     * @param bool  $include_deleted
802
-     * @return array
803
-     * @since   5.0.0.p
804
-     */
805
-    private function addDeletedWhereParams(array $where_params, bool $include_deleted = true)
806
-    {
807
-        $deleted                     = $include_deleted ? [true, false] : [false];
808
-        $where_params['DTT_deleted'] = ['IN', $deleted];
809
-        return $where_params;
810
-    }
811
-
812
-
813
-    /**
814
-     * @param array $where_params
815
-     * @param bool  $include_expired
816
-     * @return array
817
-     * @since   5.0.0.p
818
-     */
819
-    private function addExpiredWhereParams(array $where_params, bool $include_expired = true)
820
-    {
821
-        if (! $include_expired) {
822
-            $where_params['DTT_EVT_end'] = ['>=', current_time('mysql', true)];
823
-        }
824
-        return $where_params;
825
-    }
826
-
827
-
828
-    /**
829
-     * @param array $query_params
830
-     * @param int   $limit
831
-     * @return array
832
-     * @since   5.0.0.p
833
-     */
834
-    private function addLimitQueryParams(array $query_params, $limit = 0)
835
-    {
836
-        if ($limit) {
837
-            $query_params['limit'] = $limit;
838
-        }
839
-        return $query_params;
840
-    }
841
-
842
-
843
-    /**
844
-     * @param array  $query_params
845
-     * @param string $order_by
846
-     * @param string $order
847
-     * @return array
848
-     * @since   5.0.0.p
849
-     */
850
-    private function addOrderByQueryParams(array $query_params, $order_by = 'DTT_EVT_start', $order = 'ASC')
851
-    {
852
-        $order                    = $order === 'ASC' ? 'ASC' : 'DESC';
853
-        $valid_order_columns      = ['DTT_ID', 'DTT_EVT_start', 'DTT_EVT_end', 'DTT_order'];
854
-        $order_by                 = in_array($order_by, $valid_order_columns, true) ? $order_by : 'DTT_EVT_start';
855
-        $query_params['order_by'] = [$order_by => $order];
856
-        return $query_params;
857
-    }
19
+	/**
20
+	 * @var EEM_Datetime $_instance
21
+	 */
22
+	protected static $_instance;
23
+
24
+
25
+	/**
26
+	 * private constructor to prevent direct creation
27
+	 *
28
+	 * @param string|null $timezone A string representing the timezone we want to set for returned Date Time Strings
29
+	 *                              (and any incoming timezone data that gets saved).
30
+	 *                              Note this just sends the timezone info to the date time model field objects.
31
+	 *                              Default is NULL
32
+	 *                              (and will be assumed using the set timezone in the 'timezone_string' wp option)
33
+	 * @throws EE_Error
34
+	 */
35
+	protected function __construct(?string $timezone = '')
36
+	{
37
+		$this->singular_item           = esc_html__('Datetime', 'event_espresso');
38
+		$this->plural_item             = esc_html__('Datetimes', 'event_espresso');
39
+		$this->_tables                 = [
40
+			'Datetime' => new EE_Primary_Table('esp_datetime', 'DTT_ID'),
41
+		];
42
+		$this->_fields                 = [
43
+			'Datetime' => [
44
+				'DTT_ID'          => new EE_Primary_Key_Int_Field(
45
+					'DTT_ID',
46
+					esc_html__('Datetime ID', 'event_espresso')
47
+				),
48
+				'EVT_ID'          => new EE_Foreign_Key_Int_Field(
49
+					'EVT_ID',
50
+					esc_html__('Event ID', 'event_espresso'),
51
+					false,
52
+					0,
53
+					'Event'
54
+				),
55
+				'VNU_ID'          => new EE_Foreign_Key_Int_Field(
56
+					'VNU_ID',
57
+					__('Venue ID', 'event_espresso'),
58
+					false,
59
+					0,
60
+					'Venue'
61
+				),
62
+				'DTT_name'        => new EE_Plain_Text_Field(
63
+					'DTT_name',
64
+					esc_html__('Datetime Name', 'event_espresso'),
65
+					false,
66
+					''
67
+				),
68
+				'DTT_description' => new EE_Post_Content_Field(
69
+					'DTT_description',
70
+					esc_html__('Description for Datetime', 'event_espresso'),
71
+					false,
72
+					''
73
+				),
74
+				'DTT_EVT_start'   => new EE_Datetime_Field(
75
+					'DTT_EVT_start',
76
+					esc_html__('Start time/date of Event', 'event_espresso'),
77
+					false,
78
+					EE_Datetime_Field::now,
79
+					$timezone
80
+				),
81
+				'DTT_EVT_end'     => new EE_Datetime_Field(
82
+					'DTT_EVT_end',
83
+					esc_html__('End time/date of Event', 'event_espresso'),
84
+					false,
85
+					EE_Datetime_Field::now,
86
+					$timezone
87
+				),
88
+				'DTT_reg_limit'   => new EE_Infinite_Integer_Field(
89
+					'DTT_reg_limit',
90
+					esc_html__('Registration Limit for this time', 'event_espresso'),
91
+					false,
92
+					EE_INF
93
+				),
94
+				'DTT_sold'        => new EE_Integer_Field(
95
+					'DTT_sold',
96
+					esc_html__('How many sales for this Datetime that have occurred', 'event_espresso'),
97
+					false,
98
+					0
99
+				),
100
+				'DTT_reserved'    => new EE_Integer_Field(
101
+					'DTT_reserved',
102
+					esc_html__('Quantity of tickets reserved, but not yet fully purchased', 'event_espresso'),
103
+					false,
104
+					0
105
+				),
106
+				'DTT_is_primary'  => new EE_Boolean_Field(
107
+					'DTT_is_primary',
108
+					esc_html__('Flag indicating datetime is primary one for event', 'event_espresso'),
109
+					false,
110
+					false
111
+				),
112
+				'DTT_order'       => new EE_Integer_Field(
113
+					'DTT_order',
114
+					esc_html__('The order in which the Datetime is displayed', 'event_espresso'),
115
+					false,
116
+					0
117
+				),
118
+				'DTT_parent'      => new EE_Integer_Field(
119
+					'DTT_parent',
120
+					esc_html__('Indicates what DTT_ID is the parent of this DTT_ID', 'event_espresso'),
121
+					true,
122
+					0
123
+				),
124
+				'DTT_deleted'     => new EE_Trashed_Flag_Field(
125
+					'DTT_deleted',
126
+					esc_html__('Flag indicating datetime is archived', 'event_espresso'),
127
+					false,
128
+					false
129
+				),
130
+			],
131
+		];
132
+		$this->_model_relations        = [
133
+			'Ticket'          => new EE_HABTM_Relation('Datetime_Ticket'),
134
+			'Event'           => new EE_Belongs_To_Relation(),
135
+			'Checkin'         => new EE_Has_Many_Relation(),
136
+			'Datetime_Ticket' => new EE_Has_Many_Relation(),
137
+			'Venue'           => new EE_Belongs_To_Relation(),
138
+		];
139
+		$path_to_event_model           = 'Event';
140
+		$this->model_chain_to_password = $path_to_event_model;
141
+		$this->_model_chain_to_wp_user = $path_to_event_model;
142
+		// this model is generally available for reading
143
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ]       =
144
+			new EE_Restriction_Generator_Event_Related_Public(
145
+				$path_to_event_model
146
+			);
147
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
148
+			new EE_Restriction_Generator_Event_Related_Protected(
149
+				$path_to_event_model
150
+			);
151
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
152
+			new EE_Restriction_Generator_Event_Related_Protected(
153
+				$path_to_event_model
154
+			);
155
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
156
+			new EE_Restriction_Generator_Event_Related_Protected(
157
+				$path_to_event_model,
158
+				EEM_Base::caps_edit
159
+			);
160
+		parent::__construct($timezone);
161
+	}
162
+
163
+
164
+	/**
165
+	 * create new blank datetime
166
+	 *
167
+	 * @access public
168
+	 * @return EE_Datetime[] array on success, FALSE on fail
169
+	 * @throws EE_Error
170
+	 * @throws InvalidArgumentException
171
+	 * @throws InvalidDataTypeException
172
+	 * @throws ReflectionException
173
+	 * @throws InvalidInterfaceException
174
+	 */
175
+	public function create_new_blank_datetime()
176
+	{
177
+		// makes sure timezone is always set.
178
+		$timezone_string = $this->get_timezone();
179
+		/**
180
+		 * Filters the initial start date for the new datetime.
181
+		 * Any time included in this value will be overridden later so use additional filters to modify the time.
182
+		 *
183
+		 * @param int $start_date Unix timestamp representing now + 30 days in seconds.
184
+		 * @return int Unix timestamp
185
+		 */
186
+		$start_date = apply_filters(
187
+			'FHEE__EEM_Datetime__create_new_blank_datetime__start_date',
188
+			$this->current_time_for_query('DTT_EVT_start', true) + MONTH_IN_SECONDS
189
+		);
190
+		/**
191
+		 * Filters the initial end date for the new datetime.
192
+		 * Any time included in this value will be overridden later so use additional filters to modify the time.
193
+		 *
194
+		 * @param int $end_data Unix timestamp representing now + 30 days in seconds.
195
+		 * @return int Unix timestamp
196
+		 */
197
+		$end_date       = apply_filters(
198
+			'FHEE__EEM_Datetime__create_new_blank_datetime__end_date',
199
+			$this->current_time_for_query('DTT_EVT_end', true) + MONTH_IN_SECONDS
200
+		);
201
+		$blank_datetime = EE_Datetime::new_instance(
202
+			[
203
+				'DTT_EVT_start' => $start_date,
204
+				'DTT_EVT_end'   => $end_date,
205
+				'DTT_order'     => 1,
206
+				'DTT_reg_limit' => EE_INF_IN_DB,
207
+			],
208
+			$timezone_string
209
+		);
210
+		/**
211
+		 * Filters the initial start time and format for the new EE_Datetime instance.
212
+		 *
213
+		 * @param array $start_time An array having size 2.  First element is the time, second element is the time
214
+		 *                          format.
215
+		 * @return array
216
+		 */
217
+		$start_time = apply_filters(
218
+			'FHEE__EEM_Datetime__create_new_blank_datetime__start_time',
219
+			['8am', 'ga']
220
+		);
221
+		/**
222
+		 * Filters the initial end time and format for the new EE_Datetime instance.
223
+		 *
224
+		 * @param array $end_time An array having size 2.  First element is the time, second element is the time
225
+		 *                        format
226
+		 * @return array
227
+		 */
228
+		$end_time = apply_filters(
229
+			'FHEE__EEM_Datetime__create_new_blank_datetime__end_time',
230
+			['5pm', 'ga']
231
+		);
232
+		$this->validateStartAndEndTimeForBlankDate($start_time, $end_time);
233
+		$blank_datetime->set_start_time(
234
+			$this->convert_datetime_for_query(
235
+				'DTT_EVT_start',
236
+				$start_time[0],
237
+				$start_time[1],
238
+				$timezone_string
239
+			)
240
+		);
241
+		$blank_datetime->set_end_time(
242
+			$this->convert_datetime_for_query(
243
+				'DTT_EVT_end',
244
+				$end_time[0],
245
+				$end_time[1],
246
+				$timezone_string
247
+			)
248
+		);
249
+		return [$blank_datetime];
250
+	}
251
+
252
+
253
+	/**
254
+	 * Validates whether the start_time and end_time are in the expected format.
255
+	 *
256
+	 * @param array $start_time
257
+	 * @param array $end_time
258
+	 * @throws InvalidArgumentException
259
+	 * @throws InvalidDataTypeException
260
+	 */
261
+	private function validateStartAndEndTimeForBlankDate(array $start_time, array $end_time)
262
+	{
263
+		if (! is_array($start_time)) {
264
+			throw new InvalidDataTypeException('start_time', $start_time, 'array');
265
+		}
266
+		if (! is_array($end_time)) {
267
+			throw new InvalidDataTypeException('end_time', $end_time, 'array');
268
+		}
269
+		if (count($start_time) !== 2) {
270
+			throw new InvalidArgumentException(
271
+				sprintf(
272
+					'The variable %1$s is expected to be an array with two elements.  The first item in the '
273
+					. 'array should be a valid time string, the second item in the array should be a valid time format',
274
+					'$start_time'
275
+				)
276
+			);
277
+		}
278
+		if (count($end_time) !== 2) {
279
+			throw new InvalidArgumentException(
280
+				sprintf(
281
+					'The variable %1$s is expected to be an array with two elements.  The first item in the '
282
+					. 'array should be a valid time string, the second item in the array should be a valid time format',
283
+					'$end_time'
284
+				)
285
+			);
286
+		}
287
+	}
288
+
289
+
290
+	/**
291
+	 * get event start date from db
292
+	 *
293
+	 * @access public
294
+	 * @param int $EVT_ID
295
+	 * @return EE_Datetime[] array on success, FALSE on fail
296
+	 * @throws EE_Error
297
+	 * @throws ReflectionException
298
+	 */
299
+	public function get_all_event_dates($EVT_ID = 0)
300
+	{
301
+		if (! $EVT_ID) { // on add_new_event event_id gets set to 0
302
+			return $this->create_new_blank_datetime();
303
+		}
304
+		$results = $this->get_datetimes_for_event_ordered_by_DTT_order($EVT_ID);
305
+		if (empty($results)) {
306
+			return $this->create_new_blank_datetime();
307
+		}
308
+		return $results;
309
+	}
310
+
311
+
312
+	/**
313
+	 * get all datetimes attached to an event ordered by the DTT_order field
314
+	 *
315
+	 * @public
316
+	 * @param int     $EVT_ID     event id
317
+	 * @param boolean $include_expired
318
+	 * @param boolean $include_deleted
319
+	 * @param int     $limit      If included then limit the count of results by
320
+	 *                            the given number
321
+	 * @return EE_Datetime[]
322
+	 * @throws EE_Error
323
+	 */
324
+	public function get_datetimes_for_event_ordered_by_DTT_order(
325
+		int $EVT_ID,
326
+		bool $include_expired = true,
327
+		bool $include_deleted = true,
328
+		$limit = 0
329
+	) {
330
+		$prev_data_prep_value = $this->prepModelForQuery();
331
+		$where_params         = ['Event.EVT_ID' => absint($EVT_ID)];
332
+		$query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
333
+		$query_params         = $this->addDefaultWhereConditions($query_params);
334
+		$query_params         = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
335
+		return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
336
+	}
337
+
338
+
339
+	/**
340
+	 * Gets the datetimes for the event (with the given limit), and orders them by "importance".
341
+	 * By importance, we mean that the primary datetimes are most important (DEPRECATED FOR NOW),
342
+	 * and then the earlier datetimes are the most important.
343
+	 * Maybe we'll want this to take into account datetimes that haven't already passed, but we don't yet.
344
+	 *
345
+	 * @param int $EVT_ID
346
+	 * @param int $limit
347
+	 * @return EE_Datetime[]|EE_Base_Class[]
348
+	 * @throws EE_Error
349
+	 */
350
+	public function get_datetimes_for_event_ordered_by_importance(int $EVT_ID, $limit = 0)
351
+	{
352
+		$query_params[0] = ['Event.EVT_ID' => absint($EVT_ID)];
353
+		$query_params    = $this->addDefaultWhereConditions($query_params);
354
+		$query_params    = $this->addDefaultQueryParams($query_params, $limit);
355
+		return $this->get_all($query_params);
356
+	}
357
+
358
+
359
+	/**
360
+	 * @param int     $EVT_ID
361
+	 * @param boolean $include_expired
362
+	 * @param boolean $include_deleted
363
+	 * @return EE_Datetime
364
+	 * @throws EE_Error
365
+	 */
366
+	public function get_oldest_datetime_for_event(
367
+		int $EVT_ID,
368
+		bool $include_expired = false,
369
+		bool $include_deleted = false
370
+	) {
371
+		$results = $this->get_datetimes_for_event_ordered_by_start_time(
372
+			$EVT_ID,
373
+			$include_expired,
374
+			$include_deleted,
375
+			1
376
+		);
377
+		if ($results) {
378
+			return array_shift($results);
379
+		}
380
+		return null;
381
+	}
382
+
383
+
384
+	/**
385
+	 * Gets the 'primary' datetime for an event.
386
+	 *
387
+	 * @param int  $EVT_ID
388
+	 * @param bool $try_to_exclude_expired
389
+	 * @param bool $try_to_exclude_deleted
390
+	 * @return EE_Datetime
391
+	 * @throws EE_Error
392
+	 */
393
+	public function get_primary_datetime_for_event(
394
+		int $EVT_ID,
395
+		bool $try_to_exclude_expired = true,
396
+		bool $try_to_exclude_deleted = true
397
+	) {
398
+		if ($try_to_exclude_expired) {
399
+			$non_expired = $this->get_oldest_datetime_for_event($EVT_ID, false, false);
400
+			if ($non_expired) {
401
+				return $non_expired;
402
+			}
403
+		}
404
+		if ($try_to_exclude_deleted) {
405
+			$expired_even = $this->get_oldest_datetime_for_event($EVT_ID, true);
406
+			if ($expired_even) {
407
+				return $expired_even;
408
+			}
409
+		}
410
+		return $this->get_oldest_datetime_for_event($EVT_ID, true, true);
411
+	}
412
+
413
+
414
+	/**
415
+	 * Gets ALL the datetimes for an event (including trashed ones, for now), ordered
416
+	 * only by start date
417
+	 *
418
+	 * @param int     $EVT_ID
419
+	 * @param boolean $include_expired
420
+	 * @param boolean $include_deleted
421
+	 * @param int     $limit
422
+	 * @return EE_Datetime[]
423
+	 * @throws EE_Error
424
+	 */
425
+	public function get_datetimes_for_event_ordered_by_start_time(
426
+		int $EVT_ID,
427
+		bool $include_expired = true,
428
+		bool $include_deleted = true,
429
+		$limit = 0
430
+	) {
431
+		$prev_data_prep_value = $this->prepModelForQuery();
432
+		$where_params         = ['Event.EVT_ID' => absint($EVT_ID)];
433
+		$query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
434
+		$query_params         = $this->addDefaultWhereConditions(
435
+			$query_params,
436
+			EEM_Base::default_where_conditions_this_only
437
+		);
438
+		$query_params         = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
439
+		return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
440
+	}
441
+
442
+
443
+	/**
444
+	 * Gets ALL the datetimes for an ticket (including trashed ones, for now), ordered
445
+	 * only by start date
446
+	 *
447
+	 * @param int     $TKT_ID
448
+	 * @param boolean $include_expired
449
+	 * @param boolean $include_deleted
450
+	 * @param int     $limit
451
+	 * @return EE_Datetime[]
452
+	 * @throws EE_Error
453
+	 */
454
+	public function get_datetimes_for_ticket_ordered_by_start_time(
455
+		int $TKT_ID,
456
+		bool $include_expired = true,
457
+		bool $include_deleted = true,
458
+		$limit = 0
459
+	) {
460
+		$prev_data_prep_value = $this->prepModelForQuery();
461
+		$where_params         = ['Ticket.TKT_ID' => absint($TKT_ID)];
462
+		$query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
463
+		$query_params         = $this->addDefaultQueryParams($query_params, $limit);
464
+		return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
465
+	}
466
+
467
+
468
+	/**
469
+	 * Gets all the datetimes for a ticket (including trashed ones, for now), ordered by the DTT_order for the
470
+	 * datetimes.
471
+	 *
472
+	 * @param int      $TKT_ID           ID of ticket to retrieve the datetimes for
473
+	 * @param boolean  $include_expired  whether to include expired datetimes or not
474
+	 * @param boolean  $include_deleted  whether to include trashed datetimes or not.
475
+	 * @param int|null $limit            if null, no limit, if int then limit results by
476
+	 *                                   that number
477
+	 * @return EE_Datetime[]
478
+	 * @throws EE_Error
479
+	 */
480
+	public function get_datetimes_for_ticket_ordered_by_DTT_order(
481
+		int $TKT_ID,
482
+		bool $include_expired = true,
483
+		bool $include_deleted = true,
484
+		$limit = 0
485
+	) {
486
+		$prev_data_prep_value = $this->prepModelForQuery();
487
+		$where_params         = ['Ticket.TKT_ID' => absint($TKT_ID)];
488
+		$query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
489
+		$query_params         = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
490
+		return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
491
+	}
492
+
493
+
494
+	/**
495
+	 * Gets the most important datetime for a particular event (ie, the primary event usually. But if for some WACK
496
+	 * reason it doesn't exist, we consider the earliest event the most important)
497
+	 *
498
+	 * @param int $EVT_ID
499
+	 * @return EE_Datetime
500
+	 * @throws EE_Error
501
+	 */
502
+	public function get_most_important_datetime_for_event(int $EVT_ID)
503
+	{
504
+		$results = $this->get_datetimes_for_event_ordered_by_importance($EVT_ID, 1);
505
+		if ($results) {
506
+			return array_shift($results);
507
+		}
508
+		return null;
509
+	}
510
+
511
+
512
+	/**
513
+	 * This returns a wpdb->results        Array of all DTT month and years matching the incoming query params and
514
+	 * grouped by month and year.
515
+	 *
516
+	 * @param array  $where_params       @see
517
+	 *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
518
+	 * @param string $evt_active_status  A string representing the evt active status to filter the months by.
519
+	 *                                   Can be:
520
+	 *                                   - '' = no filter
521
+	 *                                   - upcoming = Published events with at least one upcoming datetime.
522
+	 *                                   - expired = Events with all datetimes expired.
523
+	 *                                   - active = Events that are published and have at least one datetime that
524
+	 *                                   starts before now and ends after now.
525
+	 *                                   - inactive = Events that are either not published.
526
+	 * @return stdClass[]
527
+	 * @throws EE_Error
528
+	 * @throws InvalidArgumentException
529
+	 * @throws InvalidArgumentException
530
+	 */
531
+	public function get_dtt_months_and_years(array $where_params, $evt_active_status = '')
532
+	{
533
+		$current_time_for_DTT_EVT_start = $this->current_time_for_query('DTT_EVT_start');
534
+		$current_time_for_DTT_EVT_end   = $this->current_time_for_query('DTT_EVT_end');
535
+		switch ($evt_active_status) {
536
+			case 'upcoming':
537
+				$where_params['Event.status'] = 'publish';
538
+				// if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
539
+				if (isset($where_params['DTT_EVT_start'])) {
540
+					$where_params['DTT_EVT_start*****'] = $where_params['DTT_EVT_start'];
541
+				}
542
+				$where_params['DTT_EVT_start'] = ['>', $current_time_for_DTT_EVT_start];
543
+				break;
544
+			case 'expired':
545
+				if (isset($where_params['Event.status'])) {
546
+					unset($where_params['Event.status']);
547
+				}
548
+				// get events to exclude
549
+				$exclude_query[0] = array_merge(
550
+					$where_params,
551
+					['DTT_EVT_end' => ['>', $current_time_for_DTT_EVT_end]]
552
+				);
553
+				// first get all events that have datetimes where its not expired.
554
+				$event_ids = $this->_get_all_wpdb_results(
555
+					$exclude_query,
556
+					OBJECT_K,
557
+					'Datetime.EVT_ID'
558
+				);
559
+				$event_ids = array_keys($event_ids);
560
+				if (isset($where_params['DTT_EVT_end'])) {
561
+					$where_params['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
562
+				}
563
+				$where_params['DTT_EVT_end']  = ['<', $current_time_for_DTT_EVT_end];
564
+				$where_params['Event.EVT_ID'] = ['NOT IN', $event_ids];
565
+				break;
566
+			case 'active':
567
+				$where_params['Event.status'] = 'publish';
568
+				if (isset($where_params['DTT_EVT_start'])) {
569
+					$where_params['Datetime.DTT_EVT_start******'] = $where_params['DTT_EVT_start'];
570
+				}
571
+				if (isset($where_params['Datetime.DTT_EVT_end'])) {
572
+					$where_params['Datetime.DTT_EVT_end*****'] = $where_params['DTT_EVT_end'];
573
+				}
574
+				$where_params['DTT_EVT_start'] = ['<', $current_time_for_DTT_EVT_start];
575
+				$where_params['DTT_EVT_end']   = ['>', $current_time_for_DTT_EVT_end];
576
+				break;
577
+			case 'inactive':
578
+				if (isset($where_params['Event.status'])) {
579
+					unset($where_params['Event.status']);
580
+				}
581
+				if (isset($where_params['OR'])) {
582
+					$where_params['AND']['OR'] = $where_params['OR'];
583
+				}
584
+				if (isset($where_params['DTT_EVT_end'])) {
585
+					$where_params['AND']['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
586
+					unset($where_params['DTT_EVT_end']);
587
+				}
588
+				if (isset($where_params['DTT_EVT_start'])) {
589
+					$where_params['AND']['DTT_EVT_start'] = $where_params['DTT_EVT_start'];
590
+					unset($where_params['DTT_EVT_start']);
591
+				}
592
+				$where_params['AND']['Event.status'] = ['!=', 'publish'];
593
+				break;
594
+		}
595
+		$query_params[0]          = $where_params;
596
+		$query_params['group_by'] = ['dtt_year', 'dtt_month'];
597
+		$query_params             = $this->addOrderByQueryParams($query_params, 'DTT_EVT_start', 'DESC');
598
+
599
+		$query_interval    = EEH_DTT_Helper::get_sql_query_interval_for_offset(
600
+			$this->get_timezone(),
601
+			'DTT_EVT_start'
602
+		);
603
+		$columns_to_select = [
604
+			'dtt_year'      => ['YEAR(' . $query_interval . ')', '%s'],
605
+			'dtt_month'     => ['MONTHNAME(' . $query_interval . ')', '%s'],
606
+			'dtt_month_num' => ['MONTH(' . $query_interval . ')', '%s'],
607
+		];
608
+		return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
609
+	}
610
+
611
+
612
+	/**
613
+	 * Updates the DTT_sold attribute on each datetime (based on the registrations
614
+	 * for the tickets for each datetime)
615
+	 *
616
+	 * @param EE_Base_Class[]|EE_Datetime[] $datetimes
617
+	 * @throws EE_Error
618
+	 * @throws ReflectionException
619
+	 */
620
+	public function update_sold(array $datetimes)
621
+	{
622
+		EE_Error::doing_it_wrong(
623
+			__FUNCTION__,
624
+			esc_html__(
625
+				'Please use \EEM_Ticket::update_tickets_sold() instead which will in turn correctly update both the Ticket AND Datetime counts.',
626
+				'event_espresso'
627
+			),
628
+			'4.9.32.rc.005'
629
+		);
630
+		foreach ($datetimes as $datetime) {
631
+			$datetime->update_sold();
632
+		}
633
+	}
634
+
635
+
636
+	/**
637
+	 *    Gets the total number of tickets available at a particular datetime
638
+	 *    (does NOT take into account the datetime's spaces available)
639
+	 *
640
+	 * @param int   $DTT_ID
641
+	 * @param array $query_params
642
+	 * @return int of tickets available. If sold out, return less than 1. If infinite, returns EE_INF,  IF there are NO
643
+	 *             tickets attached to datetime then FALSE is returned.
644
+	 * @throws EE_Error
645
+	 * @throws ReflectionException
646
+	 */
647
+	public function sum_tickets_currently_available_at_datetime(int $DTT_ID, array $query_params = [])
648
+	{
649
+		$datetime = $this->get_one_by_ID($DTT_ID);
650
+		if ($datetime instanceof EE_Datetime) {
651
+			return $datetime->tickets_remaining($query_params);
652
+		}
653
+		return 0;
654
+	}
655
+
656
+
657
+	/**
658
+	 * This returns an array of counts of datetimes in the database for each Datetime status that can be queried.
659
+	 *
660
+	 * @param array $stati_to_include  If included you can restrict the statuses we return counts for by including the
661
+	 *                                 stati you want counts for as values in the array.  An empty array returns counts
662
+	 *                                 for all valid stati.
663
+	 * @param array $query_params      If included can be used to refine the conditions for returning the count (i.e.
664
+	 *                                 only for Datetimes connected to a specific event, or specific ticket.
665
+	 * @return array  The value returned is an array indexed by Datetime Status and the values are the counts.  The
666
+	 * @throws EE_Error
667
+	 *                                 stati used as index keys are: EE_Datetime::active EE_Datetime::upcoming
668
+	 *                                 EE_Datetime::expired
669
+	 */
670
+	public function get_datetime_counts_by_status(array $stati_to_include = [], array $query_params = [])
671
+	{
672
+		// only accept where conditions for this query.
673
+		$_where            = isset($query_params[0]) ? $query_params[0] : [];
674
+		$status_query_args = [
675
+			EE_Datetime::active   => array_merge(
676
+				$_where,
677
+				['DTT_EVT_start' => ['<', time()], 'DTT_EVT_end' => ['>', time()]]
678
+			),
679
+			EE_Datetime::upcoming => array_merge(
680
+				$_where,
681
+				['DTT_EVT_start' => ['>', time()]]
682
+			),
683
+			EE_Datetime::expired  => array_merge(
684
+				$_where,
685
+				['DTT_EVT_end' => ['<', time()]]
686
+			),
687
+		];
688
+		if (! empty($stati_to_include)) {
689
+			foreach (array_keys($status_query_args) as $status) {
690
+				if (! in_array($status, $stati_to_include, true)) {
691
+					unset($status_query_args[ $status ]);
692
+				}
693
+			}
694
+		}
695
+		// loop through and query counts for each stati.
696
+		$status_query_results = [];
697
+		foreach ($status_query_args as $status => $status_where_conditions) {
698
+			$status_query_results[ $status ] = EEM_Datetime::count(
699
+				[$status_where_conditions],
700
+				'DTT_ID',
701
+				true
702
+			);
703
+		}
704
+		return $status_query_results;
705
+	}
706
+
707
+
708
+	/**
709
+	 * Returns the specific count for a given Datetime status matching any given query_params.
710
+	 *
711
+	 * @param string $status Valid string representation for Datetime status requested. (Defaults to Active).
712
+	 * @param array  $query_params
713
+	 * @return int
714
+	 * @throws EE_Error
715
+	 */
716
+	public function get_datetime_count_for_status($status = EE_Datetime::active, array $query_params = [])
717
+	{
718
+		$count = $this->get_datetime_counts_by_status([$status], $query_params);
719
+		return ! empty($count[ $status ]) ? $count[ $status ] : 0;
720
+	}
721
+
722
+
723
+	/**
724
+	 * @return bool|int
725
+	 * @since   5.0.0.p
726
+	 */
727
+	private function prepModelForQuery()
728
+	{
729
+		$prev_data_prep_value = $this->get_assumption_concerning_values_already_prepared_by_model_object();
730
+		$this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
731
+		return $prev_data_prep_value;
732
+	}
733
+
734
+
735
+	/**
736
+	 * @param array    $query_params
737
+	 * @param bool|int $prev_data_prep_value
738
+	 * @return EE_Base_Class[]|EE_Datetime[]
739
+	 * @throws EE_Error
740
+	 * @since   5.0.0.p
741
+	 */
742
+	private function getDatetimesAndRestoreModel(array $query_params, $prev_data_prep_value)
743
+	{
744
+		$result = $this->get_all($query_params);
745
+		$this->assume_values_already_prepared_by_model_object($prev_data_prep_value);
746
+		return $result;
747
+	}
748
+
749
+
750
+	/**
751
+	 * @param array  $query_params
752
+	 * @param int    $limit
753
+	 * @param string $order_by
754
+	 * @param string $order
755
+	 * @return array
756
+	 * @since   5.0.0.p
757
+	 */
758
+	private function addDefaultQueryParams(array $query_params, $limit = 0, $order_by = 'DTT_EVT_start', $order = 'ASC')
759
+	{
760
+		$query_params = $this->addOrderByQueryParams($query_params, $order_by, $order);
761
+		$query_params = $this->addLimitQueryParams($query_params, $limit);
762
+		return $query_params;
763
+	}
764
+
765
+
766
+	/**
767
+	 * @param array  $query_params
768
+	 * @param string $default_where_conditions
769
+	 * @return array
770
+	 * @since   5.0.0.p
771
+	 */
772
+	private function addDefaultWhereConditions(
773
+		array $query_params,
774
+		$default_where_conditions = EEM_Base::default_where_conditions_none
775
+	) {
776
+		$query_params['default_where_conditions'] = $default_where_conditions;
777
+		return $query_params;
778
+	}
779
+
780
+
781
+	/**
782
+	 * @param array $where_params
783
+	 * @param bool  $include_deleted
784
+	 * @param bool  $include_expired
785
+	 * @return array
786
+	 * @since   5.0.0.p
787
+	 */
788
+	private function addDefaultWhereParams(
789
+		array $where_params,
790
+		bool $include_deleted = true,
791
+		bool $include_expired = true
792
+	) {
793
+		$where_params = $this->addExpiredWhereParams($where_params, $include_expired);
794
+		$where_params = $this->addDeletedWhereParams($where_params, $include_deleted);
795
+		return $where_params;
796
+	}
797
+
798
+
799
+	/**
800
+	 * @param array $where_params
801
+	 * @param bool  $include_deleted
802
+	 * @return array
803
+	 * @since   5.0.0.p
804
+	 */
805
+	private function addDeletedWhereParams(array $where_params, bool $include_deleted = true)
806
+	{
807
+		$deleted                     = $include_deleted ? [true, false] : [false];
808
+		$where_params['DTT_deleted'] = ['IN', $deleted];
809
+		return $where_params;
810
+	}
811
+
812
+
813
+	/**
814
+	 * @param array $where_params
815
+	 * @param bool  $include_expired
816
+	 * @return array
817
+	 * @since   5.0.0.p
818
+	 */
819
+	private function addExpiredWhereParams(array $where_params, bool $include_expired = true)
820
+	{
821
+		if (! $include_expired) {
822
+			$where_params['DTT_EVT_end'] = ['>=', current_time('mysql', true)];
823
+		}
824
+		return $where_params;
825
+	}
826
+
827
+
828
+	/**
829
+	 * @param array $query_params
830
+	 * @param int   $limit
831
+	 * @return array
832
+	 * @since   5.0.0.p
833
+	 */
834
+	private function addLimitQueryParams(array $query_params, $limit = 0)
835
+	{
836
+		if ($limit) {
837
+			$query_params['limit'] = $limit;
838
+		}
839
+		return $query_params;
840
+	}
841
+
842
+
843
+	/**
844
+	 * @param array  $query_params
845
+	 * @param string $order_by
846
+	 * @param string $order
847
+	 * @return array
848
+	 * @since   5.0.0.p
849
+	 */
850
+	private function addOrderByQueryParams(array $query_params, $order_by = 'DTT_EVT_start', $order = 'ASC')
851
+	{
852
+		$order                    = $order === 'ASC' ? 'ASC' : 'DESC';
853
+		$valid_order_columns      = ['DTT_ID', 'DTT_EVT_start', 'DTT_EVT_end', 'DTT_order'];
854
+		$order_by                 = in_array($order_by, $valid_order_columns, true) ? $order_by : 'DTT_EVT_start';
855
+		$query_params['order_by'] = [$order_by => $order];
856
+		return $query_params;
857
+	}
858 858
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Extra_Meta.model.php 2 patches
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -14,59 +14,59 @@
 block discarded – undo
14 14
  */
15 15
 class EEM_Extra_Meta extends EEM_Base
16 16
 {
17
-    // private instance of the Attendee object
18
-    protected static $_instance = null;
17
+	// private instance of the Attendee object
18
+	protected static $_instance = null;
19 19
 
20 20
 
21
-    /**
22
-     * @param string|null $timezone
23
-     * @throws EE_Error
24
-     */
25
-    protected function __construct(?string $timezone = '')
26
-    {
27
-        $this->singular_item       = esc_html__('Extra Meta', 'event_espresso');
28
-        $this->plural_item         = esc_html__('Extra Metas', 'event_espresso');
29
-        $this->_tables             = [
30
-            'Extra_Meta' => new EE_Primary_Table('esp_extra_meta', 'EXM_ID'),
31
-        ];
32
-        $models_this_can_attach_to = array_keys(EE_Registry::instance()->non_abstract_db_models);
33
-        $this->_fields             = [
34
-            'Extra_Meta' => [
35
-                'EXM_ID'    => new EE_Primary_Key_Int_Field('EXM_ID', esc_html__("Extra Meta ID", "event_espresso")),
36
-                'OBJ_ID'    => new EE_Foreign_Key_Int_Field(
37
-                    'OBJ_ID',
38
-                    esc_html__("Primary Key of Attached Thing", "event_espresso"),
39
-                    false,
40
-                    0,
41
-                    $models_this_can_attach_to
42
-                ),
43
-                'EXM_type'  => new EE_Any_Foreign_Model_Name_Field(
44
-                    'EXM_type',
45
-                    esc_html__(
46
-                        "Model of Attached Thing",
47
-                        "event_espresso"
48
-                    ),
49
-                    false,
50
-                    'Transaction',
51
-                    $models_this_can_attach_to
52
-                ),
53
-                'EXM_key'   => new EE_Plain_Text_Field('EXM_key', esc_html__("Meta Key", "event_espresso"), false, ''),
54
-                'EXM_value' => new EE_Maybe_Serialized_Text_Field(
55
-                    'EXM_value',
56
-                    esc_html__("Meta Value", "event_espresso"),
57
-                    true
58
-                ),
21
+	/**
22
+	 * @param string|null $timezone
23
+	 * @throws EE_Error
24
+	 */
25
+	protected function __construct(?string $timezone = '')
26
+	{
27
+		$this->singular_item       = esc_html__('Extra Meta', 'event_espresso');
28
+		$this->plural_item         = esc_html__('Extra Metas', 'event_espresso');
29
+		$this->_tables             = [
30
+			'Extra_Meta' => new EE_Primary_Table('esp_extra_meta', 'EXM_ID'),
31
+		];
32
+		$models_this_can_attach_to = array_keys(EE_Registry::instance()->non_abstract_db_models);
33
+		$this->_fields             = [
34
+			'Extra_Meta' => [
35
+				'EXM_ID'    => new EE_Primary_Key_Int_Field('EXM_ID', esc_html__("Extra Meta ID", "event_espresso")),
36
+				'OBJ_ID'    => new EE_Foreign_Key_Int_Field(
37
+					'OBJ_ID',
38
+					esc_html__("Primary Key of Attached Thing", "event_espresso"),
39
+					false,
40
+					0,
41
+					$models_this_can_attach_to
42
+				),
43
+				'EXM_type'  => new EE_Any_Foreign_Model_Name_Field(
44
+					'EXM_type',
45
+					esc_html__(
46
+						"Model of Attached Thing",
47
+						"event_espresso"
48
+					),
49
+					false,
50
+					'Transaction',
51
+					$models_this_can_attach_to
52
+				),
53
+				'EXM_key'   => new EE_Plain_Text_Field('EXM_key', esc_html__("Meta Key", "event_espresso"), false, ''),
54
+				'EXM_value' => new EE_Maybe_Serialized_Text_Field(
55
+					'EXM_value',
56
+					esc_html__("Meta Value", "event_espresso"),
57
+					true
58
+				),
59 59
 
60
-            ],
61
-        ];
62
-        $this->_model_relations    = [];
63
-        foreach ($models_this_can_attach_to as $model) {
64
-            $this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
65
-        }
66
-        foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
67
-            $this->_cap_restriction_generators[ $cap_context ] =
68
-                new EE_Restriction_Generator_Meta('EXM_key', 'EXM_value');
69
-        }
70
-        parent::__construct($timezone);
71
-    }
60
+			],
61
+		];
62
+		$this->_model_relations    = [];
63
+		foreach ($models_this_can_attach_to as $model) {
64
+			$this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
65
+		}
66
+		foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
67
+			$this->_cap_restriction_generators[ $cap_context ] =
68
+				new EE_Restriction_Generator_Meta('EXM_key', 'EXM_value');
69
+		}
70
+		parent::__construct($timezone);
71
+	}
72 72
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -59,12 +59,12 @@
 block discarded – undo
59 59
 
60 60
             ],
61 61
         ];
62
-        $this->_model_relations    = [];
62
+        $this->_model_relations = [];
63 63
         foreach ($models_this_can_attach_to as $model) {
64
-            $this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
64
+            $this->_model_relations[$model] = new EE_Belongs_To_Any_Relation();
65 65
         }
66 66
         foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
67
-            $this->_cap_restriction_generators[ $cap_context ] =
67
+            $this->_cap_restriction_generators[$cap_context] =
68 68
                 new EE_Restriction_Generator_Meta('EXM_key', 'EXM_value');
69 69
         }
70 70
         parent::__construct($timezone);
Please login to merge, or discard this patch.
core/db_models/EEM_Price.model.php 1 patch
Indentation   +354 added lines, -354 removed lines patch added patch discarded remove patch
@@ -13,385 +13,385 @@
 block discarded – undo
13 13
 class EEM_Price extends EEM_Soft_Delete_Base
14 14
 {
15 15
 
16
-    /**
17
-     * private instance of the EEM_Price object
18
-     *
19
-     * @var EEM_Price $_instance
20
-     */
21
-    protected static $_instance;
16
+	/**
17
+	 * private instance of the EEM_Price object
18
+	 *
19
+	 * @var EEM_Price $_instance
20
+	 */
21
+	protected static $_instance;
22 22
 
23 23
 
24
-    /**
25
-     * private constructor to prevent direct creation
26
-     *
27
-     * @Constructor
28
-     * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings
29
-     *                              (and any incoming timezone data that gets saved).
30
-     *                              Note this just sends the timezone info to the date time model field objects.
31
-     *                              Default is NULL
32
-     *                              (and will be assumed using the set timezone in the 'timezone_string' wp option)
33
-     * @throws EE_Error
34
-     * @throws ReflectionException
35
-     */
36
-    protected function __construct(?string $timezone = '')
37
-    {
38
-        $this->singular_item = esc_html__('Price', 'event_espresso');
39
-        $this->plural_item   = esc_html__('Prices', 'event_espresso');
24
+	/**
25
+	 * private constructor to prevent direct creation
26
+	 *
27
+	 * @Constructor
28
+	 * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings
29
+	 *                              (and any incoming timezone data that gets saved).
30
+	 *                              Note this just sends the timezone info to the date time model field objects.
31
+	 *                              Default is NULL
32
+	 *                              (and will be assumed using the set timezone in the 'timezone_string' wp option)
33
+	 * @throws EE_Error
34
+	 * @throws ReflectionException
35
+	 */
36
+	protected function __construct(?string $timezone = '')
37
+	{
38
+		$this->singular_item = esc_html__('Price', 'event_espresso');
39
+		$this->plural_item   = esc_html__('Prices', 'event_espresso');
40 40
 
41
-        $this->_tables          = [
42
-            'Price' => new EE_Primary_Table('esp_price', 'PRC_ID'),
43
-        ];
44
-        $this->_fields          = [
45
-            'Price' => [
46
-                'PRC_ID'         => new EE_Primary_Key_Int_Field(
47
-                    'PRC_ID',
48
-                    'Price ID'
49
-                ),
50
-                'PRT_ID'         => new EE_Foreign_Key_Int_Field(
51
-                    'PRT_ID',
52
-                    esc_html__('Price type Id', 'event_espresso'),
53
-                    false,
54
-                    null,
55
-                    'Price_Type'
56
-                ),
57
-                'PRC_amount'     => new EE_Money_Field(
58
-                    'PRC_amount',
59
-                    esc_html__('Price Amount', 'event_espresso'),
60
-                    false,
61
-                    0
62
-                ),
63
-                'PRC_name'       => new EE_Plain_Text_Field(
64
-                    'PRC_name',
65
-                    esc_html__('Name of Price', 'event_espresso'),
66
-                    false,
67
-                    ''
68
-                ),
69
-                'PRC_desc'       => new EE_Post_Content_Field(
70
-                    'PRC_desc',
71
-                    esc_html__('Price Description', 'event_espresso'),
72
-                    false,
73
-                    ''
74
-                ),
75
-                'PRC_is_default' => new EE_Boolean_Field(
76
-                    'PRC_is_default',
77
-                    esc_html__('Flag indicating whether price is a default price', 'event_espresso'),
78
-                    false,
79
-                    false
80
-                ),
81
-                'PRC_overrides'  => new EE_Integer_Field(
82
-                    'PRC_overrides',
83
-                    esc_html__(
84
-                        'Price ID for a global Price that will be overridden by this Price  ( for replacing default prices )',
85
-                        'event_espresso'
86
-                    ),
87
-                    true,
88
-                    0
89
-                ),
90
-                'PRC_order'      => new EE_Integer_Field(
91
-                    'PRC_order',
92
-                    esc_html__(
93
-                        'Order of Application of Price (lower numbers apply first?)',
94
-                        'event_espresso'
95
-                    ),
96
-                    false,
97
-                    1
98
-                ),
99
-                'PRC_deleted'    => new EE_Trashed_Flag_Field(
100
-                    'PRC_deleted',
101
-                    esc_html__('Flag Indicating if this has been deleted or not', 'event_espresso'),
102
-                    false,
103
-                    false
104
-                ),
105
-                'PRC_parent'     => new EE_Integer_Field(
106
-                    'PRC_parent',
107
-                    esc_html__('Indicates what PRC_ID is the parent of this PRC_ID', 'event_espresso'),
108
-                    true,
109
-                    0
110
-                ),
111
-                'PRC_wp_user'    => new EE_WP_User_Field(
112
-                    'PRC_wp_user',
113
-                    esc_html__('Price Creator ID', 'event_espresso'),
114
-                    false
115
-                ),
116
-            ],
117
-        ];
118
-        $this->_model_relations = [
119
-            'Ticket'     => new EE_HABTM_Relation('Ticket_Price'),
120
-            'Price_Type' => new EE_Belongs_To_Relation(),
121
-            'WP_User'    => new EE_Belongs_To_Relation(),
122
-        ];
123
-        // this model is generally available for reading
124
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] =
125
-            new EE_Restriction_Generator_Default_Public(
126
-                'PRC_is_default',
127
-                'Ticket.Datetime.Event'
128
-            );
129
-        // account for default tickets in the caps
130
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
131
-            new EE_Restriction_Generator_Default_Protected(
132
-                'PRC_is_default',
133
-                'Ticket.Datetime.Event'
134
-            );
135
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
136
-            new EE_Restriction_Generator_Default_Protected(
137
-                'PRC_is_default',
138
-                'Ticket.Datetime.Event'
139
-            );
140
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
141
-            new EE_Restriction_Generator_Default_Protected(
142
-                'PRC_is_default',
143
-                'Ticket.Datetime.Event'
144
-            );
145
-        parent::__construct($timezone);
146
-    }
41
+		$this->_tables          = [
42
+			'Price' => new EE_Primary_Table('esp_price', 'PRC_ID'),
43
+		];
44
+		$this->_fields          = [
45
+			'Price' => [
46
+				'PRC_ID'         => new EE_Primary_Key_Int_Field(
47
+					'PRC_ID',
48
+					'Price ID'
49
+				),
50
+				'PRT_ID'         => new EE_Foreign_Key_Int_Field(
51
+					'PRT_ID',
52
+					esc_html__('Price type Id', 'event_espresso'),
53
+					false,
54
+					null,
55
+					'Price_Type'
56
+				),
57
+				'PRC_amount'     => new EE_Money_Field(
58
+					'PRC_amount',
59
+					esc_html__('Price Amount', 'event_espresso'),
60
+					false,
61
+					0
62
+				),
63
+				'PRC_name'       => new EE_Plain_Text_Field(
64
+					'PRC_name',
65
+					esc_html__('Name of Price', 'event_espresso'),
66
+					false,
67
+					''
68
+				),
69
+				'PRC_desc'       => new EE_Post_Content_Field(
70
+					'PRC_desc',
71
+					esc_html__('Price Description', 'event_espresso'),
72
+					false,
73
+					''
74
+				),
75
+				'PRC_is_default' => new EE_Boolean_Field(
76
+					'PRC_is_default',
77
+					esc_html__('Flag indicating whether price is a default price', 'event_espresso'),
78
+					false,
79
+					false
80
+				),
81
+				'PRC_overrides'  => new EE_Integer_Field(
82
+					'PRC_overrides',
83
+					esc_html__(
84
+						'Price ID for a global Price that will be overridden by this Price  ( for replacing default prices )',
85
+						'event_espresso'
86
+					),
87
+					true,
88
+					0
89
+				),
90
+				'PRC_order'      => new EE_Integer_Field(
91
+					'PRC_order',
92
+					esc_html__(
93
+						'Order of Application of Price (lower numbers apply first?)',
94
+						'event_espresso'
95
+					),
96
+					false,
97
+					1
98
+				),
99
+				'PRC_deleted'    => new EE_Trashed_Flag_Field(
100
+					'PRC_deleted',
101
+					esc_html__('Flag Indicating if this has been deleted or not', 'event_espresso'),
102
+					false,
103
+					false
104
+				),
105
+				'PRC_parent'     => new EE_Integer_Field(
106
+					'PRC_parent',
107
+					esc_html__('Indicates what PRC_ID is the parent of this PRC_ID', 'event_espresso'),
108
+					true,
109
+					0
110
+				),
111
+				'PRC_wp_user'    => new EE_WP_User_Field(
112
+					'PRC_wp_user',
113
+					esc_html__('Price Creator ID', 'event_espresso'),
114
+					false
115
+				),
116
+			],
117
+		];
118
+		$this->_model_relations = [
119
+			'Ticket'     => new EE_HABTM_Relation('Ticket_Price'),
120
+			'Price_Type' => new EE_Belongs_To_Relation(),
121
+			'WP_User'    => new EE_Belongs_To_Relation(),
122
+		];
123
+		// this model is generally available for reading
124
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] =
125
+			new EE_Restriction_Generator_Default_Public(
126
+				'PRC_is_default',
127
+				'Ticket.Datetime.Event'
128
+			);
129
+		// account for default tickets in the caps
130
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
131
+			new EE_Restriction_Generator_Default_Protected(
132
+				'PRC_is_default',
133
+				'Ticket.Datetime.Event'
134
+			);
135
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
136
+			new EE_Restriction_Generator_Default_Protected(
137
+				'PRC_is_default',
138
+				'Ticket.Datetime.Event'
139
+			);
140
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
141
+			new EE_Restriction_Generator_Default_Protected(
142
+				'PRC_is_default',
143
+				'Ticket.Datetime.Event'
144
+			);
145
+		parent::__construct($timezone);
146
+	}
147 147
 
148 148
 
149
-    /**
150
-     * instantiate a new price object with blank/empty properties
151
-     *
152
-     * @return EE_Price
153
-     * @throws EE_Error
154
-     * @throws ReflectionException
155
-     */
156
-    public function get_new_price(): EE_Price
157
-    {
158
-        return $this->create_default_object();
159
-    }
149
+	/**
150
+	 * instantiate a new price object with blank/empty properties
151
+	 *
152
+	 * @return EE_Price
153
+	 * @throws EE_Error
154
+	 * @throws ReflectionException
155
+	 */
156
+	public function get_new_price(): EE_Price
157
+	{
158
+		return $this->create_default_object();
159
+	}
160 160
 
161 161
 
162
-    /**
163
-     * retrieve  ALL prices from db
164
-     *
165
-     * @return EE_Price[]
166
-     * @throws EE_Error
167
-     * @throws ReflectionException
168
-     */
169
-    public function get_all_prices(): array
170
-    {
171
-        // retrieve all prices
172
-        return $this->get_all(['order_by' => ['PRC_amount' => 'ASC']]);
173
-    }
162
+	/**
163
+	 * retrieve  ALL prices from db
164
+	 *
165
+	 * @return EE_Price[]
166
+	 * @throws EE_Error
167
+	 * @throws ReflectionException
168
+	 */
169
+	public function get_all_prices(): array
170
+	{
171
+		// retrieve all prices
172
+		return $this->get_all(['order_by' => ['PRC_amount' => 'ASC']]);
173
+	}
174 174
 
175 175
 
176
-    /**
177
-     * retrieve all active prices for a particular event
178
-     *
179
-     * @param int $EVT_ID
180
-     * @return array on success
181
-     * @throws EE_Error
182
-     * @throws ReflectionException
183
-     */
184
-    public function get_all_event_prices(int $EVT_ID = 0): array
185
-    {
186
-        return $this->get_all(
187
-            [
188
-                [
189
-                    'EVT_ID'            => $EVT_ID,
190
-                    'Price_Type.PBT_ID' => ['!=', EEM_Price_Type::base_type_tax],
191
-                ],
192
-                'order_by' => $this->_order_by_array_for_get_all_method(),
193
-            ]
194
-        );
195
-    }
176
+	/**
177
+	 * retrieve all active prices for a particular event
178
+	 *
179
+	 * @param int $EVT_ID
180
+	 * @return array on success
181
+	 * @throws EE_Error
182
+	 * @throws ReflectionException
183
+	 */
184
+	public function get_all_event_prices(int $EVT_ID = 0): array
185
+	{
186
+		return $this->get_all(
187
+			[
188
+				[
189
+					'EVT_ID'            => $EVT_ID,
190
+					'Price_Type.PBT_ID' => ['!=', EEM_Price_Type::base_type_tax],
191
+				],
192
+				'order_by' => $this->_order_by_array_for_get_all_method(),
193
+			]
194
+		);
195
+	}
196 196
 
197 197
 
198
-    /**
199
-     * retrieve all active global prices (that are not taxes (PBT_ID=4)) for a particular event
200
-     *
201
-     * @param bool $count return count
202
-     * @param bool $include_taxes
203
-     * @return int|EE_Price[]
204
-     * @throws EE_Error
205
-     * @throws ReflectionException
206
-     * @throws ReflectionException
207
-     */
208
-    public function get_all_default_prices(bool $count = false, bool $include_taxes = false)
209
-    {
210
-        $_where = [
211
-            'PRC_deleted'    => 0,
212
-            'PRC_is_default' => 1,
213
-        ];
214
-        if (! $include_taxes) {
215
-            $_where['Price_Type.PBT_ID'] = ['!=', 4];
216
-        }
217
-        $_query_params = [
218
-            $_where,
219
-            'order_by' => $this->_order_by_array_for_get_all_method(),
220
-        ];
221
-        return $count ? $this->count([$_where]) : $this->get_all($_query_params);
222
-    }
198
+	/**
199
+	 * retrieve all active global prices (that are not taxes (PBT_ID=4)) for a particular event
200
+	 *
201
+	 * @param bool $count return count
202
+	 * @param bool $include_taxes
203
+	 * @return int|EE_Price[]
204
+	 * @throws EE_Error
205
+	 * @throws ReflectionException
206
+	 * @throws ReflectionException
207
+	 */
208
+	public function get_all_default_prices(bool $count = false, bool $include_taxes = false)
209
+	{
210
+		$_where = [
211
+			'PRC_deleted'    => 0,
212
+			'PRC_is_default' => 1,
213
+		];
214
+		if (! $include_taxes) {
215
+			$_where['Price_Type.PBT_ID'] = ['!=', 4];
216
+		}
217
+		$_query_params = [
218
+			$_where,
219
+			'order_by' => $this->_order_by_array_for_get_all_method(),
220
+		];
221
+		return $count ? $this->count([$_where]) : $this->get_all($_query_params);
222
+	}
223 223
 
224 224
 
225
-    /**
226
-     * retrieve all active global prices that are taxes
227
-     *
228
-     * @return EE_Price[]
229
-     * @throws EE_Error
230
-     * @throws ReflectionException
231
-     * @since   5.0.0.p
232
-     */
233
-    public function getAllDefaultTaxes(): array
234
-    {
235
-        return $this->get_all(
236
-            [
237
-                [
238
-                    'PRC_deleted'       => 0,
239
-                    'PRC_is_default'    => 1,
240
-                    'Price_Type.PBT_ID' => EEM_Price_Type::base_type_tax,
241
-                ],
242
-                'order_by' => [
243
-                    'Price_Type.PRT_order' => 'ASC',
244
-                    'PRC_order'            => 'ASC',
245
-                ],
246
-            ]
247
-        );
248
-    }
225
+	/**
226
+	 * retrieve all active global prices that are taxes
227
+	 *
228
+	 * @return EE_Price[]
229
+	 * @throws EE_Error
230
+	 * @throws ReflectionException
231
+	 * @since   5.0.0.p
232
+	 */
233
+	public function getAllDefaultTaxes(): array
234
+	{
235
+		return $this->get_all(
236
+			[
237
+				[
238
+					'PRC_deleted'       => 0,
239
+					'PRC_is_default'    => 1,
240
+					'Price_Type.PBT_ID' => EEM_Price_Type::base_type_tax,
241
+				],
242
+				'order_by' => [
243
+					'Price_Type.PRT_order' => 'ASC',
244
+					'PRC_order'            => 'ASC',
245
+				],
246
+			]
247
+		);
248
+	}
249 249
 
250 250
 
251
-    /**
252
-     * retrieve all prices that are taxes
253
-     *
254
-     * @return EE_Price[]
255
-     * @throws EE_Error
256
-     * @throws InvalidArgumentException
257
-     * @throws ReflectionException
258
-     * @throws InvalidDataTypeException
259
-     * @throws InvalidInterfaceException
260
-     */
261
-    public function get_all_prices_that_are_taxes(): array
262
-    {
263
-        $taxes     = [];
264
-        $all_taxes = $this->get_all(
265
-            [
266
-                ['Price_Type.PBT_ID' => EEM_Price_Type::base_type_tax, 'PRC_is_default' => 1],
267
-                'order_by' => ['Price_Type.PRT_order' => 'ASC', 'PRC_order' => 'ASC'],
268
-            ]
269
-        );
270
-        foreach ($all_taxes as $tax) {
271
-            if ($tax instanceof EE_Price) {
272
-                $taxes[ $tax->order() ][ $tax->ID() ] = $tax;
273
-            }
274
-        }
275
-        return $taxes;
276
-    }
251
+	/**
252
+	 * retrieve all prices that are taxes
253
+	 *
254
+	 * @return EE_Price[]
255
+	 * @throws EE_Error
256
+	 * @throws InvalidArgumentException
257
+	 * @throws ReflectionException
258
+	 * @throws InvalidDataTypeException
259
+	 * @throws InvalidInterfaceException
260
+	 */
261
+	public function get_all_prices_that_are_taxes(): array
262
+	{
263
+		$taxes     = [];
264
+		$all_taxes = $this->get_all(
265
+			[
266
+				['Price_Type.PBT_ID' => EEM_Price_Type::base_type_tax, 'PRC_is_default' => 1],
267
+				'order_by' => ['Price_Type.PRT_order' => 'ASC', 'PRC_order' => 'ASC'],
268
+			]
269
+		);
270
+		foreach ($all_taxes as $tax) {
271
+			if ($tax instanceof EE_Price) {
272
+				$taxes[ $tax->order() ][ $tax->ID() ] = $tax;
273
+			}
274
+		}
275
+		return $taxes;
276
+	}
277 277
 
278 278
 
279
-    /**
280
-     * retrieve all prices for an ticket plus default global prices, but not taxes
281
-     *
282
-     * @param int $TKT_ID the id of the event.  If not included then we assume that this is a new ticket.
283
-     * @return EE_Price[]
284
-     * @throws EE_Error
285
-     * @throws ReflectionException
286
-     * @throws ReflectionException
287
-     * @throws ReflectionException
288
-     */
289
-    public function get_all_ticket_prices_for_admin(int $TKT_ID = 0): array
290
-    {
291
-        $array_of_price_objects = [];
292
-        if (empty($TKT_ID)) {
293
-            // if there is no tkt, get prices with no tkt ID, are global, are not a tax, and are active
294
-            // return that list
295
-            $default_prices = $this->get_all_default_prices();
279
+	/**
280
+	 * retrieve all prices for an ticket plus default global prices, but not taxes
281
+	 *
282
+	 * @param int $TKT_ID the id of the event.  If not included then we assume that this is a new ticket.
283
+	 * @return EE_Price[]
284
+	 * @throws EE_Error
285
+	 * @throws ReflectionException
286
+	 * @throws ReflectionException
287
+	 * @throws ReflectionException
288
+	 */
289
+	public function get_all_ticket_prices_for_admin(int $TKT_ID = 0): array
290
+	{
291
+		$array_of_price_objects = [];
292
+		if (empty($TKT_ID)) {
293
+			// if there is no tkt, get prices with no tkt ID, are global, are not a tax, and are active
294
+			// return that list
295
+			$default_prices = $this->get_all_default_prices();
296 296
 
297
-            if ($default_prices) {
298
-                foreach ($default_prices as $price) {
299
-                    if ($price instanceof EE_Price) {
300
-                        $array_of_price_objects[ $price->type() ][] = $price;
301
-                    }
302
-                }
303
-                return $array_of_price_objects;
304
-            }
305
-            return [];
306
-        }
307
-        $ticket_prices = $this->get_all(
308
-            [
309
-                [
310
-                    'TKT_ID'      => $TKT_ID,
311
-                    'PRC_deleted' => 0,
312
-                ],
313
-                'order_by' => ['PRC_order' => 'ASC'],
314
-            ]
315
-        );
297
+			if ($default_prices) {
298
+				foreach ($default_prices as $price) {
299
+					if ($price instanceof EE_Price) {
300
+						$array_of_price_objects[ $price->type() ][] = $price;
301
+					}
302
+				}
303
+				return $array_of_price_objects;
304
+			}
305
+			return [];
306
+		}
307
+		$ticket_prices = $this->get_all(
308
+			[
309
+				[
310
+					'TKT_ID'      => $TKT_ID,
311
+					'PRC_deleted' => 0,
312
+				],
313
+				'order_by' => ['PRC_order' => 'ASC'],
314
+			]
315
+		);
316 316
 
317
-        if (! empty($ticket_prices)) {
318
-            foreach ($ticket_prices as $price) {
319
-                if ($price instanceof EE_Price) {
320
-                    $array_of_price_objects[ $price->type() ][] = $price;
321
-                }
322
-            }
323
-            return $array_of_price_objects;
324
-        }
325
-        return [];
326
-    }
317
+		if (! empty($ticket_prices)) {
318
+			foreach ($ticket_prices as $price) {
319
+				if ($price instanceof EE_Price) {
320
+					$array_of_price_objects[ $price->type() ][] = $price;
321
+				}
322
+			}
323
+			return $array_of_price_objects;
324
+		}
325
+		return [];
326
+	}
327 327
 
328 328
 
329
-    /**
330
-     * @param EE_Price $price_a
331
-     * @param EE_Price $price_b
332
-     * @return int
333
-     * @throws EE_Error
334
-     * @throws ReflectionException
335
-     */
336
-    public function _sort_event_prices_by_type(EE_Price $price_a, EE_Price $price_b): int
337
-    {
338
-        if ($price_a->type_obj()->order() === $price_b->type_obj()->order()) {
339
-            return $this->_sort_event_prices_by_order($price_a, $price_b);
340
-        }
341
-        return $price_a->type_obj()->order() < $price_b->type_obj()->order() ? -1 : 1;
342
-    }
329
+	/**
330
+	 * @param EE_Price $price_a
331
+	 * @param EE_Price $price_b
332
+	 * @return int
333
+	 * @throws EE_Error
334
+	 * @throws ReflectionException
335
+	 */
336
+	public function _sort_event_prices_by_type(EE_Price $price_a, EE_Price $price_b): int
337
+	{
338
+		if ($price_a->type_obj()->order() === $price_b->type_obj()->order()) {
339
+			return $this->_sort_event_prices_by_order($price_a, $price_b);
340
+		}
341
+		return $price_a->type_obj()->order() < $price_b->type_obj()->order() ? -1 : 1;
342
+	}
343 343
 
344 344
 
345
-    /**
346
-     * @param EE_Price $price_a
347
-     * @param EE_Price $price_b
348
-     * @return int
349
-     * @throws EE_Error
350
-     * @throws ReflectionException
351
-     */
352
-    public function _sort_event_prices_by_order(EE_Price $price_a, EE_Price $price_b): int
353
-    {
354
-        if ($price_a->order() === $price_b->order()) {
355
-            return 0;
356
-        }
357
-        return $price_a->order() < $price_b->order() ? -1 : 1;
358
-    }
345
+	/**
346
+	 * @param EE_Price $price_a
347
+	 * @param EE_Price $price_b
348
+	 * @return int
349
+	 * @throws EE_Error
350
+	 * @throws ReflectionException
351
+	 */
352
+	public function _sort_event_prices_by_order(EE_Price $price_a, EE_Price $price_b): int
353
+	{
354
+		if ($price_a->order() === $price_b->order()) {
355
+			return 0;
356
+		}
357
+		return $price_a->order() < $price_b->order() ? -1 : 1;
358
+	}
359 359
 
360 360
 
361
-    /**
362
-     * get all prices of a specific type
363
-     *
364
-     * @param int $type - PRT_ID
365
-     * @return EE_Price[]
366
-     * @throws EE_Error
367
-     * @throws ReflectionException
368
-     */
369
-    public function get_all_prices_that_are_type(int $type = 0): array
370
-    {
371
-        return $this->get_all(
372
-            [
373
-                [
374
-                    'PRT_ID' => $type,
375
-                ],
376
-                'order_by' => $this->_order_by_array_for_get_all_method(),
377
-            ]
378
-        );
379
-    }
361
+	/**
362
+	 * get all prices of a specific type
363
+	 *
364
+	 * @param int $type - PRT_ID
365
+	 * @return EE_Price[]
366
+	 * @throws EE_Error
367
+	 * @throws ReflectionException
368
+	 */
369
+	public function get_all_prices_that_are_type(int $type = 0): array
370
+	{
371
+		return $this->get_all(
372
+			[
373
+				[
374
+					'PRT_ID' => $type,
375
+				],
376
+				'order_by' => $this->_order_by_array_for_get_all_method(),
377
+			]
378
+		);
379
+	}
380 380
 
381 381
 
382
-    /**
383
-     * Returns an array of the normal 'order_by' query parameter provided to the get_all query.
384
-     * Of course you don't have to use it, but this is the order we usually want to sort prices by
385
-     *
386
-     * @return array which can be used like so: $this->get_all(array(array(...where
387
-     *               stuff...),'order_by'=>$this->_order_by_array_for_get_all_method()));
388
-     */
389
-    public function _order_by_array_for_get_all_method(): array
390
-    {
391
-        return [
392
-            'PRC_order'            => 'ASC',
393
-            'Price_Type.PRT_order' => 'ASC',
394
-            'PRC_ID'               => 'ASC',
395
-        ];
396
-    }
382
+	/**
383
+	 * Returns an array of the normal 'order_by' query parameter provided to the get_all query.
384
+	 * Of course you don't have to use it, but this is the order we usually want to sort prices by
385
+	 *
386
+	 * @return array which can be used like so: $this->get_all(array(array(...where
387
+	 *               stuff...),'order_by'=>$this->_order_by_array_for_get_all_method()));
388
+	 */
389
+	public function _order_by_array_for_get_all_method(): array
390
+	{
391
+		return [
392
+			'PRC_order'            => 'ASC',
393
+			'Price_Type.PRT_order' => 'ASC',
394
+			'PRC_ID'               => 'ASC',
395
+		];
396
+	}
397 397
 }
Please login to merge, or discard this patch.