Completed
Branch FET/reg-form-builder/main (69a760)
by
unknown
04:39 queued 02:08
created
core/domain/services/graphql/types/FormElement.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
      */
35 35
     public function __construct(EEM_Form_Element $form_element_model)
36 36
     {
37
-        $this->setName($this->namespace . 'FormElement');
37
+        $this->setName($this->namespace.'FormElement');
38 38
         $this->setDescription(__('A form element', 'event_espresso'));
39 39
         $this->setIsCustomPostType(false);
40 40
 
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
             ),
134 134
             new GraphQLField(
135 135
                 'status',
136
-                $this->namespace . 'FormStatusEnum',
136
+                $this->namespace.'FormStatusEnum',
137 137
                 'status',
138 138
                 esc_html__(
139 139
                     'Whether form element is active, archived, trashed, or used as a default on new forms.',
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
             ),
143 143
             new GraphQLField(
144 144
                 'type',
145
-                $this->namespace . 'ElementTypeEnum',
145
+                $this->namespace.'ElementTypeEnum',
146 146
                 'type',
147 147
                 esc_html__('Form element type.', 'event_espresso')
148 148
             ),
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
     {
181 181
         // Register mutation to update an entity.
182 182
         register_graphql_mutation(
183
-            'update' . $this->name(),
183
+            'update'.$this->name(),
184 184
             [
185 185
                 'inputFields'         => $inputFields,
186 186
                 'outputFields'        => [
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
         );
195 195
         // Register mutation to delete an entity.
196 196
         register_graphql_mutation(
197
-            'delete' . $this->name(),
197
+            'delete'.$this->name(),
198 198
             [
199 199
                 'inputFields'         => [
200 200
                     'id' => $inputFields['id'],
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
                     lcfirst($this->name()) => [
204 204
                         'type'        => $this->name(),
205 205
                         'description' => esc_html__('The object before it was deleted', 'event_espresso'),
206
-                        'resolve'     => static function ($payload) {
206
+                        'resolve'     => static function($payload) {
207 207
                             $deleted = (object) $payload['deleted'];
208 208
 
209 209
                             return ! empty($deleted) ? $deleted : null;
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 
221 221
         // Register mutation to update an entity.
222 222
         register_graphql_mutation(
223
-            'create' . $this->name(),
223
+            'create'.$this->name(),
224 224
             [
225 225
                 'inputFields'         => $inputFields,
226 226
                 'outputFields'        => [
Please login to merge, or discard this patch.
Indentation   +197 added lines, -197 removed lines patch added patch discarded remove patch
@@ -27,210 +27,210 @@
 block discarded – undo
27 27
 class FormElement extends TypeBase
28 28
 {
29 29
 
30
-    /**
31
-     * FormElement constructor.
32
-     *
33
-     * @param EEM_Form_Element $form_element_model
34
-     */
35
-    public function __construct(EEM_Form_Element $form_element_model)
36
-    {
37
-        $this->setName($this->namespace . 'FormElement');
38
-        $this->setDescription(__('A form element', 'event_espresso'));
39
-        $this->setIsCustomPostType(false);
30
+	/**
31
+	 * FormElement constructor.
32
+	 *
33
+	 * @param EEM_Form_Element $form_element_model
34
+	 */
35
+	public function __construct(EEM_Form_Element $form_element_model)
36
+	{
37
+		$this->setName($this->namespace . 'FormElement');
38
+		$this->setDescription(__('A form element', 'event_espresso'));
39
+		$this->setIsCustomPostType(false);
40 40
 
41
-        parent::__construct($form_element_model);
42
-    }
41
+		parent::__construct($form_element_model);
42
+	}
43 43
 
44 44
 
45
-    /**
46
-     * @return GraphQLFieldInterface[]
47
-     */
48
-    public function getFields(): array
49
-    {
50
-        $fields = [
51
-            new GraphQLField(
52
-                'id',
53
-                ['non_null' => 'ID'],
54
-                null,
55
-                esc_html__('The globally unique ID for the object.', 'event_espresso')
56
-            ),
57
-            new GraphQLField(
58
-                'adminOnly',
59
-                'Boolean',
60
-                'adminOnly',
61
-                esc_html__(
62
-                    'Whether or not the element is only displayed in the admin. If false, input will appear in public forms',
63
-                    'event_espresso'
64
-                )
65
-            ),
66
-            new GraphQLField(
67
-                'attributes',
68
-                'String',
69
-                'attributes',
70
-                esc_html__(
71
-                    'JSON string of HTML attributes such as class, max, min, placeholder, type, etc.',
72
-                    'event_espresso'
73
-                ),
74
-                [$this, 'toJson']
75
-            ),
76
-            new GraphQLField(
77
-                'belongsTo',
78
-                'String',
79
-                'belongsTo',
80
-                esc_html__('UUID of parent form section this form element belongs to.', 'event_espresso')
81
-            ),
82
-            new GraphQLField(
83
-                'helpText',
84
-                'String',
85
-                'helpText',
86
-                esc_html__(
87
-                    "JSON string of properties pertaining to any help text required for an input.",
88
-                    'event_espresso'
89
-                ),
90
-                [$this, 'toJson']
91
-            ),
92
-            new GraphQLField(
93
-                'label',
94
-                'String',
95
-                'label',
96
-                esc_html__(
97
-                    'JSON string of properties pertaining to an element\'s label.',
98
-                    'event_espresso'
99
-                ),
100
-                [$this, 'toJson']
101
-            ),
102
-            new GraphQLField(
103
-                'mapsTo',
104
-                'String',
105
-                'mapsTo',
106
-                esc_html__("Model and Fields name that this element maps to; ex: Attendee.email", 'event_espresso')
107
-            ),
108
-            new GraphQLField(
109
-                'options',
110
-                'String',
111
-                'options',
112
-                esc_html__(
113
-                    "JSON string of options for ENUM type inputs like checkboxes, radio buttons, select inputs, etc.",
114
-                    'event_espresso'
115
-                ),
116
-                [$this, 'toJson']
117
-            ),
118
-            new GraphQLField(
119
-                'order',
120
-                'Int',
121
-                'order',
122
-                esc_html__('Order in which form element appears in a form.', 'event_espresso')
123
-            ),
124
-            new GraphQLField(
125
-                'required',
126
-                'String',
127
-                'required',
128
-                esc_html__(
129
-                    "properties pertaining to an input\'s required status and the validation text to display.",
130
-                    'event_espresso'
131
-                ),
132
-                [$this, 'toJson']
133
-            ),
134
-            new GraphQLField(
135
-                'status',
136
-                $this->namespace . 'FormStatusEnum',
137
-                'status',
138
-                esc_html__(
139
-                    'Whether form element is active, archived, trashed, or used as a default on new forms.',
140
-                    'event_espresso'
141
-                )
142
-            ),
143
-            new GraphQLField(
144
-                'type',
145
-                $this->namespace . 'ElementTypeEnum',
146
-                'type',
147
-                esc_html__('Form element type.', 'event_espresso')
148
-            ),
149
-            new GraphQLOutputField(
150
-                'wpUser',
151
-                'User',
152
-                null,
153
-                esc_html__('WP User that created this form element.', 'event_espresso')
154
-            ),
155
-            new GraphQLInputField(
156
-                'wpUser',
157
-                'ID',
158
-                null,
159
-                esc_html__('ID of the WP User that created the form element.', 'event_espresso')
160
-            ),
161
-        ];
45
+	/**
46
+	 * @return GraphQLFieldInterface[]
47
+	 */
48
+	public function getFields(): array
49
+	{
50
+		$fields = [
51
+			new GraphQLField(
52
+				'id',
53
+				['non_null' => 'ID'],
54
+				null,
55
+				esc_html__('The globally unique ID for the object.', 'event_espresso')
56
+			),
57
+			new GraphQLField(
58
+				'adminOnly',
59
+				'Boolean',
60
+				'adminOnly',
61
+				esc_html__(
62
+					'Whether or not the element is only displayed in the admin. If false, input will appear in public forms',
63
+					'event_espresso'
64
+				)
65
+			),
66
+			new GraphQLField(
67
+				'attributes',
68
+				'String',
69
+				'attributes',
70
+				esc_html__(
71
+					'JSON string of HTML attributes such as class, max, min, placeholder, type, etc.',
72
+					'event_espresso'
73
+				),
74
+				[$this, 'toJson']
75
+			),
76
+			new GraphQLField(
77
+				'belongsTo',
78
+				'String',
79
+				'belongsTo',
80
+				esc_html__('UUID of parent form section this form element belongs to.', 'event_espresso')
81
+			),
82
+			new GraphQLField(
83
+				'helpText',
84
+				'String',
85
+				'helpText',
86
+				esc_html__(
87
+					"JSON string of properties pertaining to any help text required for an input.",
88
+					'event_espresso'
89
+				),
90
+				[$this, 'toJson']
91
+			),
92
+			new GraphQLField(
93
+				'label',
94
+				'String',
95
+				'label',
96
+				esc_html__(
97
+					'JSON string of properties pertaining to an element\'s label.',
98
+					'event_espresso'
99
+				),
100
+				[$this, 'toJson']
101
+			),
102
+			new GraphQLField(
103
+				'mapsTo',
104
+				'String',
105
+				'mapsTo',
106
+				esc_html__("Model and Fields name that this element maps to; ex: Attendee.email", 'event_espresso')
107
+			),
108
+			new GraphQLField(
109
+				'options',
110
+				'String',
111
+				'options',
112
+				esc_html__(
113
+					"JSON string of options for ENUM type inputs like checkboxes, radio buttons, select inputs, etc.",
114
+					'event_espresso'
115
+				),
116
+				[$this, 'toJson']
117
+			),
118
+			new GraphQLField(
119
+				'order',
120
+				'Int',
121
+				'order',
122
+				esc_html__('Order in which form element appears in a form.', 'event_espresso')
123
+			),
124
+			new GraphQLField(
125
+				'required',
126
+				'String',
127
+				'required',
128
+				esc_html__(
129
+					"properties pertaining to an input\'s required status and the validation text to display.",
130
+					'event_espresso'
131
+				),
132
+				[$this, 'toJson']
133
+			),
134
+			new GraphQLField(
135
+				'status',
136
+				$this->namespace . 'FormStatusEnum',
137
+				'status',
138
+				esc_html__(
139
+					'Whether form element is active, archived, trashed, or used as a default on new forms.',
140
+					'event_espresso'
141
+				)
142
+			),
143
+			new GraphQLField(
144
+				'type',
145
+				$this->namespace . 'ElementTypeEnum',
146
+				'type',
147
+				esc_html__('Form element type.', 'event_espresso')
148
+			),
149
+			new GraphQLOutputField(
150
+				'wpUser',
151
+				'User',
152
+				null,
153
+				esc_html__('WP User that created this form element.', 'event_espresso')
154
+			),
155
+			new GraphQLInputField(
156
+				'wpUser',
157
+				'ID',
158
+				null,
159
+				esc_html__('ID of the WP User that created the form element.', 'event_espresso')
160
+			),
161
+		];
162 162
 
163
-        return apply_filters(
164
-            'FHEE__EventEspresso_core_domain_services_graphql_types__form_element_fields',
165
-            $fields,
166
-            $this->name,
167
-            $this->model
168
-        );
169
-    }
163
+		return apply_filters(
164
+			'FHEE__EventEspresso_core_domain_services_graphql_types__form_element_fields',
165
+			$fields,
166
+			$this->name,
167
+			$this->model
168
+		);
169
+	}
170 170
 
171 171
 
172
-    /**
173
-     * @param array $inputFields The mutation input fields.
174
-     * @throws InvalidArgumentException
175
-     * @throws ReflectionException
176
-     * @throws Exception
177
-     * @since $VID:$
178
-     */
179
-    public function registerMutations(array $inputFields)
180
-    {
181
-        // Register mutation to update an entity.
182
-        register_graphql_mutation(
183
-            'update' . $this->name(),
184
-            [
185
-                'inputFields'         => $inputFields,
186
-                'outputFields'        => [
187
-                    lcfirst($this->name()) => [
188
-                        'type'    => $this->name(),
189
-                        'resolve' => [$this, 'resolveFromPayload'],
190
-                    ],
191
-                ],
192
-                'mutateAndGetPayload' => FormElementUpdate::mutateAndGetPayload($this->model),
193
-            ]
194
-        );
195
-        // Register mutation to delete an entity.
196
-        register_graphql_mutation(
197
-            'delete' . $this->name(),
198
-            [
199
-                'inputFields'         => [
200
-                    'id' => $inputFields['id'],
201
-                ],
202
-                'outputFields'        => [
203
-                    lcfirst($this->name()) => [
204
-                        'type'        => $this->name(),
205
-                        'description' => esc_html__('The object before it was deleted', 'event_espresso'),
206
-                        'resolve'     => static function ($payload) {
207
-                            $deleted = (object) $payload['deleted'];
172
+	/**
173
+	 * @param array $inputFields The mutation input fields.
174
+	 * @throws InvalidArgumentException
175
+	 * @throws ReflectionException
176
+	 * @throws Exception
177
+	 * @since $VID:$
178
+	 */
179
+	public function registerMutations(array $inputFields)
180
+	{
181
+		// Register mutation to update an entity.
182
+		register_graphql_mutation(
183
+			'update' . $this->name(),
184
+			[
185
+				'inputFields'         => $inputFields,
186
+				'outputFields'        => [
187
+					lcfirst($this->name()) => [
188
+						'type'    => $this->name(),
189
+						'resolve' => [$this, 'resolveFromPayload'],
190
+					],
191
+				],
192
+				'mutateAndGetPayload' => FormElementUpdate::mutateAndGetPayload($this->model),
193
+			]
194
+		);
195
+		// Register mutation to delete an entity.
196
+		register_graphql_mutation(
197
+			'delete' . $this->name(),
198
+			[
199
+				'inputFields'         => [
200
+					'id' => $inputFields['id'],
201
+				],
202
+				'outputFields'        => [
203
+					lcfirst($this->name()) => [
204
+						'type'        => $this->name(),
205
+						'description' => esc_html__('The object before it was deleted', 'event_espresso'),
206
+						'resolve'     => static function ($payload) {
207
+							$deleted = (object) $payload['deleted'];
208 208
 
209
-                            return ! empty($deleted) ? $deleted : null;
210
-                        },
211
-                    ],
212
-                ],
213
-                'mutateAndGetPayload' => FormElementDelete::mutateAndGetPayload($this->model),
214
-            ]
215
-        );
209
+							return ! empty($deleted) ? $deleted : null;
210
+						},
211
+					],
212
+				],
213
+				'mutateAndGetPayload' => FormElementDelete::mutateAndGetPayload($this->model),
214
+			]
215
+		);
216 216
 
217
-        // Make element 'type' a required field for create mutations
218
-        // Yes it's "['type']['type']" 
Please login to merge, or discard this patch.
core/domain/services/graphql/types/FormSection.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
      */
35 35
     public function __construct(EEM_Form_Section $form_section_model)
36 36
     {
37
-        $this->setName($this->namespace . 'FormSection');
37
+        $this->setName($this->namespace.'FormSection');
38 38
         $this->setDescription(__('A form section', 'event_espresso'));
39 39
         $this->setIsCustomPostType(false);
40 40
 
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
             ),
57 57
             new GraphQLField(
58 58
                 'appliesTo',
59
-                $this->namespace . 'FormSectionAppliesToEnum',
59
+                $this->namespace.'FormSectionAppliesToEnum',
60 60
                 'appliesTo',
61 61
                 esc_html__('Form user type that this form section should be presented to.', 'event_espresso')
62 62
             ),
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
             ),
95 95
             new GraphQLField(
96 96
                 'status',
97
-                $this->namespace . 'FormStatusEnum',
97
+                $this->namespace.'FormStatusEnum',
98 98
                 'status',
99 99
                 esc_html__(
100 100
                     'Whether form section is active, archived, shared, trashed, or used as a default on new forms.',
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
     {
136 136
         // Register mutation to update an entity.
137 137
         register_graphql_mutation(
138
-            'update' . $this->name(),
138
+            'update'.$this->name(),
139 139
             [
140 140
                 'inputFields'         => $inputFields,
141 141
                 'outputFields'        => [
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
         );
150 150
         // Register mutation to delete an entity.
151 151
         register_graphql_mutation(
152
-            'delete' . $this->name(),
152
+            'delete'.$this->name(),
153 153
             [
154 154
                 'inputFields'         => [
155 155
                     'id' => $inputFields['id'],
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
                     lcfirst($this->name()) => [
159 159
                         'type'        => $this->name(),
160 160
                         'description' => esc_html__('The object before it was deleted', 'event_espresso'),
161
-                        'resolve'     => static function ($payload) {
161
+                        'resolve'     => static function($payload) {
162 162
                             $deleted = (object) $payload['deleted'];
163 163
 
164 164
                             return ! empty($deleted) ? $deleted : null;
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 
172 172
         // Register mutation to update an entity.
173 173
         register_graphql_mutation(
174
-            'create' . $this->name(),
174
+            'create'.$this->name(),
175 175
             [
176 176
                 'inputFields'         => $inputFields,
177 177
                 'outputFields'        => [
Please login to merge, or discard this patch.
Indentation   +179 added lines, -179 removed lines patch added patch discarded remove patch
@@ -27,191 +27,191 @@
 block discarded – undo
27 27
 class FormSection extends TypeBase
28 28
 {
29 29
 
30
-    /**
31
-     * FormSection constructor.
32
-     *
33
-     * @param EEM_Form_Section $form_section_model
34
-     */
35
-    public function __construct(EEM_Form_Section $form_section_model)
36
-    {
37
-        $this->setName($this->namespace . 'FormSection');
38
-        $this->setDescription(__('A form section', 'event_espresso'));
39
-        $this->setIsCustomPostType(false);
30
+	/**
31
+	 * FormSection constructor.
32
+	 *
33
+	 * @param EEM_Form_Section $form_section_model
34
+	 */
35
+	public function __construct(EEM_Form_Section $form_section_model)
36
+	{
37
+		$this->setName($this->namespace . 'FormSection');
38
+		$this->setDescription(__('A form section', 'event_espresso'));
39
+		$this->setIsCustomPostType(false);
40 40
 
41
-        parent::__construct($form_section_model);
42
-    }
41
+		parent::__construct($form_section_model);
42
+	}
43 43
 
44 44
 
45
-    /**
46
-     * @return GraphQLFieldInterface[]
47
-     */
48
-    public function getFields(): array
49
-    {
50
-        $fields = [
51
-            new GraphQLField(
52
-                'id',
53
-                ['non_null' => 'ID'],
54
-                null,
55
-                esc_html__('The globally unique ID for the object.', 'event_espresso')
56
-            ),
57
-            new GraphQLField(
58
-                'appliesTo',
59
-                $this->namespace . 'FormSectionAppliesToEnum',
60
-                'appliesTo',
61
-                esc_html__('Form user type that this form section should be presented to.', 'event_espresso')
62
-            ),
63
-            new GraphQLField(
64
-                'attributes',
65
-                'String',
66
-                'attributes',
67
-                esc_html__(
68
-                    'JSON string of HTML attributes, such as class, to be applied to this form section\'s container.',
69
-                    'event_espresso'
70
-                ),
71
-                [$this, 'toJson']
72
-            ),
73
-            new GraphQLField(
74
-                'belongsTo',
75
-                'String',
76
-                'belongsTo',
77
-                esc_html__('UUID or ID of related entity this form section belongs to.', 'event_espresso')
78
-            ),
79
-            new GraphQLOutputField(
80
-                'isActive',
81
-                'Boolean',
82
-                'isActive',
83
-                esc_html__('Flag indicating whether the section is active.', 'event_espresso')
84
-            ),
85
-            new GraphQLOutputField(
86
-                'isArchived',
87
-                'Boolean',
88
-                'isArchived',
89
-                esc_html__('Flag indicating whether the section is archived.', 'event_espresso')
90
-            ),
91
-            new GraphQLOutputField(
92
-                'isDefault',
93
-                'Boolean',
94
-                'isDefault',
95
-                esc_html__('Flag indicating whether the section is a default one.', 'event_espresso')
96
-            ),
97
-            new GraphQLOutputField(
98
-                'isShared',
99
-                'Boolean',
100
-                'isShared',
101
-                esc_html__('Flag indicating whether the section is a shared one.', 'event_espresso')
102
-            ),
103
-            new GraphQLOutputField(
104
-                'isTrashed',
105
-                'Boolean',
106
-                'isTrashed',
107
-                esc_html__('Flag indicating whether the section is trashed.', 'event_espresso')
108
-            ),
109
-            new GraphQLField(
110
-                'label',
111
-                'String',
112
-                'label',
113
-                esc_html__(
114
-                    'JSON string of properties pertaining to a form section\'s label.',
115
-                    'event_espresso'
116
-                ),
117
-                [$this, 'toJson']
118
-            ),
119
-            new GraphQLField(
120
-                'order',
121
-                'Int',
122
-                'order',
123
-                esc_html__('Order in which form section appears in a form.', 'event_espresso')
124
-            ),
125
-            new GraphQLField(
126
-                'status',
127
-                $this->namespace . 'FormStatusEnum',
128
-                'status',
129
-                esc_html__(
130
-                    'Whether form section is active, archived, shared, trashed, or used as a default on new forms.',
131
-                    'event_espresso'
132
-                )
133
-            ),
134
-            new GraphQLOutputField(
135
-                'wpUser',
136
-                'User',
137
-                null,
138
-                esc_html__('WP User that created this form section.', 'event_espresso')
139
-            ),
140
-            new GraphQLInputField(
141
-                'wpUser',
142
-                'ID',
143
-                null,
144
-                esc_html__('ID of the WP User that created the form section.', 'event_espresso')
145
-            ),
146
-        ];
45
+	/**
46
+	 * @return GraphQLFieldInterface[]
47
+	 */
48
+	public function getFields(): array
49
+	{
50
+		$fields = [
51
+			new GraphQLField(
52
+				'id',
53
+				['non_null' => 'ID'],
54
+				null,
55
+				esc_html__('The globally unique ID for the object.', 'event_espresso')
56
+			),
57
+			new GraphQLField(
58
+				'appliesTo',
59
+				$this->namespace . 'FormSectionAppliesToEnum',
60
+				'appliesTo',
61
+				esc_html__('Form user type that this form section should be presented to.', 'event_espresso')
62
+			),
63
+			new GraphQLField(
64
+				'attributes',
65
+				'String',
66
+				'attributes',
67
+				esc_html__(
68
+					'JSON string of HTML attributes, such as class, to be applied to this form section\'s container.',
69
+					'event_espresso'
70
+				),
71
+				[$this, 'toJson']
72
+			),
73
+			new GraphQLField(
74
+				'belongsTo',
75
+				'String',
76
+				'belongsTo',
77
+				esc_html__('UUID or ID of related entity this form section belongs to.', 'event_espresso')
78
+			),
79
+			new GraphQLOutputField(
80
+				'isActive',
81
+				'Boolean',
82
+				'isActive',
83
+				esc_html__('Flag indicating whether the section is active.', 'event_espresso')
84
+			),
85
+			new GraphQLOutputField(
86
+				'isArchived',
87
+				'Boolean',
88
+				'isArchived',
89
+				esc_html__('Flag indicating whether the section is archived.', 'event_espresso')
90
+			),
91
+			new GraphQLOutputField(
92
+				'isDefault',
93
+				'Boolean',
94
+				'isDefault',
95
+				esc_html__('Flag indicating whether the section is a default one.', 'event_espresso')
96
+			),
97
+			new GraphQLOutputField(
98
+				'isShared',
99
+				'Boolean',
100
+				'isShared',
101
+				esc_html__('Flag indicating whether the section is a shared one.', 'event_espresso')
102
+			),
103
+			new GraphQLOutputField(
104
+				'isTrashed',
105
+				'Boolean',
106
+				'isTrashed',
107
+				esc_html__('Flag indicating whether the section is trashed.', 'event_espresso')
108
+			),
109
+			new GraphQLField(
110
+				'label',
111
+				'String',
112
+				'label',
113
+				esc_html__(
114
+					'JSON string of properties pertaining to a form section\'s label.',
115
+					'event_espresso'
116
+				),
117
+				[$this, 'toJson']
118
+			),
119
+			new GraphQLField(
120
+				'order',
121
+				'Int',
122
+				'order',
123
+				esc_html__('Order in which form section appears in a form.', 'event_espresso')
124
+			),
125
+			new GraphQLField(
126
+				'status',
127
+				$this->namespace . 'FormStatusEnum',
128
+				'status',
129
+				esc_html__(
130
+					'Whether form section is active, archived, shared, trashed, or used as a default on new forms.',
131
+					'event_espresso'
132
+				)
133
+			),
134
+			new GraphQLOutputField(
135
+				'wpUser',
136
+				'User',
137
+				null,
138
+				esc_html__('WP User that created this form section.', 'event_espresso')
139
+			),
140
+			new GraphQLInputField(
141
+				'wpUser',
142
+				'ID',
143
+				null,
144
+				esc_html__('ID of the WP User that created the form section.', 'event_espresso')
145
+			),
146
+		];
147 147
 
148
-        return apply_filters(
149
-            'FHEE__EventEspresso_core_domain_services_graphql_types__form_section_fields',
150
-            $fields,
151
-            $this->name,
152
-            $this->model
153
-        );
154
-    }
148
+		return apply_filters(
149
+			'FHEE__EventEspresso_core_domain_services_graphql_types__form_section_fields',
150
+			$fields,
151
+			$this->name,
152
+			$this->model
153
+		);
154
+	}
155 155
 
156 156
 
157
-    /**
158
-     * @param array $inputFields The mutation input fields.
159
-     * @throws InvalidArgumentException
160
-     * @throws ReflectionException
161
-     * @throws Exception
162
-     * @since $VID:$
163
-     */
164
-    public function registerMutations(array $inputFields)
165
-    {
166
-        // Register mutation to update an entity.
167
-        register_graphql_mutation(
168
-            'update' . $this->name(),
169
-            [
170
-                'inputFields'         => $inputFields,
171
-                'outputFields'        => [
172
-                    lcfirst($this->name()) => [
173
-                        'type'    => $this->name(),
174
-                        'resolve' => [$this, 'resolveFromPayload'],
175
-                    ],
176
-                ],
177
-                'mutateAndGetPayload' => FormSectionUpdate::mutateAndGetPayload($this->model),
178
-            ]
179
-        );
180
-        // Register mutation to delete an entity.
181
-        register_graphql_mutation(
182
-            'delete' . $this->name(),
183
-            [
184
-                'inputFields'         => [
185
-                    'id' => $inputFields['id'],
186
-                ],
187
-                'outputFields'        => [
188
-                    lcfirst($this->name()) => [
189
-                        'type'        => $this->name(),
190
-                        'description' => esc_html__('The object before it was deleted', 'event_espresso'),
191
-                        'resolve'     => static function ($payload) {
192
-                            $deleted = (object) $payload['deleted'];
157
+	/**
158
+	 * @param array $inputFields The mutation input fields.
159
+	 * @throws InvalidArgumentException
160
+	 * @throws ReflectionException
161
+	 * @throws Exception
162
+	 * @since $VID:$
163
+	 */
164
+	public function registerMutations(array $inputFields)
165
+	{
166
+		// Register mutation to update an entity.
167
+		register_graphql_mutation(
168
+			'update' . $this->name(),
169
+			[
170
+				'inputFields'         => $inputFields,
171
+				'outputFields'        => [
172
+					lcfirst($this->name()) => [
173
+						'type'    => $this->name(),
174
+						'resolve' => [$this, 'resolveFromPayload'],
175
+					],
176
+				],
177
+				'mutateAndGetPayload' => FormSectionUpdate::mutateAndGetPayload($this->model),
178
+			]
179
+		);
180
+		// Register mutation to delete an entity.
181
+		register_graphql_mutation(
182
+			'delete' . $this->name(),
183
+			[
184
+				'inputFields'         => [
185
+					'id' => $inputFields['id'],
186
+				],
187
+				'outputFields'        => [
188
+					lcfirst($this->name()) => [
189
+						'type'        => $this->name(),
190
+						'description' => esc_html__('The object before it was deleted', 'event_espresso'),
191
+						'resolve'     => static function ($payload) {
192
+							$deleted = (object) $payload['deleted'];
193 193
 
194
-                            return ! empty($deleted) ? $deleted : null;
195
-                        },
196
-                    ],
197
-                ],
198
-                'mutateAndGetPayload' => FormSectionDelete::mutateAndGetPayload($this->model),
199
-            ]
200
-        );
194
+							return ! empty($deleted) ? $deleted : null;
195
+						},
196
+					],
197
+				],
198
+				'mutateAndGetPayload' => FormSectionDelete::mutateAndGetPayload($this->model),
199
+			]
200
+		);
201 201
 
202
-        // Register mutation to update an entity.
203
-        register_graphql_mutation(
204
-            'create' . $this->name(),
205
-            [
206
-                'inputFields'         => $inputFields,
207
-                'outputFields'        => [
208
-                    lcfirst($this->name()) => [
209
-                        'type'    => $this->name(),
210
-                        'resolve' => [$this, 'resolveFromPayload'],
211
-                    ],
212
-                ],
213
-                'mutateAndGetPayload' => FormSectionCreate::mutateAndGetPayload($this->model),
214
-            ]
215
-        );
216
-    }
202
+		// Register mutation to update an entity.
203
+		register_graphql_mutation(
204
+			'create' . $this->name(),
205
+			[
206
+				'inputFields'         => $inputFields,
207
+				'outputFields'        => [
208
+					lcfirst($this->name()) => [
209
+						'type'    => $this->name(),
210
+						'resolve' => [$this, 'resolveFromPayload'],
211
+					],
212
+				],
213
+				'mutateAndGetPayload' => FormSectionCreate::mutateAndGetPayload($this->model),
214
+			]
215
+		);
216
+	}
217 217
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6522 added lines, -6522 removed lines patch added patch discarded remove patch
@@ -40,6528 +40,6528 @@
 block discarded – undo
40 40
 abstract class EEM_Base extends EE_Base implements ResettableInterface
41 41
 {
42 42
 
43
-    /**
44
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
45
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
46
-     * They almost always WILL NOT, but it's not necessarily a requirement.
47
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
48
-     *
49
-     * @var boolean
50
-     */
51
-    private $_values_already_prepared_by_model_object = 0;
52
-
53
-    /**
54
-     * when $_values_already_prepared_by_model_object equals this, we assume
55
-     * the data is just like form input that needs to have the model fields'
56
-     * prepare_for_set and prepare_for_use_in_db called on it
57
-     */
58
-    const not_prepared_by_model_object = 0;
59
-
60
-    /**
61
-     * when $_values_already_prepared_by_model_object equals this, we
62
-     * assume this value is coming from a model object and doesn't need to have
63
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
64
-     */
65
-    const prepared_by_model_object = 1;
66
-
67
-    /**
68
-     * when $_values_already_prepared_by_model_object equals this, we assume
69
-     * the values are already to be used in the database (ie no processing is done
70
-     * on them by the model's fields)
71
-     */
72
-    const prepared_for_use_in_db = 2;
73
-
74
-
75
-    protected $singular_item = 'Item';
76
-
77
-    protected $plural_item   = 'Items';
78
-
79
-    /**
80
-     * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
81
-     */
82
-    protected $_tables;
83
-
84
-    /**
85
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
86
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
87
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
88
-     *
89
-     * @var EE_Model_Field_Base[][] $_fields
90
-     */
91
-    protected $_fields;
92
-
93
-    /**
94
-     * array of different kinds of relations
95
-     *
96
-     * @var EE_Model_Relation_Base[] $_model_relations
97
-     */
98
-    protected $_model_relations = [];
99
-
100
-    /**
101
-     * @var EE_Index[] $_indexes
102
-     */
103
-    protected $_indexes = array();
104
-
105
-    /**
106
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
107
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
108
-     * by setting the same columns as used in these queries in the query yourself.
109
-     *
110
-     * @var EE_Default_Where_Conditions
111
-     */
112
-    protected $_default_where_conditions_strategy;
113
-
114
-    /**
115
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
116
-     * This is particularly useful when you want something between 'none' and 'default'
117
-     *
118
-     * @var EE_Default_Where_Conditions
119
-     */
120
-    protected $_minimum_where_conditions_strategy;
121
-
122
-    /**
123
-     * String describing how to find the "owner" of this model's objects.
124
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
125
-     * But when there isn't, this indicates which related model, or transiently-related model,
126
-     * has the foreign key to the wp_users table.
127
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
128
-     * related to events, and events have a foreign key to wp_users.
129
-     * On EEM_Transaction, this would be 'Transaction.Event'
130
-     *
131
-     * @var string
132
-     */
133
-    protected $_model_chain_to_wp_user = '';
134
-
135
-    /**
136
-     * String describing how to find the model with a password controlling access to this model. This property has the
137
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
138
-     * This value is the path of models to follow to arrive at the model with the password field.
139
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
140
-     * model with a password that should affect reading this on the front-end.
141
-     * Eg this is an empty string for the Event model because it has a password.
142
-     * This is null for the Registration model, because its event's password has no bearing on whether
143
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
144
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
145
-     * should hide tickets for datetimes for events that have a password set.
146
-     * @var string |null
147
-     */
148
-    protected $model_chain_to_password = null;
149
-
150
-    /**
151
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
-     * don't need it (particularly CPT models)
153
-     *
154
-     * @var bool
155
-     */
156
-    protected $_ignore_where_strategy = false;
157
-
158
-    /**
159
-     * String used in caps relating to this model. Eg, if the caps relating to this
160
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
-     *
162
-     * @var string. If null it hasn't been initialized yet. If false then we
163
-     * have indicated capabilities don't apply to this
164
-     */
165
-    protected $_caps_slug = null;
166
-
167
-    /**
168
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
-     * and next-level keys are capability names, and each's value is a
170
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
-     * they specify which context to use (ie, frontend, backend, edit or delete)
172
-     * and then each capability in the corresponding sub-array that they're missing
173
-     * adds the where conditions onto the query.
174
-     *
175
-     * @var array
176
-     */
177
-    protected $_cap_restrictions = array(
178
-        self::caps_read       => array(),
179
-        self::caps_read_admin => array(),
180
-        self::caps_edit       => array(),
181
-        self::caps_delete     => array(),
182
-    );
183
-
184
-    /**
185
-     * Array defining which cap restriction generators to use to create default
186
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
187
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
-     * automatically set this to false (not just null).
190
-     *
191
-     * @var EE_Restriction_Generator_Base[]
192
-     */
193
-    protected $_cap_restriction_generators = array();
194
-
195
-    /**
196
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
-     */
198
-    const caps_read       = 'read';
199
-
200
-    const caps_read_admin = 'read_admin';
201
-
202
-    const caps_edit       = 'edit';
203
-
204
-    const caps_delete     = 'delete';
205
-
206
-    /**
207
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
-     * maps to 'read' because when looking for relevant permissions we're going to use
210
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
211
-     *
212
-     * @var array
213
-     */
214
-    protected $_cap_contexts_to_cap_action_map = array(
215
-        self::caps_read       => 'read',
216
-        self::caps_read_admin => 'read',
217
-        self::caps_edit       => 'edit',
218
-        self::caps_delete     => 'delete',
219
-    );
220
-
221
-    /**
222
-     * Timezone
223
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
-     * EE_Datetime_Field data type will have access to it.
227
-     *
228
-     * @var string
229
-     */
230
-    protected $_timezone;
231
-
232
-
233
-    /**
234
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
-     * multisite.
236
-     *
237
-     * @var int
238
-     */
239
-    protected static $_model_query_blog_id;
240
-
241
-    /**
242
-     * A copy of _fields, except the array keys are the model names pointed to by
243
-     * the field
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cache_foreign_key_to_fields = array();
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, indexed by their name
251
-     *
252
-     * @var EE_Model_Field_Base[]
253
-     */
254
-    private $_cached_fields = null;
255
-
256
-    /**
257
-     * Cached list of all the fields on the model, except those that are
258
-     * marked as only pertinent to the database
259
-     *
260
-     * @var EE_Model_Field_Base[]
261
-     */
262
-    private $_cached_fields_non_db_only = null;
263
-
264
-    /**
265
-     * A cached reference to the primary key for quick lookup
266
-     *
267
-     * @var EE_Model_Field_Base
268
-     */
269
-    private $_primary_key_field = null;
270
-
271
-    /**
272
-     * Flag indicating whether this model has a primary key or not
273
-     *
274
-     * @var boolean
275
-     */
276
-    protected $_has_primary_key_field = null;
277
-
278
-    /**
279
-     * array in the format:  [ FK alias => full PK ]
280
-     * where keys are local column name aliases for foreign keys
281
-     * and values are the fully qualified column name for the primary key they represent
282
-     *  ex:
283
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
-     *
285
-     * @var array $foreign_key_aliases
286
-     */
287
-    protected $foreign_key_aliases = [];
288
-
289
-    /**
290
-     * Whether or not this model is based off a table in WP core only (CPTs should set
291
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
-     * This should be true for models that deal with data that should exist independent of EE.
293
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
295
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
297
-     * @var boolean
298
-     */
299
-    protected $_wp_core_model = false;
300
-
301
-    /**
302
-     * @var bool stores whether this model has a password field or not.
303
-     * null until initialized by hasPasswordField()
304
-     */
305
-    protected $has_password_field;
306
-
307
-    /**
308
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
309
-     */
310
-    protected $password_field;
311
-
312
-    /**
313
-     *    List of valid operators that can be used for querying.
314
-     * The keys are all operators we'll accept, the values are the real SQL
315
-     * operators used
316
-     *
317
-     * @var array
318
-     */
319
-    protected $_valid_operators = array(
320
-        '='           => '=',
321
-        '<='          => '<=',
322
-        '<'           => '<',
323
-        '>='          => '>=',
324
-        '>'           => '>',
325
-        '!='          => '!=',
326
-        'LIKE'        => 'LIKE',
327
-        'like'        => 'LIKE',
328
-        'NOT_LIKE'    => 'NOT LIKE',
329
-        'not_like'    => 'NOT LIKE',
330
-        'NOT LIKE'    => 'NOT LIKE',
331
-        'not like'    => 'NOT LIKE',
332
-        'IN'          => 'IN',
333
-        'in'          => 'IN',
334
-        'NOT_IN'      => 'NOT IN',
335
-        'not_in'      => 'NOT IN',
336
-        'NOT IN'      => 'NOT IN',
337
-        'not in'      => 'NOT IN',
338
-        'between'     => 'BETWEEN',
339
-        'BETWEEN'     => 'BETWEEN',
340
-        'IS_NOT_NULL' => 'IS NOT NULL',
341
-        'is_not_null' => 'IS NOT NULL',
342
-        'IS NOT NULL' => 'IS NOT NULL',
343
-        'is not null' => 'IS NOT NULL',
344
-        'IS_NULL'     => 'IS NULL',
345
-        'is_null'     => 'IS NULL',
346
-        'IS NULL'     => 'IS NULL',
347
-        'is null'     => 'IS NULL',
348
-        'REGEXP'      => 'REGEXP',
349
-        'regexp'      => 'REGEXP',
350
-        'NOT_REGEXP'  => 'NOT REGEXP',
351
-        'not_regexp'  => 'NOT REGEXP',
352
-        'NOT REGEXP'  => 'NOT REGEXP',
353
-        'not regexp'  => 'NOT REGEXP',
354
-    );
355
-
356
-    /**
357
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
358
-     *
359
-     * @var array
360
-     */
361
-    protected $_in_style_operators = array('IN', 'NOT IN');
362
-
363
-    /**
364
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
365
-     * '12-31-2012'"
366
-     *
367
-     * @var array
368
-     */
369
-    protected $_between_style_operators = array('BETWEEN');
370
-
371
-    /**
372
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
373
-     * @var array
374
-     */
375
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
376
-    /**
377
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
378
-     * on a join table.
379
-     *
380
-     * @var array
381
-     */
382
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
383
-
384
-    /**
385
-     * Allowed values for $query_params['order'] for ordering in queries
386
-     *
387
-     * @var array
388
-     */
389
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
390
-
391
-    /**
392
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
393
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
394
-     *
395
-     * @var array
396
-     */
397
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
398
-
399
-    /**
400
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
401
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
402
-     *
403
-     * @var array
404
-     */
405
-    private $_allowed_query_params = array(
406
-        0,
407
-        'limit',
408
-        'order_by',
409
-        'group_by',
410
-        'having',
411
-        'force_join',
412
-        'order',
413
-        'on_join_limit',
414
-        'default_where_conditions',
415
-        'caps',
416
-        'extra_selects',
417
-        'exclude_protected',
418
-    );
419
-
420
-    /**
421
-     * All the data types that can be used in $wpdb->prepare statements.
422
-     *
423
-     * @var array
424
-     */
425
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
426
-
427
-    /**
428
-     * @var EE_Registry $EE
429
-     */
430
-    protected $EE = null;
431
-
432
-
433
-    /**
434
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
435
-     *
436
-     * @var int
437
-     */
438
-    protected $_show_next_x_db_queries = 0;
439
-
440
-    /**
441
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
442
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
443
-     * WHERE, GROUP_BY, etc.
444
-     *
445
-     * @var CustomSelects
446
-     */
447
-    protected $_custom_selections = array();
448
-
449
-    /**
450
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
451
-     * caches every model object we've fetched from the DB on this request
452
-     *
453
-     * @var array
454
-     */
455
-    protected $_entity_map;
456
-
457
-    /**
458
-     * @var LoaderInterface
459
-     */
460
-    private static $loader;
461
-
462
-    /**
463
-     * @var Mirror
464
-     */
465
-    private static $mirror;
466
-
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
-    /**
548
-     * About all child constructors:
549
-     * they should define the _tables, _fields and _model_relations arrays.
550
-     * Should ALWAYS be called after child constructor.
551
-     * In order to make the child constructors to be as simple as possible, this parent constructor
552
-     * finalizes constructing all the object's attributes.
553
-     * Generally, rather than requiring a child to code
554
-     * $this->_tables = array(
555
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
556
-     *        ...);
557
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
558
-     * each EE_Table has a function to set the table's alias after the constructor, using
559
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
560
-     * do something similar.
561
-     *
562
-     * @param null $timezone
563
-     * @throws EE_Error
564
-     */
565
-    protected function __construct($timezone = null)
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
-                    __(
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
-                /** @var $table_obj EE_Secondary_Table */
597
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
598
-            }
599
-        }
600
-        /**
601
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
602
-         * EE_Register_Model_Extension
603
-         *
604
-         * @param EE_Model_Field_Base[] $_fields
605
-         */
606
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
607
-        $this->_invalidate_field_caches();
608
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
609
-            if (! array_key_exists($table_alias, $this->_tables)) {
610
-                throw new EE_Error(sprintf(__(
611
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
612
-                    'event_espresso'
613
-                ), $table_alias, implode(",", $this->_fields)));
614
-            }
615
-            foreach ($fields_for_table as $field_name => $field_obj) {
616
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
617
-                // primary key field base has a slightly different _construct_finalize
618
-                /** @var $field_obj EE_Model_Field_Base */
619
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
620
-            }
621
-        }
622
-        // everything is related to Extra_Meta
623
-        if (get_class($this) !== 'EEM_Extra_Meta') {
624
-            // make extra meta related to everything, but don't block deleting things just
625
-            // because they have related extra meta info. For now just orphan those extra meta
626
-            // in the future we should automatically delete them
627
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
628
-        }
629
-        // and change logs
630
-        if (get_class($this) !== 'EEM_Change_Log') {
631
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
632
-        }
633
-        /**
634
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
635
-         * EE_Register_Model_Extension
636
-         *
637
-         * @param EE_Model_Relation_Base[] $_model_relations
638
-         */
639
-        $this->_model_relations = (array) apply_filters(
640
-            'FHEE__' . get_class($this) . '__construct__model_relations',
641
-            $this->_model_relations
642
-        );
643
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
644
-            /** @var $relation_obj EE_Model_Relation_Base */
645
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
646
-        }
647
-        foreach ($this->_indexes as $index_name => $index_obj) {
648
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
649
-        }
650
-        $this->set_timezone($timezone);
651
-        // finalize default where condition strategy, or set default
652
-        if (! $this->_default_where_conditions_strategy) {
653
-            // nothing was set during child constructor, so set default
654
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
655
-        }
656
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
657
-        if (! $this->_minimum_where_conditions_strategy) {
658
-            // nothing was set during child constructor, so set default
659
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
660
-        }
661
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
662
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
663
-        // to indicate to NOT set it, set it to the logical default
664
-        if ($this->_caps_slug === null) {
665
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
666
-        }
667
-        // initialize the standard cap restriction generators if none were specified by the child constructor
668
-        if (is_array($this->_cap_restriction_generators)) {
669
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
670
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
671
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
672
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
673
-                        new EE_Restriction_Generator_Protected(),
674
-                        $cap_context,
675
-                        $this
676
-                    );
677
-                }
678
-            }
679
-        }
680
-        // if there are cap restriction generators, use them to make the default cap restrictions
681
-        if (is_array($this->_cap_restriction_generators)) {
682
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
683
-                if (! $generator_object) {
684
-                    continue;
685
-                }
686
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
687
-                    throw new EE_Error(
688
-                        sprintf(
689
-                            __(
690
-                                '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.',
691
-                                'event_espresso'
692
-                            ),
693
-                            $context,
694
-                            $this->get_this_model_name()
695
-                        )
696
-                    );
697
-                }
698
-                $action = $this->cap_action_for_context($context);
699
-                if (! $generator_object->construction_finalized()) {
700
-                    $generator_object->_construct_finalize($this, $action);
701
-                }
702
-            }
703
-        }
704
-        do_action('AHEE__' . get_class($this) . '__construct__end');
705
-    }
706
-
707
-
708
-    /**
709
-     * @return LoaderInterface
710
-     * @throws InvalidArgumentException
711
-     * @throws InvalidDataTypeException
712
-     * @throws InvalidInterfaceException
713
-     */
714
-    protected static function getLoader(): LoaderInterface
715
-    {
716
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
717
-            EEM_Base::$loader = LoaderFactory::getLoader();
718
-        }
719
-        return EEM_Base::$loader;
720
-    }
721
-
722
-
723
-    /**
724
-     * @return Mirror
725
-     * @since   $VID:$
726
-     */
727
-    private static function getMirror(): Mirror
728
-    {
729
-        if (! EEM_Base::$mirror instanceof Mirror) {
730
-            EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
731
-        }
732
-        return EEM_Base::$mirror;
733
-    }
734
-
735
-
736
-    /**
737
-     * @param string $model_class_Name
738
-     * @param string $timezone
739
-     * @return array
740
-     * @throws ReflectionException
741
-     * @since   $VID:$
742
-     */
743
-    private static function getModelArguments(string $model_class_Name, string $timezone): array
744
-    {
745
-        $arguments = [$timezone];
746
-        $params    = EEM_Base::getMirror()->getParameters($model_class_Name);
747
-        if (count($params) > 1) {
748
-            if ($params[1]->getName() === 'model_field_factory') {
749
-                $arguments = [
750
-                    $timezone,
751
-                    EEM_Base::getLoader()->getShared(ModelFieldFactory::class)
752
-                ];
753
-            } elseif ($model_class_Name === 'EEM_Form_Section') {
754
-                $arguments = [
755
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
756
-                    $timezone
757
-                ];
758
-            } elseif ($model_class_Name === 'EEM_Form_Element') {
759
-                $arguments = [
760
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
761
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
762
-                    $timezone,
763
-                ];
764
-            }
765
-        }
766
-        return $arguments;
767
-    }
768
-
769
-
770
-    /**
771
-     * This function is a singleton method used to instantiate the Espresso_model object
772
-     *
773
-     * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
774
-     *                                (and any incoming timezone data that gets saved).
775
-     *                                Note this just sends the timezone info to the date time model field objects.
776
-     *                                Default is NULL
777
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
778
-     * @return static (as in the concrete child class)
779
-     * @throws EE_Error
780
-     * @throws ReflectionException
781
-     */
782
-    public static function instance($timezone = null)
783
-    {
784
-        // check if instance of Espresso_model already exists
785
-        if (! static::$_instance instanceof static) {
786
-            $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
787
-            $model = new static(...$arguments);
788
-            EEM_Base::getLoader()->share(static::class, $model, $arguments);
789
-            static::$_instance = $model;
790
-        }
791
-        // we might have a timezone set, let set_timezone decide what to do with it
792
-        if ($timezone) {
793
-            static::$_instance->set_timezone($timezone);
794
-        }
795
-        // Espresso_model object
796
-        return static::$_instance;
797
-    }
798
-
799
-
800
-
801
-    /**
802
-     * resets the model and returns it
803
-     *
804
-     * @param string|null $timezone
805
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
806
-     * all its properties reset; if it wasn't instantiated, returns null)
807
-     * @throws EE_Error
808
-     * @throws ReflectionException
809
-     * @throws InvalidArgumentException
810
-     * @throws InvalidDataTypeException
811
-     * @throws InvalidInterfaceException
812
-     */
813
-    public static function reset($timezone = null)
814
-    {
815
-        if (! static::$_instance instanceof EEM_Base) {
816
-            return null;
817
-        }
818
-        // Let's NOT swap out the current instance for a new one
819
-        // because if someone has a reference to it, we can't remove their reference.
820
-        // It's best to keep using the same reference but change the original object instead,
821
-        // so reset all its properties to their original values as defined in the class.
822
-        $static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
823
-        foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
824
-            // don't set instance to null like it was originally,
825
-            // but it's static anyways, and we're ignoring static properties (for now at least)
826
-            if (! isset($static_properties[ $property ])) {
827
-                static::$_instance->{$property} = $value;
828
-            }
829
-        }
830
-        // and then directly call its constructor again, like we would if we were creating a new one
831
-        $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
832
-        static::$_instance->__construct(...$arguments);
833
-        return self::instance();
834
-    }
835
-
836
-
837
-    /**
838
-     * Used to set the $_model_query_blog_id static property.
839
-     *
840
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
841
-     *                      value for get_current_blog_id() will be used.
842
-     */
843
-    public static function set_model_query_blog_id($blog_id = 0)
844
-    {
845
-        EEM_Base::$_model_query_blog_id = $blog_id > 0
846
-            ? (int) $blog_id
847
-            : get_current_blog_id();
848
-    }
849
-
850
-
851
-    /**
852
-     * Returns whatever is set as the internal $model_query_blog_id.
853
-     *
854
-     * @return int
855
-     */
856
-    public static function get_model_query_blog_id()
857
-    {
858
-        return EEM_Base::$_model_query_blog_id;
859
-    }
860
-
861
-
862
-
863
-    /**
864
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
865
-     *
866
-     * @param  boolean $translated return localized strings or JUST the array.
867
-     * @return array
868
-     * @throws EE_Error
869
-     * @throws InvalidArgumentException
870
-     * @throws InvalidDataTypeException
871
-     * @throws InvalidInterfaceException
872
-     */
873
-    public function status_array($translated = false)
874
-    {
875
-        if (! array_key_exists('Status', $this->_model_relations)) {
876
-            return array();
877
-        }
878
-        $model_name = $this->get_this_model_name();
879
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
880
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
881
-        $status_array = array();
882
-        foreach ($stati as $status) {
883
-            $status_array[ $status->ID() ] = $status->get('STS_code');
884
-        }
885
-        return $translated
886
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
887
-            : $status_array;
888
-    }
889
-
890
-
891
-
892
-    /**
893
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
894
-     *
895
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
896
-     *                             or if you have the development copy of EE you can view this at the path:
897
-     *                             /docs/G--Model-System/model-query-params.md
898
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
899
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
900
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
901
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
902
-     *                                        array( array(
903
-     *                                        'OR'=>array(
904
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
905
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
906
-     *                                        )
907
-     *                                        ),
908
-     *                                        'limit'=>10,
909
-     *                                        'group_by'=>'TXN_ID'
910
-     *                                        ));
911
-     *                                        get all the answers to the question titled "shirt size" for event with id
912
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
913
-     *                                        'Question.QST_display_text'=>'shirt size',
914
-     *                                        'Registration.Event.EVT_ID'=>12
915
-     *                                        ),
916
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
917
-     *                                        ));
918
-     * @throws EE_Error
919
-     */
920
-    public function get_all($query_params = array())
921
-    {
922
-        if (
923
-            isset($query_params['limit'])
924
-            && ! isset($query_params['group_by'])
925
-        ) {
926
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
927
-        }
928
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
929
-    }
930
-
931
-
932
-
933
-    /**
934
-     * Modifies the query parameters so we only get back model objects
935
-     * that "belong" to the current user
936
-     *
937
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
938
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
939
-     */
940
-    public function alter_query_params_to_only_include_mine($query_params = array())
941
-    {
942
-        $wp_user_field_name = $this->wp_user_field_name();
943
-        if ($wp_user_field_name) {
944
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
945
-        }
946
-        return $query_params;
947
-    }
948
-
949
-
950
-
951
-    /**
952
-     * Returns the name of the field's name that points to the WP_User table
953
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
954
-     * foreign key to the WP_User table)
955
-     *
956
-     * @return string|boolean string on success, boolean false when there is no
957
-     * foreign key to the WP_User table
958
-     */
959
-    public function wp_user_field_name()
960
-    {
961
-        try {
962
-            if (! empty($this->_model_chain_to_wp_user)) {
963
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
964
-                $last_model_name = end($models_to_follow_to_wp_users);
965
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
966
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
967
-            } else {
968
-                $model_with_fk_to_wp_users = $this;
969
-                $model_chain_to_wp_user = '';
970
-            }
971
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
972
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
973
-        } catch (EE_Error $e) {
974
-            return false;
975
-        }
976
-    }
977
-
978
-
979
-
980
-    /**
981
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
982
-     * (or transiently-related model) has a foreign key to the wp_users table;
983
-     * useful for finding if model objects of this type are 'owned' by the current user.
984
-     * This is an empty string when the foreign key is on this model and when it isn't,
985
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
986
-     * (or transiently-related model)
987
-     *
988
-     * @return string
989
-     */
990
-    public function model_chain_to_wp_user()
991
-    {
992
-        return $this->_model_chain_to_wp_user;
993
-    }
994
-
995
-
996
-
997
-    /**
998
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
999
-     * like how registrations don't have a foreign key to wp_users, but the
1000
-     * events they are for are), or is unrelated to wp users.
1001
-     * generally available
1002
-     *
1003
-     * @return boolean
1004
-     */
1005
-    public function is_owned()
1006
-    {
1007
-        if ($this->model_chain_to_wp_user()) {
1008
-            return true;
1009
-        }
1010
-        try {
1011
-            $this->get_foreign_key_to('WP_User');
1012
-            return true;
1013
-        } catch (EE_Error $e) {
1014
-            return false;
1015
-        }
1016
-    }
1017
-
1018
-
1019
-    /**
1020
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1021
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1022
-     * the model)
1023
-     *
1024
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1025
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1026
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1027
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1028
-     *                                  override this and set the select to "*", or a specific column name, like
1029
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1030
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1031
-     *                                  the aliases used to refer to this selection, and values are to be
1032
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1033
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1034
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1035
-     * @throws EE_Error
1036
-     * @throws InvalidArgumentException
1037
-     */
1038
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1039
-    {
1040
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1041
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1042
-        $select_expressions = $columns_to_select === null
1043
-            ? $this->_construct_default_select_sql($model_query_info)
1044
-            : '';
1045
-        if ($this->_custom_selections instanceof CustomSelects) {
1046
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1047
-            $select_expressions .= $select_expressions
1048
-                ? ', ' . $custom_expressions
1049
-                : $custom_expressions;
1050
-        }
1051
-
1052
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1053
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1054
-    }
1055
-
1056
-
1057
-    /**
1058
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1059
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1060
-     * method of including extra select information.
1061
-     *
1062
-     * @param array             $query_params
1063
-     * @param null|array|string $columns_to_select
1064
-     * @return null|CustomSelects
1065
-     * @throws InvalidArgumentException
1066
-     */
1067
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1068
-    {
1069
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1070
-            return null;
1071
-        }
1072
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1073
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1074
-        return new CustomSelects($selects);
1075
-    }
1076
-
1077
-
1078
-
1079
-    /**
1080
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1081
-     * but you can use the model query params to more easily
1082
-     * take care of joins, field preparation etc.
1083
-     *
1084
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1085
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1086
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1087
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1088
-     *                                  override this and set the select to "*", or a specific column name, like
1089
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1090
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1091
-     *                                  the aliases used to refer to this selection, and values are to be
1092
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1093
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1094
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1095
-     * @throws EE_Error
1096
-     */
1097
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1098
-    {
1099
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1100
-    }
1101
-
1102
-
1103
-
1104
-    /**
1105
-     * For creating a custom select statement
1106
-     *
1107
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1108
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1109
-     *                                 SQL, and 1=>is the datatype
1110
-     * @throws EE_Error
1111
-     * @return string
1112
-     */
1113
-    private function _construct_select_from_input($columns_to_select)
1114
-    {
1115
-        if (is_array($columns_to_select)) {
1116
-            $select_sql_array = array();
1117
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1118
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1119
-                    throw new EE_Error(
1120
-                        sprintf(
1121
-                            __(
1122
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1123
-                                'event_espresso'
1124
-                            ),
1125
-                            $selection_and_datatype,
1126
-                            $alias
1127
-                        )
1128
-                    );
1129
-                }
1130
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1131
-                    throw new EE_Error(
1132
-                        sprintf(
1133
-                            esc_html__(
1134
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1135
-                                'event_espresso'
1136
-                            ),
1137
-                            $selection_and_datatype[1],
1138
-                            $selection_and_datatype[0],
1139
-                            $alias,
1140
-                            implode(', ', $this->_valid_wpdb_data_types)
1141
-                        )
1142
-                    );
1143
-                }
1144
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1145
-            }
1146
-            $columns_to_select_string = implode(', ', $select_sql_array);
1147
-        } else {
1148
-            $columns_to_select_string = $columns_to_select;
1149
-        }
1150
-        return $columns_to_select_string;
1151
-    }
1152
-
1153
-
1154
-
1155
-    /**
1156
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1157
-     *
1158
-     * @return string
1159
-     * @throws EE_Error
1160
-     */
1161
-    public function primary_key_name()
1162
-    {
1163
-        return $this->get_primary_key_field()->get_name();
1164
-    }
1165
-
1166
-
1167
-    /**
1168
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1169
-     * If there is no primary key on this model, $id is treated as primary key string
1170
-     *
1171
-     * @param mixed $id int or string, depending on the type of the model's primary key
1172
-     * @return EE_Base_Class
1173
-     * @throws EE_Error
1174
-     */
1175
-    public function get_one_by_ID($id)
1176
-    {
1177
-        if ($this->get_from_entity_map($id)) {
1178
-            return $this->get_from_entity_map($id);
1179
-        }
1180
-        $model_object = $this->get_one(
1181
-            $this->alter_query_params_to_restrict_by_ID(
1182
-                $id,
1183
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1184
-            )
1185
-        );
1186
-        $className = $this->_get_class_name();
1187
-        if ($model_object instanceof $className) {
1188
-            // make sure valid objects get added to the entity map
1189
-            // so that the next call to this method doesn't trigger another trip to the db
1190
-            $this->add_to_entity_map($model_object);
1191
-        }
1192
-        return $model_object;
1193
-    }
1194
-
1195
-
1196
-
1197
-    /**
1198
-     * Alters query parameters to only get items with this ID are returned.
1199
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1200
-     * or could just be a simple primary key ID
1201
-     *
1202
-     * @param int   $id
1203
-     * @param array $query_params
1204
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1205
-     * @throws EE_Error
1206
-     */
1207
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1208
-    {
1209
-        if (! isset($query_params[0])) {
1210
-            $query_params[0] = array();
1211
-        }
1212
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1213
-        if ($conditions_from_id === null) {
1214
-            $query_params[0][ $this->primary_key_name() ] = $id;
1215
-        } else {
1216
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1217
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1218
-        }
1219
-        return $query_params;
1220
-    }
1221
-
1222
-
1223
-
1224
-    /**
1225
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1226
-     * array. If no item is found, null is returned.
1227
-     *
1228
-     * @param array $query_params like EEM_Base's $query_params variable.
1229
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1230
-     * @throws EE_Error
1231
-     */
1232
-    public function get_one($query_params = array())
1233
-    {
1234
-        if (! is_array($query_params)) {
1235
-            EE_Error::doing_it_wrong(
1236
-                'EEM_Base::get_one',
1237
-                sprintf(
1238
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1239
-                    gettype($query_params)
1240
-                ),
1241
-                '4.6.0'
1242
-            );
1243
-            $query_params = array();
1244
-        }
1245
-        $query_params['limit'] = 1;
1246
-        $items = $this->get_all($query_params);
1247
-        if (empty($items)) {
1248
-            return null;
1249
-        }
1250
-        return array_shift($items);
1251
-    }
1252
-
1253
-
1254
-
1255
-    /**
1256
-     * Returns the next x number of items in sequence from the given value as
1257
-     * found in the database matching the given query conditions.
1258
-     *
1259
-     * @param mixed $current_field_value    Value used for the reference point.
1260
-     * @param null  $field_to_order_by      What field is used for the
1261
-     *                                      reference point.
1262
-     * @param int   $limit                  How many to return.
1263
-     * @param array $query_params           Extra conditions on the query.
1264
-     * @param null  $columns_to_select      If left null, then an array of
1265
-     *                                      EE_Base_Class objects is returned,
1266
-     *                                      otherwise you can indicate just the
1267
-     *                                      columns you want returned.
1268
-     * @return EE_Base_Class[]|array
1269
-     * @throws EE_Error
1270
-     */
1271
-    public function next_x(
1272
-        $current_field_value,
1273
-        $field_to_order_by = null,
1274
-        $limit = 1,
1275
-        $query_params = array(),
1276
-        $columns_to_select = null
1277
-    ) {
1278
-        return $this->_get_consecutive(
1279
-            $current_field_value,
1280
-            '>',
1281
-            $field_to_order_by,
1282
-            $limit,
1283
-            $query_params,
1284
-            $columns_to_select
1285
-        );
1286
-    }
1287
-
1288
-
1289
-
1290
-    /**
1291
-     * Returns the previous x number of items in sequence from the given value
1292
-     * as found in the database matching the given query conditions.
1293
-     *
1294
-     * @param mixed $current_field_value    Value used for the reference point.
1295
-     * @param null  $field_to_order_by      What field is used for the
1296
-     *                                      reference point.
1297
-     * @param int   $limit                  How many to return.
1298
-     * @param array $query_params           Extra conditions on the query.
1299
-     * @param null  $columns_to_select      If left null, then an array of
1300
-     *                                      EE_Base_Class objects is returned,
1301
-     *                                      otherwise you can indicate just the
1302
-     *                                      columns you want returned.
1303
-     * @return EE_Base_Class[]|array
1304
-     * @throws EE_Error
1305
-     */
1306
-    public function previous_x(
1307
-        $current_field_value,
1308
-        $field_to_order_by = null,
1309
-        $limit = 1,
1310
-        $query_params = array(),
1311
-        $columns_to_select = null
1312
-    ) {
1313
-        return $this->_get_consecutive(
1314
-            $current_field_value,
1315
-            '<',
1316
-            $field_to_order_by,
1317
-            $limit,
1318
-            $query_params,
1319
-            $columns_to_select
1320
-        );
1321
-    }
1322
-
1323
-
1324
-
1325
-    /**
1326
-     * Returns the next item in sequence from the given value as found in the
1327
-     * database matching the given query conditions.
1328
-     *
1329
-     * @param mixed $current_field_value    Value used for the reference point.
1330
-     * @param null  $field_to_order_by      What field is used for the
1331
-     *                                      reference point.
1332
-     * @param array $query_params           Extra conditions on the query.
1333
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1334
-     *                                      object is returned, otherwise you
1335
-     *                                      can indicate just the columns you
1336
-     *                                      want and a single array indexed by
1337
-     *                                      the columns will be returned.
1338
-     * @return EE_Base_Class|null|array()
1339
-     * @throws EE_Error
1340
-     */
1341
-    public function next(
1342
-        $current_field_value,
1343
-        $field_to_order_by = null,
1344
-        $query_params = array(),
1345
-        $columns_to_select = null
1346
-    ) {
1347
-        $results = $this->_get_consecutive(
1348
-            $current_field_value,
1349
-            '>',
1350
-            $field_to_order_by,
1351
-            1,
1352
-            $query_params,
1353
-            $columns_to_select
1354
-        );
1355
-        return empty($results) ? null : reset($results);
1356
-    }
1357
-
1358
-
1359
-
1360
-    /**
1361
-     * Returns the previous item in sequence from the given value as found in
1362
-     * the database matching the given query conditions.
1363
-     *
1364
-     * @param mixed $current_field_value    Value used for the reference point.
1365
-     * @param null  $field_to_order_by      What field is used for the
1366
-     *                                      reference point.
1367
-     * @param array $query_params           Extra conditions on the query.
1368
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1369
-     *                                      object is returned, otherwise you
1370
-     *                                      can indicate just the columns you
1371
-     *                                      want and a single array indexed by
1372
-     *                                      the columns will be returned.
1373
-     * @return EE_Base_Class|null|array()
1374
-     * @throws EE_Error
1375
-     */
1376
-    public function previous(
1377
-        $current_field_value,
1378
-        $field_to_order_by = null,
1379
-        $query_params = array(),
1380
-        $columns_to_select = null
1381
-    ) {
1382
-        $results = $this->_get_consecutive(
1383
-            $current_field_value,
1384
-            '<',
1385
-            $field_to_order_by,
1386
-            1,
1387
-            $query_params,
1388
-            $columns_to_select
1389
-        );
1390
-        return empty($results) ? null : reset($results);
1391
-    }
1392
-
1393
-
1394
-
1395
-    /**
1396
-     * Returns the a consecutive number of items in sequence from the given
1397
-     * value as found in the database matching the given query conditions.
1398
-     *
1399
-     * @param mixed  $current_field_value   Value used for the reference point.
1400
-     * @param string $operand               What operand is used for the sequence.
1401
-     * @param string $field_to_order_by     What field is used for the reference point.
1402
-     * @param int    $limit                 How many to return.
1403
-     * @param array  $query_params          Extra conditions on the query.
1404
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1405
-     *                                      otherwise you can indicate just the columns you want returned.
1406
-     * @return EE_Base_Class[]|array
1407
-     * @throws EE_Error
1408
-     */
1409
-    protected function _get_consecutive(
1410
-        $current_field_value,
1411
-        $operand = '>',
1412
-        $field_to_order_by = null,
1413
-        $limit = 1,
1414
-        $query_params = array(),
1415
-        $columns_to_select = null
1416
-    ) {
1417
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1418
-        if (empty($field_to_order_by)) {
1419
-            if ($this->has_primary_key_field()) {
1420
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1421
-            } else {
1422
-                if (WP_DEBUG) {
1423
-                    throw new EE_Error(__(
1424
-                        '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).',
1425
-                        'event_espresso'
1426
-                    ));
1427
-                }
1428
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1429
-                return array();
1430
-            }
1431
-        }
1432
-        if (! is_array($query_params)) {
1433
-            EE_Error::doing_it_wrong(
1434
-                'EEM_Base::_get_consecutive',
1435
-                sprintf(
1436
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1437
-                    gettype($query_params)
1438
-                ),
1439
-                '4.6.0'
1440
-            );
1441
-            $query_params = array();
1442
-        }
1443
-        // let's add the where query param for consecutive look up.
1444
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1445
-        $query_params['limit'] = $limit;
1446
-        // set direction
1447
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1448
-        $query_params['order_by'] = $operand === '>'
1449
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1450
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1451
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1452
-        if (empty($columns_to_select)) {
1453
-            return $this->get_all($query_params);
1454
-        }
1455
-        // getting just the fields
1456
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1457
-    }
1458
-
1459
-
1460
-
1461
-    /**
1462
-     * This sets the _timezone property after model object has been instantiated.
1463
-     *
1464
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1465
-     */
1466
-    public function set_timezone($timezone)
1467
-    {
1468
-        if ($timezone !== null) {
1469
-            $this->_timezone = $timezone;
1470
-        }
1471
-        // note we need to loop through relations and set the timezone on those objects as well.
1472
-        foreach ($this->_model_relations as $relation) {
1473
-            $relation->set_timezone($timezone);
1474
-        }
1475
-        // and finally we do the same for any datetime fields
1476
-        foreach ($this->_fields as $field) {
1477
-            if ($field instanceof EE_Datetime_Field) {
1478
-                $field->set_timezone($timezone);
1479
-            }
1480
-        }
1481
-    }
1482
-
1483
-
1484
-
1485
-    /**
1486
-     * This just returns whatever is set for the current timezone.
1487
-     *
1488
-     * @access public
1489
-     * @return string
1490
-     */
1491
-    public function get_timezone()
1492
-    {
1493
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1494
-        if (empty($this->_timezone)) {
1495
-            foreach ($this->_fields as $field) {
1496
-                if ($field instanceof EE_Datetime_Field) {
1497
-                    $this->set_timezone($field->get_timezone());
1498
-                    break;
1499
-                }
1500
-            }
1501
-        }
1502
-        // if timezone STILL empty then return the default timezone for the site.
1503
-        if (empty($this->_timezone)) {
1504
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1505
-        }
1506
-        return $this->_timezone;
1507
-    }
1508
-
1509
-
1510
-
1511
-    /**
1512
-     * This returns the date formats set for the given field name and also ensures that
1513
-     * $this->_timezone property is set correctly.
1514
-     *
1515
-     * @since 4.6.x
1516
-     * @param string $field_name The name of the field the formats are being retrieved for.
1517
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1518
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1519
-     * @return array formats in an array with the date format first, and the time format last.
1520
-     */
1521
-    public function get_formats_for($field_name, $pretty = false)
1522
-    {
1523
-        $field_settings = $this->field_settings_for($field_name);
1524
-        // if not a valid EE_Datetime_Field then throw error
1525
-        if (! $field_settings instanceof EE_Datetime_Field) {
1526
-            throw new EE_Error(sprintf(__(
1527
-                '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.',
1528
-                'event_espresso'
1529
-            ), $field_name));
1530
-        }
1531
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1532
-        // the field.
1533
-        $this->_timezone = $field_settings->get_timezone();
1534
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1535
-    }
1536
-
1537
-
1538
-
1539
-    /**
1540
-     * This returns the current time in a format setup for a query on this model.
1541
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1542
-     * it will return:
1543
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1544
-     *  NOW
1545
-     *  - or a unix timestamp (equivalent to time())
1546
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1547
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1548
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1549
-     * @since 4.6.x
1550
-     * @param string $field_name       The field the current time is needed for.
1551
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1552
-     *                                 formatted string matching the set format for the field in the set timezone will
1553
-     *                                 be returned.
1554
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1555
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1556
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1557
-     *                                 exception is triggered.
1558
-     */
1559
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1560
-    {
1561
-        $formats = $this->get_formats_for($field_name);
1562
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1563
-        if ($timestamp) {
1564
-            return $DateTime->format('U');
1565
-        }
1566
-        // not returning timestamp, so return formatted string in timezone.
1567
-        switch ($what) {
1568
-            case 'time':
1569
-                return $DateTime->format($formats[1]);
1570
-                break;
1571
-            case 'date':
1572
-                return $DateTime->format($formats[0]);
1573
-                break;
1574
-            default:
1575
-                return $DateTime->format(implode(' ', $formats));
1576
-                break;
1577
-        }
1578
-    }
1579
-
1580
-
1581
-
1582
-    /**
1583
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1584
-     * for the model are.  Returns a DateTime object.
1585
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1586
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1587
-     * ignored.
1588
-     *
1589
-     * @param string $field_name      The field being setup.
1590
-     * @param string $timestring      The date time string being used.
1591
-     * @param string $incoming_format The format for the time string.
1592
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1593
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1594
-     *                                format is
1595
-     *                                'U', this is ignored.
1596
-     * @return DateTime
1597
-     * @throws EE_Error
1598
-     */
1599
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1600
-    {
1601
-        // just using this to ensure the timezone is set correctly internally
1602
-        $this->get_formats_for($field_name);
1603
-        // load EEH_DTT_Helper
1604
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1605
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1606
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1607
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1608
-    }
1609
-
1610
-
1611
-
1612
-    /**
1613
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1614
-     *
1615
-     * @return EE_Table_Base[]
1616
-     */
1617
-    public function get_tables()
1618
-    {
1619
-        return $this->_tables;
1620
-    }
1621
-
1622
-
1623
-
1624
-    /**
1625
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1626
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1627
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1628
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1629
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1630
-     * model object with EVT_ID = 1
1631
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1632
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1633
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1634
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1635
-     * are not specified)
1636
-     *
1637
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1638
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1639
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1640
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1641
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1642
-     *                                         ID=34, we'd use this method as follows:
1643
-     *                                         EEM_Transaction::instance()->update(
1644
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1645
-     *                                         array(array('TXN_ID'=>34)));
1646
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1647
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1648
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1649
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1650
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1651
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1652
-     *                                         TRUE, it is assumed that you've already called
1653
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1654
-     *                                         malicious javascript. However, if
1655
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1656
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1657
-     *                                         and every other field, before insertion. We provide this parameter
1658
-     *                                         because model objects perform their prepare_for_set function on all
1659
-     *                                         their values, and so don't need to be called again (and in many cases,
1660
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1661
-     *                                         prepare_for_set method...)
1662
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1663
-     *                                         in this model's entity map according to $fields_n_values that match
1664
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1665
-     *                                         by setting this to FALSE, but be aware that model objects being used
1666
-     *                                         could get out-of-sync with the database
1667
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1668
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1669
-     *                                         bad)
1670
-     * @throws EE_Error
1671
-     */
1672
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1673
-    {
1674
-        if (! is_array($query_params)) {
1675
-            EE_Error::doing_it_wrong(
1676
-                'EEM_Base::update',
1677
-                sprintf(
1678
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1679
-                    gettype($query_params)
1680
-                ),
1681
-                '4.6.0'
1682
-            );
1683
-            $query_params = array();
1684
-        }
1685
-        /**
1686
-         * Action called before a model update call has been made.
1687
-         *
1688
-         * @param EEM_Base $model
1689
-         * @param array    $fields_n_values the updated fields and their new values
1690
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1691
-         */
1692
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1693
-        /**
1694
-         * Filters the fields about to be updated given the query parameters. You can provide the
1695
-         * $query_params to $this->get_all() to find exactly which records will be updated
1696
-         *
1697
-         * @param array    $fields_n_values fields and their new values
1698
-         * @param EEM_Base $model           the model being queried
1699
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1700
-         */
1701
-        $fields_n_values = (array) apply_filters(
1702
-            'FHEE__EEM_Base__update__fields_n_values',
1703
-            $fields_n_values,
1704
-            $this,
1705
-            $query_params
1706
-        );
1707
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1708
-        // to do that, for each table, verify that it's PK isn't null.
1709
-        $tables = $this->get_tables();
1710
-        // 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
1711
-        // NOTE: we should make this code more efficient by NOT querying twice
1712
-        // before the real update, but that needs to first go through ALPHA testing
1713
-        // as it's dangerous. says Mike August 8 2014
1714
-        // we want to make sure the default_where strategy is ignored
1715
-        $this->_ignore_where_strategy = true;
1716
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1717
-        foreach ($wpdb_select_results as $wpdb_result) {
1718
-            // type cast stdClass as array
1719
-            $wpdb_result = (array) $wpdb_result;
1720
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1721
-            if ($this->has_primary_key_field()) {
1722
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1723
-            } else {
1724
-                // 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)
1725
-                $main_table_pk_value = null;
1726
-            }
1727
-            // 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
1728
-            // 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
1729
-            if (count($tables) > 1) {
1730
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1731
-                // in that table, and so we'll want to insert one
1732
-                foreach ($tables as $table_obj) {
1733
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1734
-                    // if there is no private key for this table on the results, it means there's no entry
1735
-                    // in this table, right? so insert a row in the current table, using any fields available
1736
-                    if (
1737
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1738
-                           && $wpdb_result[ $this_table_pk_column ])
1739
-                    ) {
1740
-                        $success = $this->_insert_into_specific_table(
1741
-                            $table_obj,
1742
-                            $fields_n_values,
1743
-                            $main_table_pk_value
1744
-                        );
1745
-                        // if we died here, report the error
1746
-                        if (! $success) {
1747
-                            return false;
1748
-                        }
1749
-                    }
1750
-                }
1751
-            }
1752
-            //              //and now check that if we have cached any models by that ID on the model, that
1753
-            //              //they also get updated properly
1754
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1755
-            //              if( $model_object ){
1756
-            //                  foreach( $fields_n_values as $field => $value ){
1757
-            //                      $model_object->set($field, $value);
1758
-            // let's make sure default_where strategy is followed now
1759
-            $this->_ignore_where_strategy = false;
1760
-        }
1761
-        // if we want to keep model objects in sync, AND
1762
-        // if this wasn't called from a model object (to update itself)
1763
-        // then we want to make sure we keep all the existing
1764
-        // model objects in sync with the db
1765
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1766
-            if ($this->has_primary_key_field()) {
1767
-                $model_objs_affected_ids = $this->get_col($query_params);
1768
-            } else {
1769
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1770
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1771
-                $model_objs_affected_ids = array();
1772
-                foreach ($models_affected_key_columns as $row) {
1773
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1774
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1775
-                }
1776
-            }
1777
-            if (! $model_objs_affected_ids) {
1778
-                // wait wait wait- if nothing was affected let's stop here
1779
-                return 0;
1780
-            }
1781
-            foreach ($model_objs_affected_ids as $id) {
1782
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1783
-                if ($model_obj_in_entity_map) {
1784
-                    foreach ($fields_n_values as $field => $new_value) {
1785
-                        $model_obj_in_entity_map->set($field, $new_value);
1786
-                    }
1787
-                }
1788
-            }
1789
-            // if there is a primary key on this model, we can now do a slight optimization
1790
-            if ($this->has_primary_key_field()) {
1791
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1792
-                $query_params = array(
1793
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1794
-                    'limit'                    => count($model_objs_affected_ids),
1795
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1796
-                );
1797
-            }
1798
-        }
1799
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1800
-        $SQL = "UPDATE "
1801
-               . $model_query_info->get_full_join_sql()
1802
-               . " SET "
1803
-               . $this->_construct_update_sql($fields_n_values)
1804
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1805
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1806
-        /**
1807
-         * Action called after a model update call has been made.
1808
-         *
1809
-         * @param EEM_Base $model
1810
-         * @param array    $fields_n_values the updated fields and their new values
1811
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1812
-         * @param int      $rows_affected
1813
-         */
1814
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1815
-        return $rows_affected;// how many supposedly got updated
1816
-    }
1817
-
1818
-
1819
-
1820
-    /**
1821
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1822
-     * are teh values of the field specified (or by default the primary key field)
1823
-     * that matched the query params. Note that you should pass the name of the
1824
-     * model FIELD, not the database table's column name.
1825
-     *
1826
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1827
-     * @param string $field_to_select
1828
-     * @return array just like $wpdb->get_col()
1829
-     * @throws EE_Error
1830
-     */
1831
-    public function get_col($query_params = array(), $field_to_select = null)
1832
-    {
1833
-        if ($field_to_select) {
1834
-            $field = $this->field_settings_for($field_to_select);
1835
-        } elseif ($this->has_primary_key_field()) {
1836
-            $field = $this->get_primary_key_field();
1837
-        } else {
1838
-            // no primary key, just grab the first column
1839
-            $field = reset($this->field_settings());
1840
-        }
1841
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1842
-        $select_expressions = $field->get_qualified_column();
1843
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1844
-        return $this->_do_wpdb_query('get_col', array($SQL));
1845
-    }
1846
-
1847
-
1848
-
1849
-    /**
1850
-     * Returns a single column value for a single row from the database
1851
-     *
1852
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1853
-     * @param string $field_to_select @see EEM_Base::get_col()
1854
-     * @return string
1855
-     * @throws EE_Error
1856
-     */
1857
-    public function get_var($query_params = array(), $field_to_select = null)
1858
-    {
1859
-        $query_params['limit'] = 1;
1860
-        $col = $this->get_col($query_params, $field_to_select);
1861
-        if (! empty($col)) {
1862
-            return reset($col);
1863
-        }
1864
-        return null;
1865
-    }
1866
-
1867
-
1868
-
1869
-    /**
1870
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1871
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1872
-     * injection, but currently no further filtering is done
1873
-     *
1874
-     * @global      $wpdb
1875
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1876
-     *                               be updated to in the DB
1877
-     * @return string of SQL
1878
-     * @throws EE_Error
1879
-     */
1880
-    public function _construct_update_sql($fields_n_values)
1881
-    {
1882
-        /** @type WPDB $wpdb */
1883
-        global $wpdb;
1884
-        $cols_n_values = array();
1885
-        foreach ($fields_n_values as $field_name => $value) {
1886
-            $field_obj = $this->field_settings_for($field_name);
1887
-            // if the value is NULL, we want to assign the value to that.
1888
-            // wpdb->prepare doesn't really handle that properly
1889
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1890
-            $value_sql = $prepared_value === null ? 'NULL'
1891
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1892
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1893
-        }
1894
-        return implode(",", $cols_n_values);
1895
-    }
1896
-
1897
-
1898
-
1899
-    /**
1900
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1901
-     * Performs a HARD delete, meaning the database row should always be removed,
1902
-     * not just have a flag field on it switched
1903
-     * Wrapper for EEM_Base::delete_permanently()
1904
-     *
1905
-     * @param mixed $id
1906
-     * @param boolean $allow_blocking
1907
-     * @return int the number of rows deleted
1908
-     * @throws EE_Error
1909
-     */
1910
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1911
-    {
1912
-        return $this->delete_permanently(
1913
-            array(
1914
-                array($this->get_primary_key_field()->get_name() => $id),
1915
-                'limit' => 1,
1916
-            ),
1917
-            $allow_blocking
1918
-        );
1919
-    }
1920
-
1921
-
1922
-
1923
-    /**
1924
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1925
-     * Wrapper for EEM_Base::delete()
1926
-     *
1927
-     * @param mixed $id
1928
-     * @param boolean $allow_blocking
1929
-     * @return int the number of rows deleted
1930
-     * @throws EE_Error
1931
-     */
1932
-    public function delete_by_ID($id, $allow_blocking = true)
1933
-    {
1934
-        return $this->delete(
1935
-            array(
1936
-                array($this->get_primary_key_field()->get_name() => $id),
1937
-                'limit' => 1,
1938
-            ),
1939
-            $allow_blocking
1940
-        );
1941
-    }
1942
-
1943
-
1944
-
1945
-    /**
1946
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1947
-     * meaning if the model has a field that indicates its been "trashed" or
1948
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1949
-     *
1950
-     * @see EEM_Base::delete_permanently
1951
-     * @param array   $query_params
1952
-     * @param boolean $allow_blocking
1953
-     * @return int how many rows got deleted
1954
-     * @throws EE_Error
1955
-     */
1956
-    public function delete($query_params, $allow_blocking = true)
1957
-    {
1958
-        return $this->delete_permanently($query_params, $allow_blocking);
1959
-    }
1960
-
1961
-
1962
-
1963
-    /**
1964
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1965
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1966
-     * as archived, not actually deleted
1967
-     *
1968
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1969
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1970
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1971
-     *                                deletes regardless of other objects which may depend on it. Its generally
1972
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1973
-     *                                DB
1974
-     * @return int how many rows got deleted
1975
-     * @throws EE_Error
1976
-     */
1977
-    public function delete_permanently($query_params, $allow_blocking = true)
1978
-    {
1979
-        /**
1980
-         * Action called just before performing a real deletion query. You can use the
1981
-         * model and its $query_params to find exactly which items will be deleted
1982
-         *
1983
-         * @param EEM_Base $model
1984
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1985
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1986
-         *                                 to block (prevent) this deletion
1987
-         */
1988
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1989
-        // some MySQL databases may be running safe mode, which may restrict
1990
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1991
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1992
-        // to delete them
1993
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1994
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1995
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1996
-            $columns_and_ids_for_deleting
1997
-        );
1998
-        /**
1999
-         * Allows client code to act on the items being deleted before the query is actually executed.
2000
-         *
2001
-         * @param EEM_Base $this  The model instance being acted on.
2002
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2003
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
2004
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
2005
-         *                                                  derived from the incoming query parameters.
2006
-         *                                                  @see details on the structure of this array in the phpdocs
2007
-         *                                                  for the `_get_ids_for_delete_method`
2008
-         *
2009
-         */
2010
-        do_action(
2011
-            'AHEE__EEM_Base__delete__before_query',
2012
-            $this,
2013
-            $query_params,
2014
-            $allow_blocking,
2015
-            $columns_and_ids_for_deleting
2016
-        );
2017
-        if ($deletion_where_query_part) {
2018
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2019
-            $table_aliases = array_keys($this->_tables);
2020
-            $SQL = "DELETE "
2021
-                   . implode(", ", $table_aliases)
2022
-                   . " FROM "
2023
-                   . $model_query_info->get_full_join_sql()
2024
-                   . " WHERE "
2025
-                   . $deletion_where_query_part;
2026
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2027
-        } else {
2028
-            $rows_deleted = 0;
2029
-        }
2030
-
2031
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2032
-        // there was no error with the delete query.
2033
-        if (
2034
-            $this->has_primary_key_field()
2035
-            && $rows_deleted !== false
2036
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2037
-        ) {
2038
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2039
-            foreach ($ids_for_removal as $id) {
2040
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2041
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2042
-                }
2043
-            }
2044
-
2045
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2046
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2047
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2048
-            // (although it is possible).
2049
-            // Note this can be skipped by using the provided filter and returning false.
2050
-            if (
2051
-                apply_filters(
2052
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2053
-                    ! $this instanceof EEM_Extra_Meta,
2054
-                    $this
2055
-                )
2056
-            ) {
2057
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2058
-                    0 => array(
2059
-                        'EXM_type' => $this->get_this_model_name(),
2060
-                        'OBJ_ID'   => array(
2061
-                            'IN',
2062
-                            $ids_for_removal
2063
-                        )
2064
-                    )
2065
-                ));
2066
-            }
2067
-        }
2068
-
2069
-        /**
2070
-         * Action called just after performing a real deletion query. Although at this point the
2071
-         * items should have been deleted
2072
-         *
2073
-         * @param EEM_Base $model
2074
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2075
-         * @param int      $rows_deleted
2076
-         */
2077
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2078
-        return $rows_deleted;// how many supposedly got deleted
2079
-    }
2080
-
2081
-
2082
-
2083
-    /**
2084
-     * Checks all the relations that throw error messages when there are blocking related objects
2085
-     * for related model objects. If there are any related model objects on those relations,
2086
-     * adds an EE_Error, and return true
2087
-     *
2088
-     * @param EE_Base_Class|int $this_model_obj_or_id
2089
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2090
-     *                                                 should be ignored when determining whether there are related
2091
-     *                                                 model objects which block this model object's deletion. Useful
2092
-     *                                                 if you know A is related to B and are considering deleting A,
2093
-     *                                                 but want to see if A has any other objects blocking its deletion
2094
-     *                                                 before removing the relation between A and B
2095
-     * @return boolean
2096
-     * @throws EE_Error
2097
-     */
2098
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2099
-    {
2100
-        // first, if $ignore_this_model_obj was supplied, get its model
2101
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2102
-            $ignored_model = $ignore_this_model_obj->get_model();
2103
-        } else {
2104
-            $ignored_model = null;
2105
-        }
2106
-        // now check all the relations of $this_model_obj_or_id and see if there
2107
-        // are any related model objects blocking it?
2108
-        $is_blocked = false;
2109
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2110
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2111
-                // if $ignore_this_model_obj was supplied, then for the query
2112
-                // on that model needs to be told to ignore $ignore_this_model_obj
2113
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2114
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2115
-                        array(
2116
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2117
-                                '!=',
2118
-                                $ignore_this_model_obj->ID(),
2119
-                            ),
2120
-                        ),
2121
-                    ));
2122
-                } else {
2123
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2124
-                }
2125
-                if ($related_model_objects) {
2126
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2127
-                    $is_blocked = true;
2128
-                }
2129
-            }
2130
-        }
2131
-        return $is_blocked;
2132
-    }
2133
-
2134
-
2135
-    /**
2136
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2137
-     * @param array $row_results_for_deleting
2138
-     * @param bool  $allow_blocking
2139
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2140
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2141
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2142
-     *                 deleted. Example:
2143
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2144
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2145
-     *                 where each element is a group of columns and values that get deleted. Example:
2146
-     *                      array(
2147
-     *                          0 => array(
2148
-     *                              'Term_Relationship.object_id' => 1
2149
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2150
-     *                          ),
2151
-     *                          1 => array(
2152
-     *                              'Term_Relationship.object_id' => 1
2153
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2154
-     *                          )
2155
-     *                      )
2156
-     * @throws EE_Error
2157
-     */
2158
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2159
-    {
2160
-        $ids_to_delete_indexed_by_column = array();
2161
-        if ($this->has_primary_key_field()) {
2162
-            $primary_table = $this->_get_main_table();
2163
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2164
-            $other_tables = $this->_get_other_tables();
2165
-            $ids_to_delete_indexed_by_column = $query = array();
2166
-            foreach ($row_results_for_deleting as $item_to_delete) {
2167
-                // before we mark this item for deletion,
2168
-                // make sure there's no related entities blocking its deletion (if we're checking)
2169
-                if (
2170
-                    $allow_blocking
2171
-                    && $this->delete_is_blocked_by_related_models(
2172
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2173
-                    )
2174
-                ) {
2175
-                    continue;
2176
-                }
2177
-                // primary table deletes
2178
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2179
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2180
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2181
-                }
2182
-            }
2183
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2184
-            $fields = $this->get_combined_primary_key_fields();
2185
-            foreach ($row_results_for_deleting as $item_to_delete) {
2186
-                $ids_to_delete_indexed_by_column_for_row = array();
2187
-                foreach ($fields as $cpk_field) {
2188
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2189
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2190
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2191
-                    }
2192
-                }
2193
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2194
-            }
2195
-        } else {
2196
-            // so there's no primary key and no combined key...
2197
-            // sorry, can't help you
2198
-            throw new EE_Error(
2199
-                sprintf(
2200
-                    __(
2201
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2202
-                        "event_espresso"
2203
-                    ),
2204
-                    get_class($this)
2205
-                )
2206
-            );
2207
-        }
2208
-        return $ids_to_delete_indexed_by_column;
2209
-    }
2210
-
2211
-
2212
-    /**
2213
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2214
-     * the corresponding query_part for the query performing the delete.
2215
-     *
2216
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2217
-     * @return string
2218
-     * @throws EE_Error
2219
-     */
2220
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2221
-    {
2222
-        $query_part = '';
2223
-        if (empty($ids_to_delete_indexed_by_column)) {
2224
-            return $query_part;
2225
-        } elseif ($this->has_primary_key_field()) {
2226
-            $query = array();
2227
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2228
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2229
-            }
2230
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2231
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2232
-            $ways_to_identify_a_row = array();
2233
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2234
-                $values_for_each_combined_primary_key_for_a_row = array();
2235
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2236
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2237
-                }
2238
-                $ways_to_identify_a_row[] = '('
2239
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2240
-                                            . ')';
2241
-            }
2242
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2243
-        }
2244
-        return $query_part;
2245
-    }
2246
-
2247
-
2248
-
2249
-    /**
2250
-     * Gets the model field by the fully qualified name
2251
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2252
-     * @return EE_Model_Field_Base
2253
-     */
2254
-    public function get_field_by_column($qualified_column_name)
2255
-    {
2256
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2257
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2258
-                return $field_obj;
2259
-            }
2260
-        }
2261
-        throw new EE_Error(
2262
-            sprintf(
2263
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2264
-                $this->get_this_model_name(),
2265
-                $qualified_column_name
2266
-            )
2267
-        );
2268
-    }
2269
-
2270
-
2271
-
2272
-    /**
2273
-     * Count all the rows that match criteria the model query params.
2274
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2275
-     * column
2276
-     *
2277
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2278
-     * @param string $field_to_count field on model to count by (not column name)
2279
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2280
-     *                               that by the setting $distinct to TRUE;
2281
-     * @return int
2282
-     * @throws EE_Error
2283
-     */
2284
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2285
-    {
2286
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2287
-        if ($field_to_count) {
2288
-            $field_obj = $this->field_settings_for($field_to_count);
2289
-            $column_to_count = $field_obj->get_qualified_column();
2290
-        } elseif ($this->has_primary_key_field()) {
2291
-            $pk_field_obj = $this->get_primary_key_field();
2292
-            $column_to_count = $pk_field_obj->get_qualified_column();
2293
-        } else {
2294
-            // there's no primary key
2295
-            // if we're counting distinct items, and there's no primary key,
2296
-            // we need to list out the columns for distinction;
2297
-            // otherwise we can just use star
2298
-            if ($distinct) {
2299
-                $columns_to_use = array();
2300
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2301
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2302
-                }
2303
-                $column_to_count = implode(',', $columns_to_use);
2304
-            } else {
2305
-                $column_to_count = '*';
2306
-            }
2307
-        }
2308
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2309
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2310
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2311
-    }
2312
-
2313
-
2314
-
2315
-    /**
2316
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2317
-     *
2318
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2319
-     * @param string $field_to_sum name of field (array key in $_fields array)
2320
-     * @return float
2321
-     * @throws EE_Error
2322
-     */
2323
-    public function sum($query_params, $field_to_sum = null)
2324
-    {
2325
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2326
-        if ($field_to_sum) {
2327
-            $field_obj = $this->field_settings_for($field_to_sum);
2328
-        } else {
2329
-            $field_obj = $this->get_primary_key_field();
2330
-        }
2331
-        $column_to_count = $field_obj->get_qualified_column();
2332
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2333
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2334
-        $data_type = $field_obj->get_wpdb_data_type();
2335
-        if ($data_type === '%d' || $data_type === '%s') {
2336
-            return (float) $return_value;
2337
-        }
2338
-        // must be %f
2339
-        return (float) $return_value;
2340
-    }
2341
-
2342
-
2343
-
2344
-    /**
2345
-     * Just calls the specified method on $wpdb with the given arguments
2346
-     * Consolidates a little extra error handling code
2347
-     *
2348
-     * @param string $wpdb_method
2349
-     * @param array  $arguments_to_provide
2350
-     * @throws EE_Error
2351
-     * @global wpdb  $wpdb
2352
-     * @return mixed
2353
-     */
2354
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2355
-    {
2356
-        // if we're in maintenance mode level 2, DON'T run any queries
2357
-        // because level 2 indicates the database needs updating and
2358
-        // is probably out of sync with the code
2359
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2360
-            throw new EE_Error(sprintf(__(
2361
-                "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.",
2362
-                "event_espresso"
2363
-            )));
2364
-        }
2365
-        /** @type WPDB $wpdb */
2366
-        global $wpdb;
2367
-        if (! method_exists($wpdb, $wpdb_method)) {
2368
-            throw new EE_Error(sprintf(__(
2369
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2370
-                'event_espresso'
2371
-            ), $wpdb_method));
2372
-        }
2373
-        if (WP_DEBUG) {
2374
-            $old_show_errors_value = $wpdb->show_errors;
2375
-            $wpdb->show_errors(false);
2376
-        }
2377
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2378
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2379
-        if (WP_DEBUG) {
2380
-            $wpdb->show_errors($old_show_errors_value);
2381
-            if (! empty($wpdb->last_error)) {
2382
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2383
-            }
2384
-            if ($result === false) {
2385
-                throw new EE_Error(sprintf(__(
2386
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2387
-                    'event_espresso'
2388
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2389
-            }
2390
-        } elseif ($result === false) {
2391
-            EE_Error::add_error(
2392
-                sprintf(
2393
-                    __(
2394
-                        '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"',
2395
-                        'event_espresso'
2396
-                    ),
2397
-                    $wpdb_method,
2398
-                    var_export($arguments_to_provide, true),
2399
-                    $wpdb->last_error
2400
-                ),
2401
-                __FILE__,
2402
-                __FUNCTION__,
2403
-                __LINE__
2404
-            );
2405
-        }
2406
-        return $result;
2407
-    }
2408
-
2409
-
2410
-
2411
-    /**
2412
-     * Attempts to run the indicated WPDB method with the provided arguments,
2413
-     * and if there's an error tries to verify the DB is correct. Uses
2414
-     * the static property EEM_Base::$_db_verification_level to determine whether
2415
-     * we should try to fix the EE core db, the addons, or just give up
2416
-     *
2417
-     * @param string $wpdb_method
2418
-     * @param array  $arguments_to_provide
2419
-     * @return mixed
2420
-     */
2421
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2422
-    {
2423
-        /** @type WPDB $wpdb */
2424
-        global $wpdb;
2425
-        $wpdb->last_error = null;
2426
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2427
-        // was there an error running the query? but we don't care on new activations
2428
-        // (we're going to setup the DB anyway on new activations)
2429
-        if (
2430
-            ($result === false || ! empty($wpdb->last_error))
2431
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2432
-        ) {
2433
-            switch (EEM_Base::$_db_verification_level) {
2434
-                case EEM_Base::db_verified_none:
2435
-                    // let's double-check core's DB
2436
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2437
-                    break;
2438
-                case EEM_Base::db_verified_core:
2439
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2440
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2441
-                    break;
2442
-                case EEM_Base::db_verified_addons:
2443
-                    // ummmm... you in trouble
2444
-                    return $result;
2445
-                    break;
2446
-            }
2447
-            if (! empty($error_message)) {
2448
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2449
-                trigger_error($error_message);
2450
-            }
2451
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2452
-        }
2453
-        return $result;
2454
-    }
2455
-
2456
-
2457
-
2458
-    /**
2459
-     * Verifies the EE core database is up-to-date and records that we've done it on
2460
-     * EEM_Base::$_db_verification_level
2461
-     *
2462
-     * @param string $wpdb_method
2463
-     * @param array  $arguments_to_provide
2464
-     * @return string
2465
-     */
2466
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2467
-    {
2468
-        /** @type WPDB $wpdb */
2469
-        global $wpdb;
2470
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2471
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2472
-        $error_message = sprintf(
2473
-            __(
2474
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2475
-                'event_espresso'
2476
-            ),
2477
-            $wpdb->last_error,
2478
-            $wpdb_method,
2479
-            wp_json_encode($arguments_to_provide)
2480
-        );
2481
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2482
-        return $error_message;
2483
-    }
2484
-
2485
-
2486
-
2487
-    /**
2488
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2489
-     * EEM_Base::$_db_verification_level
2490
-     *
2491
-     * @param $wpdb_method
2492
-     * @param $arguments_to_provide
2493
-     * @return string
2494
-     */
2495
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2496
-    {
2497
-        /** @type WPDB $wpdb */
2498
-        global $wpdb;
2499
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2500
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2501
-        $error_message = sprintf(
2502
-            __(
2503
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2504
-                'event_espresso'
2505
-            ),
2506
-            $wpdb->last_error,
2507
-            $wpdb_method,
2508
-            wp_json_encode($arguments_to_provide)
2509
-        );
2510
-        EE_System::instance()->initialize_addons();
2511
-        return $error_message;
2512
-    }
2513
-
2514
-
2515
-
2516
-    /**
2517
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2518
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2519
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2520
-     * ..."
2521
-     *
2522
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2523
-     * @return string
2524
-     */
2525
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2526
-    {
2527
-        return " FROM " . $model_query_info->get_full_join_sql() .
2528
-               $model_query_info->get_where_sql() .
2529
-               $model_query_info->get_group_by_sql() .
2530
-               $model_query_info->get_having_sql() .
2531
-               $model_query_info->get_order_by_sql() .
2532
-               $model_query_info->get_limit_sql();
2533
-    }
2534
-
2535
-
2536
-
2537
-    /**
2538
-     * Set to easily debug the next X queries ran from this model.
2539
-     *
2540
-     * @param int $count
2541
-     */
2542
-    public function show_next_x_db_queries($count = 1)
2543
-    {
2544
-        $this->_show_next_x_db_queries = $count;
2545
-    }
2546
-
2547
-
2548
-
2549
-    /**
2550
-     * @param $sql_query
2551
-     */
2552
-    public function show_db_query_if_previously_requested($sql_query)
2553
-    {
2554
-        if ($this->_show_next_x_db_queries > 0) {
2555
-            echo $sql_query;
2556
-            $this->_show_next_x_db_queries--;
2557
-        }
2558
-    }
2559
-
2560
-
2561
-
2562
-    /**
2563
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2564
-     * There are the 3 cases:
2565
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2566
-     * $otherModelObject has no ID, it is first saved.
2567
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2568
-     * has no ID, it is first saved.
2569
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2570
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2571
-     * join table
2572
-     *
2573
-     * @param        EE_Base_Class                     /int $thisModelObject
2574
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2575
-     * @param string $relationName                     , key in EEM_Base::_relations
2576
-     *                                                 an attendee to a group, you also want to specify which role they
2577
-     *                                                 will have in that group. So you would use this parameter to
2578
-     *                                                 specify array('role-column-name'=>'role-id')
2579
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2580
-     *                                                 to for relation to methods that allow you to further specify
2581
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2582
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2583
-     *                                                 because these will be inserted in any new rows created as well.
2584
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2585
-     * @throws EE_Error
2586
-     */
2587
-    public function add_relationship_to(
2588
-        $id_or_obj,
2589
-        $other_model_id_or_obj,
2590
-        $relationName,
2591
-        $extra_join_model_fields_n_values = array()
2592
-    ) {
2593
-        $relation_obj = $this->related_settings_for($relationName);
2594
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2595
-    }
2596
-
2597
-
2598
-
2599
-    /**
2600
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2601
-     * There are the 3 cases:
2602
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2603
-     * error
2604
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2605
-     * an error
2606
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2607
-     *
2608
-     * @param        EE_Base_Class /int $id_or_obj
2609
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2610
-     * @param string $relationName key in EEM_Base::_relations
2611
-     * @return boolean of success
2612
-     * @throws EE_Error
2613
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2614
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2615
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2616
-     *                             because these will be inserted in any new rows created as well.
2617
-     */
2618
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2619
-    {
2620
-        $relation_obj = $this->related_settings_for($relationName);
2621
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2622
-    }
2623
-
2624
-
2625
-
2626
-    /**
2627
-     * @param mixed           $id_or_obj
2628
-     * @param string          $relationName
2629
-     * @param array           $where_query_params
2630
-     * @param EE_Base_Class[] objects to which relations were removed
2631
-     * @return \EE_Base_Class[]
2632
-     * @throws EE_Error
2633
-     */
2634
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2635
-    {
2636
-        $relation_obj = $this->related_settings_for($relationName);
2637
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2638
-    }
2639
-
2640
-
2641
-
2642
-    /**
2643
-     * Gets all the related items of the specified $model_name, using $query_params.
2644
-     * Note: by default, we remove the "default query params"
2645
-     * because we want to get even deleted items etc.
2646
-     *
2647
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2648
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2649
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2650
-     * @return EE_Base_Class[]
2651
-     * @throws EE_Error
2652
-     */
2653
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2654
-    {
2655
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2656
-        $relation_settings = $this->related_settings_for($model_name);
2657
-        return $relation_settings->get_all_related($model_obj, $query_params);
2658
-    }
2659
-
2660
-
2661
-
2662
-    /**
2663
-     * Deletes all the model objects across the relation indicated by $model_name
2664
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2665
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2666
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2667
-     *
2668
-     * @param EE_Base_Class|int|string $id_or_obj
2669
-     * @param string                   $model_name
2670
-     * @param array                    $query_params
2671
-     * @return int how many deleted
2672
-     * @throws EE_Error
2673
-     */
2674
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2675
-    {
2676
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2677
-        $relation_settings = $this->related_settings_for($model_name);
2678
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2679
-    }
2680
-
2681
-
2682
-
2683
-    /**
2684
-     * Hard deletes all the model objects across the relation indicated by $model_name
2685
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2686
-     * the model objects can't be hard deleted because of blocking related model objects,
2687
-     * just does a soft-delete on them instead.
2688
-     *
2689
-     * @param EE_Base_Class|int|string $id_or_obj
2690
-     * @param string                   $model_name
2691
-     * @param array                    $query_params
2692
-     * @return int how many deleted
2693
-     * @throws EE_Error
2694
-     */
2695
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2696
-    {
2697
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2698
-        $relation_settings = $this->related_settings_for($model_name);
2699
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2700
-    }
2701
-
2702
-
2703
-
2704
-    /**
2705
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2706
-     * unless otherwise specified in the $query_params
2707
-     *
2708
-     * @param        int             /EE_Base_Class $id_or_obj
2709
-     * @param string $model_name     like 'Event', or 'Registration'
2710
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2711
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2712
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2713
-     *                               that by the setting $distinct to TRUE;
2714
-     * @return int
2715
-     * @throws EE_Error
2716
-     */
2717
-    public function count_related(
2718
-        $id_or_obj,
2719
-        $model_name,
2720
-        $query_params = array(),
2721
-        $field_to_count = null,
2722
-        $distinct = false
2723
-    ) {
2724
-        $related_model = $this->get_related_model_obj($model_name);
2725
-        // we're just going to use the query params on the related model's normal get_all query,
2726
-        // except add a condition to say to match the current mod
2727
-        if (! isset($query_params['default_where_conditions'])) {
2728
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2729
-        }
2730
-        $this_model_name = $this->get_this_model_name();
2731
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2732
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2733
-        return $related_model->count($query_params, $field_to_count, $distinct);
2734
-    }
2735
-
2736
-
2737
-
2738
-    /**
2739
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2740
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2741
-     *
2742
-     * @param        int           /EE_Base_Class $id_or_obj
2743
-     * @param string $model_name   like 'Event', or 'Registration'
2744
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2745
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2746
-     * @return float
2747
-     * @throws EE_Error
2748
-     */
2749
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2750
-    {
2751
-        $related_model = $this->get_related_model_obj($model_name);
2752
-        if (! is_array($query_params)) {
2753
-            EE_Error::doing_it_wrong(
2754
-                'EEM_Base::sum_related',
2755
-                sprintf(
2756
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2757
-                    gettype($query_params)
2758
-                ),
2759
-                '4.6.0'
2760
-            );
2761
-            $query_params = array();
2762
-        }
2763
-        // we're just going to use the query params on the related model's normal get_all query,
2764
-        // except add a condition to say to match the current mod
2765
-        if (! isset($query_params['default_where_conditions'])) {
2766
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2767
-        }
2768
-        $this_model_name = $this->get_this_model_name();
2769
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2770
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2771
-        return $related_model->sum($query_params, $field_to_sum);
2772
-    }
2773
-
2774
-
2775
-
2776
-    /**
2777
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2778
-     * $modelObject
2779
-     *
2780
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2781
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2782
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2783
-     * @return EE_Base_Class
2784
-     * @throws EE_Error
2785
-     */
2786
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2787
-    {
2788
-        $query_params['limit'] = 1;
2789
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2790
-        if ($results) {
2791
-            return array_shift($results);
2792
-        }
2793
-        return null;
2794
-    }
2795
-
2796
-
2797
-
2798
-    /**
2799
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2800
-     *
2801
-     * @return string
2802
-     */
2803
-    public function get_this_model_name()
2804
-    {
2805
-        return str_replace("EEM_", "", get_class($this));
2806
-    }
2807
-
2808
-
2809
-
2810
-    /**
2811
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2812
-     *
2813
-     * @return EE_Any_Foreign_Model_Name_Field
2814
-     * @throws EE_Error
2815
-     */
2816
-    public function get_field_containing_related_model_name()
2817
-    {
2818
-        foreach ($this->field_settings(true) as $field) {
2819
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2820
-                $field_with_model_name = $field;
2821
-            }
2822
-        }
2823
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2824
-            throw new EE_Error(sprintf(
2825
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2826
-                $this->get_this_model_name()
2827
-            ));
2828
-        }
2829
-        return $field_with_model_name;
2830
-    }
2831
-
2832
-
2833
-
2834
-    /**
2835
-     * Inserts a new entry into the database, for each table.
2836
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2837
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2838
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2839
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2840
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2841
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2842
-     *
2843
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2844
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2845
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2846
-     *                              of EEM_Base)
2847
-     * @return int|string new primary key on main table that got inserted
2848
-     * @throws EE_Error
2849
-     */
2850
-    public function insert($field_n_values)
2851
-    {
2852
-        /**
2853
-         * Filters the fields and their values before inserting an item using the models
2854
-         *
2855
-         * @param array    $fields_n_values keys are the fields and values are their new values
2856
-         * @param EEM_Base $model           the model used
2857
-         */
2858
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2859
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2860
-            $main_table = $this->_get_main_table();
2861
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2862
-            if ($new_id !== false) {
2863
-                foreach ($this->_get_other_tables() as $other_table) {
2864
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2865
-                }
2866
-            }
2867
-            /**
2868
-             * Done just after attempting to insert a new model object
2869
-             *
2870
-             * @param EEM_Base   $model           used
2871
-             * @param array      $fields_n_values fields and their values
2872
-             * @param int|string the              ID of the newly-inserted model object
2873
-             */
2874
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2875
-            return $new_id;
2876
-        }
2877
-        return false;
2878
-    }
2879
-
2880
-
2881
-
2882
-    /**
2883
-     * Checks that the result would satisfy the unique indexes on this model
2884
-     *
2885
-     * @param array  $field_n_values
2886
-     * @param string $action
2887
-     * @return boolean
2888
-     * @throws EE_Error
2889
-     */
2890
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2891
-    {
2892
-        foreach ($this->unique_indexes() as $index_name => $index) {
2893
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2894
-            if ($this->exists(array($uniqueness_where_params))) {
2895
-                EE_Error::add_error(
2896
-                    sprintf(
2897
-                        __(
2898
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2899
-                            "event_espresso"
2900
-                        ),
2901
-                        $action,
2902
-                        $this->_get_class_name(),
2903
-                        $index_name,
2904
-                        implode(",", $index->field_names()),
2905
-                        http_build_query($uniqueness_where_params)
2906
-                    ),
2907
-                    __FILE__,
2908
-                    __FUNCTION__,
2909
-                    __LINE__
2910
-                );
2911
-                return false;
2912
-            }
2913
-        }
2914
-        return true;
2915
-    }
2916
-
2917
-
2918
-
2919
-    /**
2920
-     * Checks the database for an item that conflicts (ie, if this item were
2921
-     * saved to the DB would break some uniqueness requirement, like a primary key
2922
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2923
-     * can be either an EE_Base_Class or an array of fields n values
2924
-     *
2925
-     * @param EE_Base_Class|array $obj_or_fields_array
2926
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2927
-     *                                                 when looking for conflicts
2928
-     *                                                 (ie, if false, we ignore the model object's primary key
2929
-     *                                                 when finding "conflicts". If true, it's also considered).
2930
-     *                                                 Only works for INT primary key,
2931
-     *                                                 STRING primary keys cannot be ignored
2932
-     * @throws EE_Error
2933
-     * @return EE_Base_Class|array
2934
-     */
2935
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2936
-    {
2937
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2938
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2939
-        } elseif (is_array($obj_or_fields_array)) {
2940
-            $fields_n_values = $obj_or_fields_array;
2941
-        } else {
2942
-            throw new EE_Error(
2943
-                sprintf(
2944
-                    __(
2945
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2946
-                        "event_espresso"
2947
-                    ),
2948
-                    get_class($this),
2949
-                    $obj_or_fields_array
2950
-                )
2951
-            );
2952
-        }
2953
-        $query_params = array();
2954
-        if (
2955
-            $this->has_primary_key_field()
2956
-            && ($include_primary_key
2957
-                || $this->get_primary_key_field()
2958
-                   instanceof
2959
-                   EE_Primary_Key_String_Field)
2960
-            && isset($fields_n_values[ $this->primary_key_name() ])
2961
-        ) {
2962
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2963
-        }
2964
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2965
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2966
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2967
-        }
2968
-        // if there is nothing to base this search on, then we shouldn't find anything
2969
-        if (empty($query_params)) {
2970
-            return array();
2971
-        }
2972
-        return $this->get_one($query_params);
2973
-    }
2974
-
2975
-
2976
-
2977
-    /**
2978
-     * Like count, but is optimized and returns a boolean instead of an int
2979
-     *
2980
-     * @param array $query_params
2981
-     * @return boolean
2982
-     * @throws EE_Error
2983
-     */
2984
-    public function exists($query_params)
2985
-    {
2986
-        $query_params['limit'] = 1;
2987
-        return $this->count($query_params) > 0;
2988
-    }
2989
-
2990
-
2991
-
2992
-    /**
2993
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2994
-     *
2995
-     * @param int|string $id
2996
-     * @return boolean
2997
-     * @throws EE_Error
2998
-     */
2999
-    public function exists_by_ID($id)
3000
-    {
3001
-        return $this->exists(
3002
-            array(
3003
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3004
-                array(
3005
-                    $this->primary_key_name() => $id,
3006
-                ),
3007
-            )
3008
-        );
3009
-    }
3010
-
3011
-
3012
-
3013
-    /**
3014
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3015
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3016
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3017
-     * on the main table)
3018
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3019
-     * cases where we want to call it directly rather than via insert().
3020
-     *
3021
-     * @access   protected
3022
-     * @param EE_Table_Base $table
3023
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3024
-     *                                       float
3025
-     * @param int           $new_id          for now we assume only int keys
3026
-     * @throws EE_Error
3027
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3028
-     * @return int ID of new row inserted, or FALSE on failure
3029
-     */
3030
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3031
-    {
3032
-        global $wpdb;
3033
-        $insertion_col_n_values = array();
3034
-        $format_for_insertion = array();
3035
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
3036
-        foreach ($fields_on_table as $field_name => $field_obj) {
3037
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3038
-            if ($field_obj->is_auto_increment()) {
3039
-                continue;
3040
-            }
3041
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3042
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3043
-            if ($prepared_value !== null) {
3044
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3045
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3046
-            }
3047
-        }
3048
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3049
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3050
-            // so add the fk to the main table as a column
3051
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3052
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3053
-        }
3054
-        // insert the new entry
3055
-        $result = $this->_do_wpdb_query(
3056
-            'insert',
3057
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3058
-        );
3059
-        if ($result === false) {
3060
-            return false;
3061
-        }
3062
-        // ok, now what do we return for the ID of the newly-inserted thing?
3063
-        if ($this->has_primary_key_field()) {
3064
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3065
-                return $wpdb->insert_id;
3066
-            }
3067
-            // it's not an auto-increment primary key, so
3068
-            // it must have been supplied
3069
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3070
-        }
3071
-        // we can't return a  primary key because there is none. instead return
3072
-        // a unique string indicating this model
3073
-        return $this->get_index_primary_key_string($fields_n_values);
3074
-    }
3075
-
3076
-
3077
-
3078
-    /**
3079
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3080
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3081
-     * and there is no default, we pass it along. WPDB will take care of it)
3082
-     *
3083
-     * @param EE_Model_Field_Base $field_obj
3084
-     * @param array               $fields_n_values
3085
-     * @return mixed string|int|float depending on what the table column will be expecting
3086
-     * @throws EE_Error
3087
-     */
3088
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3089
-    {
3090
-        // if this field doesn't allow nullable, don't allow it
3091
-        if (
3092
-            ! $field_obj->is_nullable()
3093
-            && (
3094
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3095
-                || $fields_n_values[ $field_obj->get_name() ] === null
3096
-            )
3097
-        ) {
3098
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3099
-        }
3100
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3101
-            ? $fields_n_values[ $field_obj->get_name() ]
3102
-            : null;
3103
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3104
-    }
3105
-
3106
-
3107
-
3108
-    /**
3109
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3110
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3111
-     * the field's prepare_for_set() method.
3112
-     *
3113
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3114
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3115
-     *                                   top of file)
3116
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3117
-     *                                   $value is a custom selection
3118
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3119
-     */
3120
-    private function _prepare_value_for_use_in_db($value, $field)
3121
-    {
3122
-        if ($field && $field instanceof EE_Model_Field_Base) {
3123
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3124
-            switch ($this->_values_already_prepared_by_model_object) {
3125
-                /** @noinspection PhpMissingBreakStatementInspection */
3126
-                case self::not_prepared_by_model_object:
3127
-                    $value = $field->prepare_for_set($value);
3128
-                // purposefully left out "return"
3129
-                // no break
3130
-                case self::prepared_by_model_object:
3131
-                    /** @noinspection SuspiciousAssignmentsInspection */
3132
-                    $value = $field->prepare_for_use_in_db($value);
3133
-                    // no break
3134
-                case self::prepared_for_use_in_db:
3135
-                    // leave the value alone
3136
-            }
3137
-            return $value;
3138
-            // phpcs:enable
3139
-        }
3140
-        return $value;
3141
-    }
3142
-
3143
-
3144
-
3145
-    /**
3146
-     * Returns the main table on this model
3147
-     *
3148
-     * @return EE_Primary_Table
3149
-     * @throws EE_Error
3150
-     */
3151
-    protected function _get_main_table()
3152
-    {
3153
-        foreach ($this->_tables as $table) {
3154
-            if ($table instanceof EE_Primary_Table) {
3155
-                return $table;
3156
-            }
3157
-        }
3158
-        throw new EE_Error(sprintf(__(
3159
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3160
-            'event_espresso'
3161
-        ), get_class($this)));
3162
-    }
3163
-
3164
-
3165
-
3166
-    /**
3167
-     * table
3168
-     * returns EE_Primary_Table table name
3169
-     *
3170
-     * @return string
3171
-     * @throws EE_Error
3172
-     */
3173
-    public function table()
3174
-    {
3175
-        return $this->_get_main_table()->get_table_name();
3176
-    }
3177
-
3178
-
3179
-
3180
-    /**
3181
-     * table
3182
-     * returns first EE_Secondary_Table table name
3183
-     *
3184
-     * @return string
3185
-     */
3186
-    public function second_table()
3187
-    {
3188
-        // grab second table from tables array
3189
-        $second_table = end($this->_tables);
3190
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3191
-    }
3192
-
3193
-
3194
-
3195
-    /**
3196
-     * get_table_obj_by_alias
3197
-     * returns table name given it's alias
3198
-     *
3199
-     * @param string $table_alias
3200
-     * @return EE_Primary_Table | EE_Secondary_Table
3201
-     */
3202
-    public function get_table_obj_by_alias($table_alias = '')
3203
-    {
3204
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3205
-    }
3206
-
3207
-
3208
-
3209
-    /**
3210
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3211
-     *
3212
-     * @return EE_Secondary_Table[]
3213
-     */
3214
-    protected function _get_other_tables()
3215
-    {
3216
-        $other_tables = array();
3217
-        foreach ($this->_tables as $table_alias => $table) {
3218
-            if ($table instanceof EE_Secondary_Table) {
3219
-                $other_tables[ $table_alias ] = $table;
3220
-            }
3221
-        }
3222
-        return $other_tables;
3223
-    }
3224
-
3225
-
3226
-
3227
-    /**
3228
-     * Finds all the fields that correspond to the given table
3229
-     *
3230
-     * @param string $table_alias , array key in EEM_Base::_tables
3231
-     * @return EE_Model_Field_Base[]
3232
-     */
3233
-    public function _get_fields_for_table($table_alias)
3234
-    {
3235
-        return $this->_fields[ $table_alias ];
3236
-    }
3237
-
3238
-
3239
-
3240
-    /**
3241
-     * Recurses through all the where parameters, and finds all the related models we'll need
3242
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3243
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3244
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3245
-     * related Registration, Transaction, and Payment models.
3246
-     *
3247
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3248
-     * @return EE_Model_Query_Info_Carrier
3249
-     * @throws EE_Error
3250
-     */
3251
-    public function _extract_related_models_from_query($query_params)
3252
-    {
3253
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3254
-        if (array_key_exists(0, $query_params)) {
3255
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3256
-        }
3257
-        if (array_key_exists('group_by', $query_params)) {
3258
-            if (is_array($query_params['group_by'])) {
3259
-                $this->_extract_related_models_from_sub_params_array_values(
3260
-                    $query_params['group_by'],
3261
-                    $query_info_carrier,
3262
-                    'group_by'
3263
-                );
3264
-            } elseif (! empty($query_params['group_by'])) {
3265
-                $this->_extract_related_model_info_from_query_param(
3266
-                    $query_params['group_by'],
3267
-                    $query_info_carrier,
3268
-                    'group_by'
3269
-                );
3270
-            }
3271
-        }
3272
-        if (array_key_exists('having', $query_params)) {
3273
-            $this->_extract_related_models_from_sub_params_array_keys(
3274
-                $query_params[0],
3275
-                $query_info_carrier,
3276
-                'having'
3277
-            );
3278
-        }
3279
-        if (array_key_exists('order_by', $query_params)) {
3280
-            if (is_array($query_params['order_by'])) {
3281
-                $this->_extract_related_models_from_sub_params_array_keys(
3282
-                    $query_params['order_by'],
3283
-                    $query_info_carrier,
3284
-                    'order_by'
3285
-                );
3286
-            } elseif (! empty($query_params['order_by'])) {
3287
-                $this->_extract_related_model_info_from_query_param(
3288
-                    $query_params['order_by'],
3289
-                    $query_info_carrier,
3290
-                    'order_by'
3291
-                );
3292
-            }
3293
-        }
3294
-        if (array_key_exists('force_join', $query_params)) {
3295
-            $this->_extract_related_models_from_sub_params_array_values(
3296
-                $query_params['force_join'],
3297
-                $query_info_carrier,
3298
-                'force_join'
3299
-            );
3300
-        }
3301
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3302
-        return $query_info_carrier;
3303
-    }
3304
-
3305
-
3306
-
3307
-    /**
3308
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3309
-     *
3310
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3311
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3312
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3313
-     * @throws EE_Error
3314
-     * @return \EE_Model_Query_Info_Carrier
3315
-     */
3316
-    private function _extract_related_models_from_sub_params_array_keys(
3317
-        $sub_query_params,
3318
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3319
-        $query_param_type
3320
-    ) {
3321
-        if (! empty($sub_query_params)) {
3322
-            $sub_query_params = (array) $sub_query_params;
3323
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3324
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3325
-                $this->_extract_related_model_info_from_query_param(
3326
-                    $param,
3327
-                    $model_query_info_carrier,
3328
-                    $query_param_type
3329
-                );
3330
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3331
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3332
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3333
-                // of array('Registration.TXN_ID'=>23)
3334
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3335
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3336
-                    if (! is_array($possibly_array_of_params)) {
3337
-                        throw new EE_Error(sprintf(
3338
-                            __(
3339
-                                "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'))",
3340
-                                "event_espresso"
3341
-                            ),
3342
-                            $param,
3343
-                            $possibly_array_of_params
3344
-                        ));
3345
-                    }
3346
-                    $this->_extract_related_models_from_sub_params_array_keys(
3347
-                        $possibly_array_of_params,
3348
-                        $model_query_info_carrier,
3349
-                        $query_param_type
3350
-                    );
3351
-                } elseif (
3352
-                    $query_param_type === 0 // ie WHERE
3353
-                          && is_array($possibly_array_of_params)
3354
-                          && isset($possibly_array_of_params[2])
3355
-                          && $possibly_array_of_params[2] == true
3356
-                ) {
3357
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3358
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3359
-                    // from which we should extract query parameters!
3360
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3361
-                        throw new EE_Error(sprintf(__(
3362
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3363
-                            "event_espresso"
3364
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3365
-                    }
3366
-                    $this->_extract_related_model_info_from_query_param(
3367
-                        $possibly_array_of_params[1],
3368
-                        $model_query_info_carrier,
3369
-                        $query_param_type
3370
-                    );
3371
-                }
3372
-            }
3373
-        }
3374
-        return $model_query_info_carrier;
3375
-    }
3376
-
3377
-
3378
-
3379
-    /**
3380
-     * For extracting related models from forced_joins, where the array values contain the info about what
3381
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3382
-     *
3383
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3384
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3385
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3386
-     * @throws EE_Error
3387
-     * @return \EE_Model_Query_Info_Carrier
3388
-     */
3389
-    private function _extract_related_models_from_sub_params_array_values(
3390
-        $sub_query_params,
3391
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3392
-        $query_param_type
3393
-    ) {
3394
-        if (! empty($sub_query_params)) {
3395
-            if (! is_array($sub_query_params)) {
3396
-                throw new EE_Error(sprintf(
3397
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3398
-                    $sub_query_params
3399
-                ));
3400
-            }
3401
-            foreach ($sub_query_params as $param) {
3402
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3403
-                $this->_extract_related_model_info_from_query_param(
3404
-                    $param,
3405
-                    $model_query_info_carrier,
3406
-                    $query_param_type
3407
-                );
3408
-            }
3409
-        }
3410
-        return $model_query_info_carrier;
3411
-    }
3412
-
3413
-
3414
-    /**
3415
-     * Extract all the query parts from  model query params
3416
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3417
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3418
-     * but use them in a different order. Eg, we need to know what models we are querying
3419
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3420
-     * other models before we can finalize the where clause SQL.
3421
-     *
3422
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3423
-     * @throws EE_Error
3424
-     * @return EE_Model_Query_Info_Carrier
3425
-     * @throws ModelConfigurationException
3426
-     */
3427
-    public function _create_model_query_info_carrier($query_params)
3428
-    {
3429
-        if (! is_array($query_params)) {
3430
-            EE_Error::doing_it_wrong(
3431
-                'EEM_Base::_create_model_query_info_carrier',
3432
-                sprintf(
3433
-                    __(
3434
-                        '$query_params should be an array, you passed a variable of type %s',
3435
-                        'event_espresso'
3436
-                    ),
3437
-                    gettype($query_params)
3438
-                ),
3439
-                '4.6.0'
3440
-            );
3441
-            $query_params = array();
3442
-        }
3443
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3444
-        // first check if we should alter the query to account for caps or not
3445
-        // because the caps might require us to do extra joins
3446
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3447
-            $query_params[0] = array_replace_recursive(
3448
-                $query_params[0],
3449
-                $this->caps_where_conditions($query_params['caps'])
3450
-            );
3451
-        }
3452
-
3453
-        // check if we should alter the query to remove data related to protected
3454
-        // custom post types
3455
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3456
-            $where_param_key_for_password = $this->modelChainAndPassword();
3457
-            // only include if related to a cpt where no password has been set
3458
-            $query_params[0]['OR*nopassword'] = array(
3459
-                $where_param_key_for_password => '',
3460
-                $where_param_key_for_password . '*' => array('IS_NULL')
3461
-            );
3462
-        }
3463
-        $query_object = $this->_extract_related_models_from_query($query_params);
3464
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3465
-        foreach ($query_params[0] as $key => $value) {
3466
-            if (is_int($key)) {
3467
-                throw new EE_Error(
3468
-                    sprintf(
3469
-                        __(
3470
-                            "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.",
3471
-                            "event_espresso"
3472
-                        ),
3473
-                        $key,
3474
-                        var_export($value, true),
3475
-                        var_export($query_params, true),
3476
-                        get_class($this)
3477
-                    )
3478
-                );
3479
-            }
3480
-        }
3481
-        if (
3482
-            array_key_exists('default_where_conditions', $query_params)
3483
-            && ! empty($query_params['default_where_conditions'])
3484
-        ) {
3485
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3486
-        } else {
3487
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3488
-        }
3489
-        $query_params[0] = array_merge(
3490
-            $this->_get_default_where_conditions_for_models_in_query(
3491
-                $query_object,
3492
-                $use_default_where_conditions,
3493
-                $query_params[0]
3494
-            ),
3495
-            $query_params[0]
3496
-        );
3497
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3498
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3499
-        // So we need to setup a subquery and use that for the main join.
3500
-        // Note for now this only works on the primary table for the model.
3501
-        // So for instance, you could set the limit array like this:
3502
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3503
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3504
-            $query_object->set_main_model_join_sql(
3505
-                $this->_construct_limit_join_select(
3506
-                    $query_params['on_join_limit'][0],
3507
-                    $query_params['on_join_limit'][1]
3508
-                )
3509
-            );
3510
-        }
3511
-        // set limit
3512
-        if (array_key_exists('limit', $query_params)) {
3513
-            if (is_array($query_params['limit'])) {
3514
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3515
-                    $e = sprintf(
3516
-                        __(
3517
-                            "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)",
3518
-                            "event_espresso"
3519
-                        ),
3520
-                        http_build_query($query_params['limit'])
3521
-                    );
3522
-                    throw new EE_Error($e . "|" . $e);
3523
-                }
3524
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3525
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3526
-            } elseif (! empty($query_params['limit'])) {
3527
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3528
-            }
3529
-        }
3530
-        // set order by
3531
-        if (array_key_exists('order_by', $query_params)) {
3532
-            if (is_array($query_params['order_by'])) {
3533
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3534
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3535
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3536
-                if (array_key_exists('order', $query_params)) {
3537
-                    throw new EE_Error(
3538
-                        sprintf(
3539
-                            __(
3540
-                                "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 ",
3541
-                                "event_espresso"
3542
-                            ),
3543
-                            get_class($this),
3544
-                            implode(", ", array_keys($query_params['order_by'])),
3545
-                            implode(", ", $query_params['order_by']),
3546
-                            $query_params['order']
3547
-                        )
3548
-                    );
3549
-                }
3550
-                $this->_extract_related_models_from_sub_params_array_keys(
3551
-                    $query_params['order_by'],
3552
-                    $query_object,
3553
-                    'order_by'
3554
-                );
3555
-                // assume it's an array of fields to order by
3556
-                $order_array = array();
3557
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3558
-                    $order = $this->_extract_order($order);
3559
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3560
-                }
3561
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3562
-            } elseif (! empty($query_params['order_by'])) {
3563
-                $this->_extract_related_model_info_from_query_param(
3564
-                    $query_params['order_by'],
3565
-                    $query_object,
3566
-                    'order',
3567
-                    $query_params['order_by']
3568
-                );
3569
-                $order = isset($query_params['order'])
3570
-                    ? $this->_extract_order($query_params['order'])
3571
-                    : 'DESC';
3572
-                $query_object->set_order_by_sql(
3573
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3574
-                );
3575
-            }
3576
-        }
3577
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3578
-        if (
3579
-            ! array_key_exists('order_by', $query_params)
3580
-            && array_key_exists('order', $query_params)
3581
-            && ! empty($query_params['order'])
3582
-        ) {
3583
-            $pk_field = $this->get_primary_key_field();
3584
-            $order = $this->_extract_order($query_params['order']);
3585
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3586
-        }
3587
-        // set group by
3588
-        if (array_key_exists('group_by', $query_params)) {
3589
-            if (is_array($query_params['group_by'])) {
3590
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3591
-                $group_by_array = array();
3592
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3593
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3594
-                }
3595
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3596
-            } elseif (! empty($query_params['group_by'])) {
3597
-                $query_object->set_group_by_sql(
3598
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3599
-                );
3600
-            }
3601
-        }
3602
-        // set having
3603
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3604
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3605
-        }
3606
-        // now, just verify they didn't pass anything wack
3607
-        foreach ($query_params as $query_key => $query_value) {
3608
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3609
-                throw new EE_Error(
3610
-                    sprintf(
3611
-                        __(
3612
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3613
-                            'event_espresso'
3614
-                        ),
3615
-                        $query_key,
3616
-                        get_class($this),
3617
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3618
-                        implode(',', $this->_allowed_query_params)
3619
-                    )
3620
-                );
3621
-            }
3622
-        }
3623
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3624
-        if (empty($main_model_join_sql)) {
3625
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3626
-        }
3627
-        return $query_object;
3628
-    }
3629
-
3630
-
3631
-
3632
-    /**
3633
-     * Gets the where conditions that should be imposed on the query based on the
3634
-     * context (eg reading frontend, backend, edit or delete).
3635
-     *
3636
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3637
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3638
-     * @throws EE_Error
3639
-     */
3640
-    public function caps_where_conditions($context = self::caps_read)
3641
-    {
3642
-        EEM_Base::verify_is_valid_cap_context($context);
3643
-        $cap_where_conditions = array();
3644
-        $cap_restrictions = $this->caps_missing($context);
3645
-        /**
3646
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3647
-         */
3648
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3649
-            $cap_where_conditions = array_replace_recursive(
3650
-                $cap_where_conditions,
3651
-                $restriction_if_no_cap->get_default_where_conditions()
3652
-            );
3653
-        }
3654
-        return apply_filters(
3655
-            'FHEE__EEM_Base__caps_where_conditions__return',
3656
-            $cap_where_conditions,
3657
-            $this,
3658
-            $context,
3659
-            $cap_restrictions
3660
-        );
3661
-    }
3662
-
3663
-
3664
-
3665
-    /**
3666
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3667
-     * otherwise throws an exception
3668
-     *
3669
-     * @param string $should_be_order_string
3670
-     * @return string either ASC, asc, DESC or desc
3671
-     * @throws EE_Error
3672
-     */
3673
-    private function _extract_order($should_be_order_string)
3674
-    {
3675
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3676
-            return $should_be_order_string;
3677
-        }
3678
-        throw new EE_Error(
3679
-            sprintf(
3680
-                __(
3681
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3682
-                    "event_espresso"
3683
-                ),
3684
-                get_class($this),
3685
-                $should_be_order_string
3686
-            )
3687
-        );
3688
-    }
3689
-
3690
-
3691
-
3692
-    /**
3693
-     * Looks at all the models which are included in this query, and asks each
3694
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3695
-     * so they can be merged
3696
-     *
3697
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3698
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3699
-     *                                                                  'none' means NO default where conditions will
3700
-     *                                                                  be used AT ALL during this query.
3701
-     *                                                                  'other_models_only' means default where
3702
-     *                                                                  conditions from other models will be used, but
3703
-     *                                                                  not for this primary model. 'all', the default,
3704
-     *                                                                  means default where conditions will apply as
3705
-     *                                                                  normal
3706
-     * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3707
-     * @throws EE_Error
3708
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3709
-     */
3710
-    private function _get_default_where_conditions_for_models_in_query(
3711
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3712
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3713
-        $where_query_params = array()
3714
-    ) {
3715
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3716
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3717
-            throw new EE_Error(sprintf(
3718
-                __(
3719
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3720
-                    "event_espresso"
3721
-                ),
3722
-                $use_default_where_conditions,
3723
-                implode(", ", $allowed_used_default_where_conditions_values)
3724
-            ));
3725
-        }
3726
-        $universal_query_params = array();
3727
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3728
-            $universal_query_params = $this->_get_default_where_conditions();
3729
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3730
-            $universal_query_params = $this->_get_minimum_where_conditions();
3731
-        }
3732
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3733
-            $related_model = $this->get_related_model_obj($model_name);
3734
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3735
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3736
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3737
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3738
-            } else {
3739
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3740
-                continue;
3741
-            }
3742
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3743
-                $related_model_universal_where_params,
3744
-                $where_query_params,
3745
-                $related_model,
3746
-                $model_relation_path
3747
-            );
3748
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3749
-                $universal_query_params,
3750
-                $overrides
3751
-            );
3752
-        }
3753
-        return $universal_query_params;
3754
-    }
3755
-
3756
-
3757
-
3758
-    /**
3759
-     * Determines whether or not we should use default where conditions for the model in question
3760
-     * (this model, or other related models).
3761
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3762
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3763
-     * We should use default where conditions on related models when they requested to use default where conditions
3764
-     * on all models, or specifically just on other related models
3765
-     * @param      $default_where_conditions_value
3766
-     * @param bool $for_this_model false means this is for OTHER related models
3767
-     * @return bool
3768
-     */
3769
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3770
-    {
3771
-        return (
3772
-                   $for_this_model
3773
-                   && in_array(
3774
-                       $default_where_conditions_value,
3775
-                       array(
3776
-                           EEM_Base::default_where_conditions_all,
3777
-                           EEM_Base::default_where_conditions_this_only,
3778
-                           EEM_Base::default_where_conditions_minimum_others,
3779
-                       ),
3780
-                       true
3781
-                   )
3782
-               )
3783
-               || (
3784
-                   ! $for_this_model
3785
-                   && in_array(
3786
-                       $default_where_conditions_value,
3787
-                       array(
3788
-                           EEM_Base::default_where_conditions_all,
3789
-                           EEM_Base::default_where_conditions_others_only,
3790
-                       ),
3791
-                       true
3792
-                   )
3793
-               );
3794
-    }
3795
-
3796
-    /**
3797
-     * Determines whether or not we should use default minimum conditions for the model in question
3798
-     * (this model, or other related models).
3799
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3800
-     * where conditions.
3801
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3802
-     * on this model or others
3803
-     * @param      $default_where_conditions_value
3804
-     * @param bool $for_this_model false means this is for OTHER related models
3805
-     * @return bool
3806
-     */
3807
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3808
-    {
3809
-        return (
3810
-                   $for_this_model
3811
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3812
-               )
3813
-               || (
3814
-                   ! $for_this_model
3815
-                   && in_array(
3816
-                       $default_where_conditions_value,
3817
-                       array(
3818
-                           EEM_Base::default_where_conditions_minimum_others,
3819
-                           EEM_Base::default_where_conditions_minimum_all,
3820
-                       ),
3821
-                       true
3822
-                   )
3823
-               );
3824
-    }
3825
-
3826
-
3827
-    /**
3828
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3829
-     * then we also add a special where condition which allows for that model's primary key
3830
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3831
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3832
-     *
3833
-     * @param array    $default_where_conditions
3834
-     * @param array    $provided_where_conditions
3835
-     * @param EEM_Base $model
3836
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3837
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3838
-     * @throws EE_Error
3839
-     */
3840
-    private function _override_defaults_or_make_null_friendly(
3841
-        $default_where_conditions,
3842
-        $provided_where_conditions,
3843
-        $model,
3844
-        $model_relation_path
3845
-    ) {
3846
-        $null_friendly_where_conditions = array();
3847
-        $none_overridden = true;
3848
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3849
-        foreach ($default_where_conditions as $key => $val) {
3850
-            if (isset($provided_where_conditions[ $key ])) {
3851
-                $none_overridden = false;
3852
-            } else {
3853
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3854
-            }
3855
-        }
3856
-        if ($none_overridden && $default_where_conditions) {
3857
-            if ($model->has_primary_key_field()) {
3858
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3859
-                                                                                . "."
3860
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3861
-            }/*else{
43
+	/**
44
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
45
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
46
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
47
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
48
+	 *
49
+	 * @var boolean
50
+	 */
51
+	private $_values_already_prepared_by_model_object = 0;
52
+
53
+	/**
54
+	 * when $_values_already_prepared_by_model_object equals this, we assume
55
+	 * the data is just like form input that needs to have the model fields'
56
+	 * prepare_for_set and prepare_for_use_in_db called on it
57
+	 */
58
+	const not_prepared_by_model_object = 0;
59
+
60
+	/**
61
+	 * when $_values_already_prepared_by_model_object equals this, we
62
+	 * assume this value is coming from a model object and doesn't need to have
63
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
64
+	 */
65
+	const prepared_by_model_object = 1;
66
+
67
+	/**
68
+	 * when $_values_already_prepared_by_model_object equals this, we assume
69
+	 * the values are already to be used in the database (ie no processing is done
70
+	 * on them by the model's fields)
71
+	 */
72
+	const prepared_for_use_in_db = 2;
73
+
74
+
75
+	protected $singular_item = 'Item';
76
+
77
+	protected $plural_item   = 'Items';
78
+
79
+	/**
80
+	 * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
81
+	 */
82
+	protected $_tables;
83
+
84
+	/**
85
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
86
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
87
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
88
+	 *
89
+	 * @var EE_Model_Field_Base[][] $_fields
90
+	 */
91
+	protected $_fields;
92
+
93
+	/**
94
+	 * array of different kinds of relations
95
+	 *
96
+	 * @var EE_Model_Relation_Base[] $_model_relations
97
+	 */
98
+	protected $_model_relations = [];
99
+
100
+	/**
101
+	 * @var EE_Index[] $_indexes
102
+	 */
103
+	protected $_indexes = array();
104
+
105
+	/**
106
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
107
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
108
+	 * by setting the same columns as used in these queries in the query yourself.
109
+	 *
110
+	 * @var EE_Default_Where_Conditions
111
+	 */
112
+	protected $_default_where_conditions_strategy;
113
+
114
+	/**
115
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
116
+	 * This is particularly useful when you want something between 'none' and 'default'
117
+	 *
118
+	 * @var EE_Default_Where_Conditions
119
+	 */
120
+	protected $_minimum_where_conditions_strategy;
121
+
122
+	/**
123
+	 * String describing how to find the "owner" of this model's objects.
124
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
125
+	 * But when there isn't, this indicates which related model, or transiently-related model,
126
+	 * has the foreign key to the wp_users table.
127
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
128
+	 * related to events, and events have a foreign key to wp_users.
129
+	 * On EEM_Transaction, this would be 'Transaction.Event'
130
+	 *
131
+	 * @var string
132
+	 */
133
+	protected $_model_chain_to_wp_user = '';
134
+
135
+	/**
136
+	 * String describing how to find the model with a password controlling access to this model. This property has the
137
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
138
+	 * This value is the path of models to follow to arrive at the model with the password field.
139
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
140
+	 * model with a password that should affect reading this on the front-end.
141
+	 * Eg this is an empty string for the Event model because it has a password.
142
+	 * This is null for the Registration model, because its event's password has no bearing on whether
143
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
144
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
145
+	 * should hide tickets for datetimes for events that have a password set.
146
+	 * @var string |null
147
+	 */
148
+	protected $model_chain_to_password = null;
149
+
150
+	/**
151
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
+	 * don't need it (particularly CPT models)
153
+	 *
154
+	 * @var bool
155
+	 */
156
+	protected $_ignore_where_strategy = false;
157
+
158
+	/**
159
+	 * String used in caps relating to this model. Eg, if the caps relating to this
160
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
+	 *
162
+	 * @var string. If null it hasn't been initialized yet. If false then we
163
+	 * have indicated capabilities don't apply to this
164
+	 */
165
+	protected $_caps_slug = null;
166
+
167
+	/**
168
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
+	 * and next-level keys are capability names, and each's value is a
170
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
172
+	 * and then each capability in the corresponding sub-array that they're missing
173
+	 * adds the where conditions onto the query.
174
+	 *
175
+	 * @var array
176
+	 */
177
+	protected $_cap_restrictions = array(
178
+		self::caps_read       => array(),
179
+		self::caps_read_admin => array(),
180
+		self::caps_edit       => array(),
181
+		self::caps_delete     => array(),
182
+	);
183
+
184
+	/**
185
+	 * Array defining which cap restriction generators to use to create default
186
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
187
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
+	 * automatically set this to false (not just null).
190
+	 *
191
+	 * @var EE_Restriction_Generator_Base[]
192
+	 */
193
+	protected $_cap_restriction_generators = array();
194
+
195
+	/**
196
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
+	 */
198
+	const caps_read       = 'read';
199
+
200
+	const caps_read_admin = 'read_admin';
201
+
202
+	const caps_edit       = 'edit';
203
+
204
+	const caps_delete     = 'delete';
205
+
206
+	/**
207
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
+	 * maps to 'read' because when looking for relevant permissions we're going to use
210
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
211
+	 *
212
+	 * @var array
213
+	 */
214
+	protected $_cap_contexts_to_cap_action_map = array(
215
+		self::caps_read       => 'read',
216
+		self::caps_read_admin => 'read',
217
+		self::caps_edit       => 'edit',
218
+		self::caps_delete     => 'delete',
219
+	);
220
+
221
+	/**
222
+	 * Timezone
223
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
+	 * EE_Datetime_Field data type will have access to it.
227
+	 *
228
+	 * @var string
229
+	 */
230
+	protected $_timezone;
231
+
232
+
233
+	/**
234
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
+	 * multisite.
236
+	 *
237
+	 * @var int
238
+	 */
239
+	protected static $_model_query_blog_id;
240
+
241
+	/**
242
+	 * A copy of _fields, except the array keys are the model names pointed to by
243
+	 * the field
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cache_foreign_key_to_fields = array();
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, indexed by their name
251
+	 *
252
+	 * @var EE_Model_Field_Base[]
253
+	 */
254
+	private $_cached_fields = null;
255
+
256
+	/**
257
+	 * Cached list of all the fields on the model, except those that are
258
+	 * marked as only pertinent to the database
259
+	 *
260
+	 * @var EE_Model_Field_Base[]
261
+	 */
262
+	private $_cached_fields_non_db_only = null;
263
+
264
+	/**
265
+	 * A cached reference to the primary key for quick lookup
266
+	 *
267
+	 * @var EE_Model_Field_Base
268
+	 */
269
+	private $_primary_key_field = null;
270
+
271
+	/**
272
+	 * Flag indicating whether this model has a primary key or not
273
+	 *
274
+	 * @var boolean
275
+	 */
276
+	protected $_has_primary_key_field = null;
277
+
278
+	/**
279
+	 * array in the format:  [ FK alias => full PK ]
280
+	 * where keys are local column name aliases for foreign keys
281
+	 * and values are the fully qualified column name for the primary key they represent
282
+	 *  ex:
283
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
+	 *
285
+	 * @var array $foreign_key_aliases
286
+	 */
287
+	protected $foreign_key_aliases = [];
288
+
289
+	/**
290
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
291
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
+	 * This should be true for models that deal with data that should exist independent of EE.
293
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
295
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
297
+	 * @var boolean
298
+	 */
299
+	protected $_wp_core_model = false;
300
+
301
+	/**
302
+	 * @var bool stores whether this model has a password field or not.
303
+	 * null until initialized by hasPasswordField()
304
+	 */
305
+	protected $has_password_field;
306
+
307
+	/**
308
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
309
+	 */
310
+	protected $password_field;
311
+
312
+	/**
313
+	 *    List of valid operators that can be used for querying.
314
+	 * The keys are all operators we'll accept, the values are the real SQL
315
+	 * operators used
316
+	 *
317
+	 * @var array
318
+	 */
319
+	protected $_valid_operators = array(
320
+		'='           => '=',
321
+		'<='          => '<=',
322
+		'<'           => '<',
323
+		'>='          => '>=',
324
+		'>'           => '>',
325
+		'!='          => '!=',
326
+		'LIKE'        => 'LIKE',
327
+		'like'        => 'LIKE',
328
+		'NOT_LIKE'    => 'NOT LIKE',
329
+		'not_like'    => 'NOT LIKE',
330
+		'NOT LIKE'    => 'NOT LIKE',
331
+		'not like'    => 'NOT LIKE',
332
+		'IN'          => 'IN',
333
+		'in'          => 'IN',
334
+		'NOT_IN'      => 'NOT IN',
335
+		'not_in'      => 'NOT IN',
336
+		'NOT IN'      => 'NOT IN',
337
+		'not in'      => 'NOT IN',
338
+		'between'     => 'BETWEEN',
339
+		'BETWEEN'     => 'BETWEEN',
340
+		'IS_NOT_NULL' => 'IS NOT NULL',
341
+		'is_not_null' => 'IS NOT NULL',
342
+		'IS NOT NULL' => 'IS NOT NULL',
343
+		'is not null' => 'IS NOT NULL',
344
+		'IS_NULL'     => 'IS NULL',
345
+		'is_null'     => 'IS NULL',
346
+		'IS NULL'     => 'IS NULL',
347
+		'is null'     => 'IS NULL',
348
+		'REGEXP'      => 'REGEXP',
349
+		'regexp'      => 'REGEXP',
350
+		'NOT_REGEXP'  => 'NOT REGEXP',
351
+		'not_regexp'  => 'NOT REGEXP',
352
+		'NOT REGEXP'  => 'NOT REGEXP',
353
+		'not regexp'  => 'NOT REGEXP',
354
+	);
355
+
356
+	/**
357
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
358
+	 *
359
+	 * @var array
360
+	 */
361
+	protected $_in_style_operators = array('IN', 'NOT IN');
362
+
363
+	/**
364
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
365
+	 * '12-31-2012'"
366
+	 *
367
+	 * @var array
368
+	 */
369
+	protected $_between_style_operators = array('BETWEEN');
370
+
371
+	/**
372
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
373
+	 * @var array
374
+	 */
375
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
376
+	/**
377
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
378
+	 * on a join table.
379
+	 *
380
+	 * @var array
381
+	 */
382
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
383
+
384
+	/**
385
+	 * Allowed values for $query_params['order'] for ordering in queries
386
+	 *
387
+	 * @var array
388
+	 */
389
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
390
+
391
+	/**
392
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
393
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
394
+	 *
395
+	 * @var array
396
+	 */
397
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
398
+
399
+	/**
400
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
401
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
402
+	 *
403
+	 * @var array
404
+	 */
405
+	private $_allowed_query_params = array(
406
+		0,
407
+		'limit',
408
+		'order_by',
409
+		'group_by',
410
+		'having',
411
+		'force_join',
412
+		'order',
413
+		'on_join_limit',
414
+		'default_where_conditions',
415
+		'caps',
416
+		'extra_selects',
417
+		'exclude_protected',
418
+	);
419
+
420
+	/**
421
+	 * All the data types that can be used in $wpdb->prepare statements.
422
+	 *
423
+	 * @var array
424
+	 */
425
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
426
+
427
+	/**
428
+	 * @var EE_Registry $EE
429
+	 */
430
+	protected $EE = null;
431
+
432
+
433
+	/**
434
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
435
+	 *
436
+	 * @var int
437
+	 */
438
+	protected $_show_next_x_db_queries = 0;
439
+
440
+	/**
441
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
442
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
443
+	 * WHERE, GROUP_BY, etc.
444
+	 *
445
+	 * @var CustomSelects
446
+	 */
447
+	protected $_custom_selections = array();
448
+
449
+	/**
450
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
451
+	 * caches every model object we've fetched from the DB on this request
452
+	 *
453
+	 * @var array
454
+	 */
455
+	protected $_entity_map;
456
+
457
+	/**
458
+	 * @var LoaderInterface
459
+	 */
460
+	private static $loader;
461
+
462
+	/**
463
+	 * @var Mirror
464
+	 */
465
+	private static $mirror;
466
+
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
+	/**
548
+	 * About all child constructors:
549
+	 * they should define the _tables, _fields and _model_relations arrays.
550
+	 * Should ALWAYS be called after child constructor.
551
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
552
+	 * finalizes constructing all the object's attributes.
553
+	 * Generally, rather than requiring a child to code
554
+	 * $this->_tables = array(
555
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
556
+	 *        ...);
557
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
558
+	 * each EE_Table has a function to set the table's alias after the constructor, using
559
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
560
+	 * do something similar.
561
+	 *
562
+	 * @param null $timezone
563
+	 * @throws EE_Error
564
+	 */
565
+	protected function __construct($timezone = null)
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
+					__(
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
+				/** @var $table_obj EE_Secondary_Table */
597
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
598
+			}
599
+		}
600
+		/**
601
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
602
+		 * EE_Register_Model_Extension
603
+		 *
604
+		 * @param EE_Model_Field_Base[] $_fields
605
+		 */
606
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
607
+		$this->_invalidate_field_caches();
608
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
609
+			if (! array_key_exists($table_alias, $this->_tables)) {
610
+				throw new EE_Error(sprintf(__(
611
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
612
+					'event_espresso'
613
+				), $table_alias, implode(",", $this->_fields)));
614
+			}
615
+			foreach ($fields_for_table as $field_name => $field_obj) {
616
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
617
+				// primary key field base has a slightly different _construct_finalize
618
+				/** @var $field_obj EE_Model_Field_Base */
619
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
620
+			}
621
+		}
622
+		// everything is related to Extra_Meta
623
+		if (get_class($this) !== 'EEM_Extra_Meta') {
624
+			// make extra meta related to everything, but don't block deleting things just
625
+			// because they have related extra meta info. For now just orphan those extra meta
626
+			// in the future we should automatically delete them
627
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
628
+		}
629
+		// and change logs
630
+		if (get_class($this) !== 'EEM_Change_Log') {
631
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
632
+		}
633
+		/**
634
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
635
+		 * EE_Register_Model_Extension
636
+		 *
637
+		 * @param EE_Model_Relation_Base[] $_model_relations
638
+		 */
639
+		$this->_model_relations = (array) apply_filters(
640
+			'FHEE__' . get_class($this) . '__construct__model_relations',
641
+			$this->_model_relations
642
+		);
643
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
644
+			/** @var $relation_obj EE_Model_Relation_Base */
645
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
646
+		}
647
+		foreach ($this->_indexes as $index_name => $index_obj) {
648
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
649
+		}
650
+		$this->set_timezone($timezone);
651
+		// finalize default where condition strategy, or set default
652
+		if (! $this->_default_where_conditions_strategy) {
653
+			// nothing was set during child constructor, so set default
654
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
655
+		}
656
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
657
+		if (! $this->_minimum_where_conditions_strategy) {
658
+			// nothing was set during child constructor, so set default
659
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
660
+		}
661
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
662
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
663
+		// to indicate to NOT set it, set it to the logical default
664
+		if ($this->_caps_slug === null) {
665
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
666
+		}
667
+		// initialize the standard cap restriction generators if none were specified by the child constructor
668
+		if (is_array($this->_cap_restriction_generators)) {
669
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
670
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
671
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
672
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
673
+						new EE_Restriction_Generator_Protected(),
674
+						$cap_context,
675
+						$this
676
+					);
677
+				}
678
+			}
679
+		}
680
+		// if there are cap restriction generators, use them to make the default cap restrictions
681
+		if (is_array($this->_cap_restriction_generators)) {
682
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
683
+				if (! $generator_object) {
684
+					continue;
685
+				}
686
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
687
+					throw new EE_Error(
688
+						sprintf(
689
+							__(
690
+								'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.',
691
+								'event_espresso'
692
+							),
693
+							$context,
694
+							$this->get_this_model_name()
695
+						)
696
+					);
697
+				}
698
+				$action = $this->cap_action_for_context($context);
699
+				if (! $generator_object->construction_finalized()) {
700
+					$generator_object->_construct_finalize($this, $action);
701
+				}
702
+			}
703
+		}
704
+		do_action('AHEE__' . get_class($this) . '__construct__end');
705
+	}
706
+
707
+
708
+	/**
709
+	 * @return LoaderInterface
710
+	 * @throws InvalidArgumentException
711
+	 * @throws InvalidDataTypeException
712
+	 * @throws InvalidInterfaceException
713
+	 */
714
+	protected static function getLoader(): LoaderInterface
715
+	{
716
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
717
+			EEM_Base::$loader = LoaderFactory::getLoader();
718
+		}
719
+		return EEM_Base::$loader;
720
+	}
721
+
722
+
723
+	/**
724
+	 * @return Mirror
725
+	 * @since   $VID:$
726
+	 */
727
+	private static function getMirror(): Mirror
728
+	{
729
+		if (! EEM_Base::$mirror instanceof Mirror) {
730
+			EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
731
+		}
732
+		return EEM_Base::$mirror;
733
+	}
734
+
735
+
736
+	/**
737
+	 * @param string $model_class_Name
738
+	 * @param string $timezone
739
+	 * @return array
740
+	 * @throws ReflectionException
741
+	 * @since   $VID:$
742
+	 */
743
+	private static function getModelArguments(string $model_class_Name, string $timezone): array
744
+	{
745
+		$arguments = [$timezone];
746
+		$params    = EEM_Base::getMirror()->getParameters($model_class_Name);
747
+		if (count($params) > 1) {
748
+			if ($params[1]->getName() === 'model_field_factory') {
749
+				$arguments = [
750
+					$timezone,
751
+					EEM_Base::getLoader()->getShared(ModelFieldFactory::class)
752
+				];
753
+			} elseif ($model_class_Name === 'EEM_Form_Section') {
754
+				$arguments = [
755
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
756
+					$timezone
757
+				];
758
+			} elseif ($model_class_Name === 'EEM_Form_Element') {
759
+				$arguments = [
760
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
761
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
762
+					$timezone,
763
+				];
764
+			}
765
+		}
766
+		return $arguments;
767
+	}
768
+
769
+
770
+	/**
771
+	 * This function is a singleton method used to instantiate the Espresso_model object
772
+	 *
773
+	 * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
774
+	 *                                (and any incoming timezone data that gets saved).
775
+	 *                                Note this just sends the timezone info to the date time model field objects.
776
+	 *                                Default is NULL
777
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
778
+	 * @return static (as in the concrete child class)
779
+	 * @throws EE_Error
780
+	 * @throws ReflectionException
781
+	 */
782
+	public static function instance($timezone = null)
783
+	{
784
+		// check if instance of Espresso_model already exists
785
+		if (! static::$_instance instanceof static) {
786
+			$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
787
+			$model = new static(...$arguments);
788
+			EEM_Base::getLoader()->share(static::class, $model, $arguments);
789
+			static::$_instance = $model;
790
+		}
791
+		// we might have a timezone set, let set_timezone decide what to do with it
792
+		if ($timezone) {
793
+			static::$_instance->set_timezone($timezone);
794
+		}
795
+		// Espresso_model object
796
+		return static::$_instance;
797
+	}
798
+
799
+
800
+
801
+	/**
802
+	 * resets the model and returns it
803
+	 *
804
+	 * @param string|null $timezone
805
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
806
+	 * all its properties reset; if it wasn't instantiated, returns null)
807
+	 * @throws EE_Error
808
+	 * @throws ReflectionException
809
+	 * @throws InvalidArgumentException
810
+	 * @throws InvalidDataTypeException
811
+	 * @throws InvalidInterfaceException
812
+	 */
813
+	public static function reset($timezone = null)
814
+	{
815
+		if (! static::$_instance instanceof EEM_Base) {
816
+			return null;
817
+		}
818
+		// Let's NOT swap out the current instance for a new one
819
+		// because if someone has a reference to it, we can't remove their reference.
820
+		// It's best to keep using the same reference but change the original object instead,
821
+		// so reset all its properties to their original values as defined in the class.
822
+		$static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
823
+		foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
824
+			// don't set instance to null like it was originally,
825
+			// but it's static anyways, and we're ignoring static properties (for now at least)
826
+			if (! isset($static_properties[ $property ])) {
827
+				static::$_instance->{$property} = $value;
828
+			}
829
+		}
830
+		// and then directly call its constructor again, like we would if we were creating a new one
831
+		$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
832
+		static::$_instance->__construct(...$arguments);
833
+		return self::instance();
834
+	}
835
+
836
+
837
+	/**
838
+	 * Used to set the $_model_query_blog_id static property.
839
+	 *
840
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
841
+	 *                      value for get_current_blog_id() will be used.
842
+	 */
843
+	public static function set_model_query_blog_id($blog_id = 0)
844
+	{
845
+		EEM_Base::$_model_query_blog_id = $blog_id > 0
846
+			? (int) $blog_id
847
+			: get_current_blog_id();
848
+	}
849
+
850
+
851
+	/**
852
+	 * Returns whatever is set as the internal $model_query_blog_id.
853
+	 *
854
+	 * @return int
855
+	 */
856
+	public static function get_model_query_blog_id()
857
+	{
858
+		return EEM_Base::$_model_query_blog_id;
859
+	}
860
+
861
+
862
+
863
+	/**
864
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
865
+	 *
866
+	 * @param  boolean $translated return localized strings or JUST the array.
867
+	 * @return array
868
+	 * @throws EE_Error
869
+	 * @throws InvalidArgumentException
870
+	 * @throws InvalidDataTypeException
871
+	 * @throws InvalidInterfaceException
872
+	 */
873
+	public function status_array($translated = false)
874
+	{
875
+		if (! array_key_exists('Status', $this->_model_relations)) {
876
+			return array();
877
+		}
878
+		$model_name = $this->get_this_model_name();
879
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
880
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
881
+		$status_array = array();
882
+		foreach ($stati as $status) {
883
+			$status_array[ $status->ID() ] = $status->get('STS_code');
884
+		}
885
+		return $translated
886
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
887
+			: $status_array;
888
+	}
889
+
890
+
891
+
892
+	/**
893
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
894
+	 *
895
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
896
+	 *                             or if you have the development copy of EE you can view this at the path:
897
+	 *                             /docs/G--Model-System/model-query-params.md
898
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
899
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
900
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
901
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
902
+	 *                                        array( array(
903
+	 *                                        'OR'=>array(
904
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
905
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
906
+	 *                                        )
907
+	 *                                        ),
908
+	 *                                        'limit'=>10,
909
+	 *                                        'group_by'=>'TXN_ID'
910
+	 *                                        ));
911
+	 *                                        get all the answers to the question titled "shirt size" for event with id
912
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
913
+	 *                                        'Question.QST_display_text'=>'shirt size',
914
+	 *                                        'Registration.Event.EVT_ID'=>12
915
+	 *                                        ),
916
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
917
+	 *                                        ));
918
+	 * @throws EE_Error
919
+	 */
920
+	public function get_all($query_params = array())
921
+	{
922
+		if (
923
+			isset($query_params['limit'])
924
+			&& ! isset($query_params['group_by'])
925
+		) {
926
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
927
+		}
928
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
929
+	}
930
+
931
+
932
+
933
+	/**
934
+	 * Modifies the query parameters so we only get back model objects
935
+	 * that "belong" to the current user
936
+	 *
937
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
938
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
939
+	 */
940
+	public function alter_query_params_to_only_include_mine($query_params = array())
941
+	{
942
+		$wp_user_field_name = $this->wp_user_field_name();
943
+		if ($wp_user_field_name) {
944
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
945
+		}
946
+		return $query_params;
947
+	}
948
+
949
+
950
+
951
+	/**
952
+	 * Returns the name of the field's name that points to the WP_User table
953
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
954
+	 * foreign key to the WP_User table)
955
+	 *
956
+	 * @return string|boolean string on success, boolean false when there is no
957
+	 * foreign key to the WP_User table
958
+	 */
959
+	public function wp_user_field_name()
960
+	{
961
+		try {
962
+			if (! empty($this->_model_chain_to_wp_user)) {
963
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
964
+				$last_model_name = end($models_to_follow_to_wp_users);
965
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
966
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
967
+			} else {
968
+				$model_with_fk_to_wp_users = $this;
969
+				$model_chain_to_wp_user = '';
970
+			}
971
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
972
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
973
+		} catch (EE_Error $e) {
974
+			return false;
975
+		}
976
+	}
977
+
978
+
979
+
980
+	/**
981
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
982
+	 * (or transiently-related model) has a foreign key to the wp_users table;
983
+	 * useful for finding if model objects of this type are 'owned' by the current user.
984
+	 * This is an empty string when the foreign key is on this model and when it isn't,
985
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
986
+	 * (or transiently-related model)
987
+	 *
988
+	 * @return string
989
+	 */
990
+	public function model_chain_to_wp_user()
991
+	{
992
+		return $this->_model_chain_to_wp_user;
993
+	}
994
+
995
+
996
+
997
+	/**
998
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
999
+	 * like how registrations don't have a foreign key to wp_users, but the
1000
+	 * events they are for are), or is unrelated to wp users.
1001
+	 * generally available
1002
+	 *
1003
+	 * @return boolean
1004
+	 */
1005
+	public function is_owned()
1006
+	{
1007
+		if ($this->model_chain_to_wp_user()) {
1008
+			return true;
1009
+		}
1010
+		try {
1011
+			$this->get_foreign_key_to('WP_User');
1012
+			return true;
1013
+		} catch (EE_Error $e) {
1014
+			return false;
1015
+		}
1016
+	}
1017
+
1018
+
1019
+	/**
1020
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1021
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1022
+	 * the model)
1023
+	 *
1024
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1025
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1026
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1027
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1028
+	 *                                  override this and set the select to "*", or a specific column name, like
1029
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1030
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1031
+	 *                                  the aliases used to refer to this selection, and values are to be
1032
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1033
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1034
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1035
+	 * @throws EE_Error
1036
+	 * @throws InvalidArgumentException
1037
+	 */
1038
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1039
+	{
1040
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1041
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1042
+		$select_expressions = $columns_to_select === null
1043
+			? $this->_construct_default_select_sql($model_query_info)
1044
+			: '';
1045
+		if ($this->_custom_selections instanceof CustomSelects) {
1046
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1047
+			$select_expressions .= $select_expressions
1048
+				? ', ' . $custom_expressions
1049
+				: $custom_expressions;
1050
+		}
1051
+
1052
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1053
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1054
+	}
1055
+
1056
+
1057
+	/**
1058
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1059
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1060
+	 * method of including extra select information.
1061
+	 *
1062
+	 * @param array             $query_params
1063
+	 * @param null|array|string $columns_to_select
1064
+	 * @return null|CustomSelects
1065
+	 * @throws InvalidArgumentException
1066
+	 */
1067
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1068
+	{
1069
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1070
+			return null;
1071
+		}
1072
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1073
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1074
+		return new CustomSelects($selects);
1075
+	}
1076
+
1077
+
1078
+
1079
+	/**
1080
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1081
+	 * but you can use the model query params to more easily
1082
+	 * take care of joins, field preparation etc.
1083
+	 *
1084
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1085
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1086
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1087
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1088
+	 *                                  override this and set the select to "*", or a specific column name, like
1089
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1090
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1091
+	 *                                  the aliases used to refer to this selection, and values are to be
1092
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1093
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1094
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1095
+	 * @throws EE_Error
1096
+	 */
1097
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1098
+	{
1099
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1100
+	}
1101
+
1102
+
1103
+
1104
+	/**
1105
+	 * For creating a custom select statement
1106
+	 *
1107
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1108
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1109
+	 *                                 SQL, and 1=>is the datatype
1110
+	 * @throws EE_Error
1111
+	 * @return string
1112
+	 */
1113
+	private function _construct_select_from_input($columns_to_select)
1114
+	{
1115
+		if (is_array($columns_to_select)) {
1116
+			$select_sql_array = array();
1117
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1118
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1119
+					throw new EE_Error(
1120
+						sprintf(
1121
+							__(
1122
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1123
+								'event_espresso'
1124
+							),
1125
+							$selection_and_datatype,
1126
+							$alias
1127
+						)
1128
+					);
1129
+				}
1130
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1131
+					throw new EE_Error(
1132
+						sprintf(
1133
+							esc_html__(
1134
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1135
+								'event_espresso'
1136
+							),
1137
+							$selection_and_datatype[1],
1138
+							$selection_and_datatype[0],
1139
+							$alias,
1140
+							implode(', ', $this->_valid_wpdb_data_types)
1141
+						)
1142
+					);
1143
+				}
1144
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1145
+			}
1146
+			$columns_to_select_string = implode(', ', $select_sql_array);
1147
+		} else {
1148
+			$columns_to_select_string = $columns_to_select;
1149
+		}
1150
+		return $columns_to_select_string;
1151
+	}
1152
+
1153
+
1154
+
1155
+	/**
1156
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1157
+	 *
1158
+	 * @return string
1159
+	 * @throws EE_Error
1160
+	 */
1161
+	public function primary_key_name()
1162
+	{
1163
+		return $this->get_primary_key_field()->get_name();
1164
+	}
1165
+
1166
+
1167
+	/**
1168
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1169
+	 * If there is no primary key on this model, $id is treated as primary key string
1170
+	 *
1171
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1172
+	 * @return EE_Base_Class
1173
+	 * @throws EE_Error
1174
+	 */
1175
+	public function get_one_by_ID($id)
1176
+	{
1177
+		if ($this->get_from_entity_map($id)) {
1178
+			return $this->get_from_entity_map($id);
1179
+		}
1180
+		$model_object = $this->get_one(
1181
+			$this->alter_query_params_to_restrict_by_ID(
1182
+				$id,
1183
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1184
+			)
1185
+		);
1186
+		$className = $this->_get_class_name();
1187
+		if ($model_object instanceof $className) {
1188
+			// make sure valid objects get added to the entity map
1189
+			// so that the next call to this method doesn't trigger another trip to the db
1190
+			$this->add_to_entity_map($model_object);
1191
+		}
1192
+		return $model_object;
1193
+	}
1194
+
1195
+
1196
+
1197
+	/**
1198
+	 * Alters query parameters to only get items with this ID are returned.
1199
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1200
+	 * or could just be a simple primary key ID
1201
+	 *
1202
+	 * @param int   $id
1203
+	 * @param array $query_params
1204
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1205
+	 * @throws EE_Error
1206
+	 */
1207
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1208
+	{
1209
+		if (! isset($query_params[0])) {
1210
+			$query_params[0] = array();
1211
+		}
1212
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1213
+		if ($conditions_from_id === null) {
1214
+			$query_params[0][ $this->primary_key_name() ] = $id;
1215
+		} else {
1216
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1217
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1218
+		}
1219
+		return $query_params;
1220
+	}
1221
+
1222
+
1223
+
1224
+	/**
1225
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1226
+	 * array. If no item is found, null is returned.
1227
+	 *
1228
+	 * @param array $query_params like EEM_Base's $query_params variable.
1229
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1230
+	 * @throws EE_Error
1231
+	 */
1232
+	public function get_one($query_params = array())
1233
+	{
1234
+		if (! is_array($query_params)) {
1235
+			EE_Error::doing_it_wrong(
1236
+				'EEM_Base::get_one',
1237
+				sprintf(
1238
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1239
+					gettype($query_params)
1240
+				),
1241
+				'4.6.0'
1242
+			);
1243
+			$query_params = array();
1244
+		}
1245
+		$query_params['limit'] = 1;
1246
+		$items = $this->get_all($query_params);
1247
+		if (empty($items)) {
1248
+			return null;
1249
+		}
1250
+		return array_shift($items);
1251
+	}
1252
+
1253
+
1254
+
1255
+	/**
1256
+	 * Returns the next x number of items in sequence from the given value as
1257
+	 * found in the database matching the given query conditions.
1258
+	 *
1259
+	 * @param mixed $current_field_value    Value used for the reference point.
1260
+	 * @param null  $field_to_order_by      What field is used for the
1261
+	 *                                      reference point.
1262
+	 * @param int   $limit                  How many to return.
1263
+	 * @param array $query_params           Extra conditions on the query.
1264
+	 * @param null  $columns_to_select      If left null, then an array of
1265
+	 *                                      EE_Base_Class objects is returned,
1266
+	 *                                      otherwise you can indicate just the
1267
+	 *                                      columns you want returned.
1268
+	 * @return EE_Base_Class[]|array
1269
+	 * @throws EE_Error
1270
+	 */
1271
+	public function next_x(
1272
+		$current_field_value,
1273
+		$field_to_order_by = null,
1274
+		$limit = 1,
1275
+		$query_params = array(),
1276
+		$columns_to_select = null
1277
+	) {
1278
+		return $this->_get_consecutive(
1279
+			$current_field_value,
1280
+			'>',
1281
+			$field_to_order_by,
1282
+			$limit,
1283
+			$query_params,
1284
+			$columns_to_select
1285
+		);
1286
+	}
1287
+
1288
+
1289
+
1290
+	/**
1291
+	 * Returns the previous x number of items in sequence from the given value
1292
+	 * as found in the database matching the given query conditions.
1293
+	 *
1294
+	 * @param mixed $current_field_value    Value used for the reference point.
1295
+	 * @param null  $field_to_order_by      What field is used for the
1296
+	 *                                      reference point.
1297
+	 * @param int   $limit                  How many to return.
1298
+	 * @param array $query_params           Extra conditions on the query.
1299
+	 * @param null  $columns_to_select      If left null, then an array of
1300
+	 *                                      EE_Base_Class objects is returned,
1301
+	 *                                      otherwise you can indicate just the
1302
+	 *                                      columns you want returned.
1303
+	 * @return EE_Base_Class[]|array
1304
+	 * @throws EE_Error
1305
+	 */
1306
+	public function previous_x(
1307
+		$current_field_value,
1308
+		$field_to_order_by = null,
1309
+		$limit = 1,
1310
+		$query_params = array(),
1311
+		$columns_to_select = null
1312
+	) {
1313
+		return $this->_get_consecutive(
1314
+			$current_field_value,
1315
+			'<',
1316
+			$field_to_order_by,
1317
+			$limit,
1318
+			$query_params,
1319
+			$columns_to_select
1320
+		);
1321
+	}
1322
+
1323
+
1324
+
1325
+	/**
1326
+	 * Returns the next item in sequence from the given value as found in the
1327
+	 * database matching the given query conditions.
1328
+	 *
1329
+	 * @param mixed $current_field_value    Value used for the reference point.
1330
+	 * @param null  $field_to_order_by      What field is used for the
1331
+	 *                                      reference point.
1332
+	 * @param array $query_params           Extra conditions on the query.
1333
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1334
+	 *                                      object is returned, otherwise you
1335
+	 *                                      can indicate just the columns you
1336
+	 *                                      want and a single array indexed by
1337
+	 *                                      the columns will be returned.
1338
+	 * @return EE_Base_Class|null|array()
1339
+	 * @throws EE_Error
1340
+	 */
1341
+	public function next(
1342
+		$current_field_value,
1343
+		$field_to_order_by = null,
1344
+		$query_params = array(),
1345
+		$columns_to_select = null
1346
+	) {
1347
+		$results = $this->_get_consecutive(
1348
+			$current_field_value,
1349
+			'>',
1350
+			$field_to_order_by,
1351
+			1,
1352
+			$query_params,
1353
+			$columns_to_select
1354
+		);
1355
+		return empty($results) ? null : reset($results);
1356
+	}
1357
+
1358
+
1359
+
1360
+	/**
1361
+	 * Returns the previous item in sequence from the given value as found in
1362
+	 * the database matching the given query conditions.
1363
+	 *
1364
+	 * @param mixed $current_field_value    Value used for the reference point.
1365
+	 * @param null  $field_to_order_by      What field is used for the
1366
+	 *                                      reference point.
1367
+	 * @param array $query_params           Extra conditions on the query.
1368
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1369
+	 *                                      object is returned, otherwise you
1370
+	 *                                      can indicate just the columns you
1371
+	 *                                      want and a single array indexed by
1372
+	 *                                      the columns will be returned.
1373
+	 * @return EE_Base_Class|null|array()
1374
+	 * @throws EE_Error
1375
+	 */
1376
+	public function previous(
1377
+		$current_field_value,
1378
+		$field_to_order_by = null,
1379
+		$query_params = array(),
1380
+		$columns_to_select = null
1381
+	) {
1382
+		$results = $this->_get_consecutive(
1383
+			$current_field_value,
1384
+			'<',
1385
+			$field_to_order_by,
1386
+			1,
1387
+			$query_params,
1388
+			$columns_to_select
1389
+		);
1390
+		return empty($results) ? null : reset($results);
1391
+	}
1392
+
1393
+
1394
+
1395
+	/**
1396
+	 * Returns the a consecutive number of items in sequence from the given
1397
+	 * value as found in the database matching the given query conditions.
1398
+	 *
1399
+	 * @param mixed  $current_field_value   Value used for the reference point.
1400
+	 * @param string $operand               What operand is used for the sequence.
1401
+	 * @param string $field_to_order_by     What field is used for the reference point.
1402
+	 * @param int    $limit                 How many to return.
1403
+	 * @param array  $query_params          Extra conditions on the query.
1404
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1405
+	 *                                      otherwise you can indicate just the columns you want returned.
1406
+	 * @return EE_Base_Class[]|array
1407
+	 * @throws EE_Error
1408
+	 */
1409
+	protected function _get_consecutive(
1410
+		$current_field_value,
1411
+		$operand = '>',
1412
+		$field_to_order_by = null,
1413
+		$limit = 1,
1414
+		$query_params = array(),
1415
+		$columns_to_select = null
1416
+	) {
1417
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1418
+		if (empty($field_to_order_by)) {
1419
+			if ($this->has_primary_key_field()) {
1420
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1421
+			} else {
1422
+				if (WP_DEBUG) {
1423
+					throw new EE_Error(__(
1424
+						'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).',
1425
+						'event_espresso'
1426
+					));
1427
+				}
1428
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1429
+				return array();
1430
+			}
1431
+		}
1432
+		if (! is_array($query_params)) {
1433
+			EE_Error::doing_it_wrong(
1434
+				'EEM_Base::_get_consecutive',
1435
+				sprintf(
1436
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1437
+					gettype($query_params)
1438
+				),
1439
+				'4.6.0'
1440
+			);
1441
+			$query_params = array();
1442
+		}
1443
+		// let's add the where query param for consecutive look up.
1444
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1445
+		$query_params['limit'] = $limit;
1446
+		// set direction
1447
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1448
+		$query_params['order_by'] = $operand === '>'
1449
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1450
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1451
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1452
+		if (empty($columns_to_select)) {
1453
+			return $this->get_all($query_params);
1454
+		}
1455
+		// getting just the fields
1456
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1457
+	}
1458
+
1459
+
1460
+
1461
+	/**
1462
+	 * This sets the _timezone property after model object has been instantiated.
1463
+	 *
1464
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1465
+	 */
1466
+	public function set_timezone($timezone)
1467
+	{
1468
+		if ($timezone !== null) {
1469
+			$this->_timezone = $timezone;
1470
+		}
1471
+		// note we need to loop through relations and set the timezone on those objects as well.
1472
+		foreach ($this->_model_relations as $relation) {
1473
+			$relation->set_timezone($timezone);
1474
+		}
1475
+		// and finally we do the same for any datetime fields
1476
+		foreach ($this->_fields as $field) {
1477
+			if ($field instanceof EE_Datetime_Field) {
1478
+				$field->set_timezone($timezone);
1479
+			}
1480
+		}
1481
+	}
1482
+
1483
+
1484
+
1485
+	/**
1486
+	 * This just returns whatever is set for the current timezone.
1487
+	 *
1488
+	 * @access public
1489
+	 * @return string
1490
+	 */
1491
+	public function get_timezone()
1492
+	{
1493
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1494
+		if (empty($this->_timezone)) {
1495
+			foreach ($this->_fields as $field) {
1496
+				if ($field instanceof EE_Datetime_Field) {
1497
+					$this->set_timezone($field->get_timezone());
1498
+					break;
1499
+				}
1500
+			}
1501
+		}
1502
+		// if timezone STILL empty then return the default timezone for the site.
1503
+		if (empty($this->_timezone)) {
1504
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1505
+		}
1506
+		return $this->_timezone;
1507
+	}
1508
+
1509
+
1510
+
1511
+	/**
1512
+	 * This returns the date formats set for the given field name and also ensures that
1513
+	 * $this->_timezone property is set correctly.
1514
+	 *
1515
+	 * @since 4.6.x
1516
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1517
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1518
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1519
+	 * @return array formats in an array with the date format first, and the time format last.
1520
+	 */
1521
+	public function get_formats_for($field_name, $pretty = false)
1522
+	{
1523
+		$field_settings = $this->field_settings_for($field_name);
1524
+		// if not a valid EE_Datetime_Field then throw error
1525
+		if (! $field_settings instanceof EE_Datetime_Field) {
1526
+			throw new EE_Error(sprintf(__(
1527
+				'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.',
1528
+				'event_espresso'
1529
+			), $field_name));
1530
+		}
1531
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1532
+		// the field.
1533
+		$this->_timezone = $field_settings->get_timezone();
1534
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1535
+	}
1536
+
1537
+
1538
+
1539
+	/**
1540
+	 * This returns the current time in a format setup for a query on this model.
1541
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1542
+	 * it will return:
1543
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1544
+	 *  NOW
1545
+	 *  - or a unix timestamp (equivalent to time())
1546
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1547
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1548
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1549
+	 * @since 4.6.x
1550
+	 * @param string $field_name       The field the current time is needed for.
1551
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1552
+	 *                                 formatted string matching the set format for the field in the set timezone will
1553
+	 *                                 be returned.
1554
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1555
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1556
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1557
+	 *                                 exception is triggered.
1558
+	 */
1559
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1560
+	{
1561
+		$formats = $this->get_formats_for($field_name);
1562
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1563
+		if ($timestamp) {
1564
+			return $DateTime->format('U');
1565
+		}
1566
+		// not returning timestamp, so return formatted string in timezone.
1567
+		switch ($what) {
1568
+			case 'time':
1569
+				return $DateTime->format($formats[1]);
1570
+				break;
1571
+			case 'date':
1572
+				return $DateTime->format($formats[0]);
1573
+				break;
1574
+			default:
1575
+				return $DateTime->format(implode(' ', $formats));
1576
+				break;
1577
+		}
1578
+	}
1579
+
1580
+
1581
+
1582
+	/**
1583
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1584
+	 * for the model are.  Returns a DateTime object.
1585
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1586
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1587
+	 * ignored.
1588
+	 *
1589
+	 * @param string $field_name      The field being setup.
1590
+	 * @param string $timestring      The date time string being used.
1591
+	 * @param string $incoming_format The format for the time string.
1592
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1593
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1594
+	 *                                format is
1595
+	 *                                'U', this is ignored.
1596
+	 * @return DateTime
1597
+	 * @throws EE_Error
1598
+	 */
1599
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1600
+	{
1601
+		// just using this to ensure the timezone is set correctly internally
1602
+		$this->get_formats_for($field_name);
1603
+		// load EEH_DTT_Helper
1604
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1605
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1606
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1607
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1608
+	}
1609
+
1610
+
1611
+
1612
+	/**
1613
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1614
+	 *
1615
+	 * @return EE_Table_Base[]
1616
+	 */
1617
+	public function get_tables()
1618
+	{
1619
+		return $this->_tables;
1620
+	}
1621
+
1622
+
1623
+
1624
+	/**
1625
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1626
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1627
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1628
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1629
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1630
+	 * model object with EVT_ID = 1
1631
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1632
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1633
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1634
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1635
+	 * are not specified)
1636
+	 *
1637
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1638
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1639
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1640
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1641
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1642
+	 *                                         ID=34, we'd use this method as follows:
1643
+	 *                                         EEM_Transaction::instance()->update(
1644
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1645
+	 *                                         array(array('TXN_ID'=>34)));
1646
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1647
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1648
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1649
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1650
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1651
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1652
+	 *                                         TRUE, it is assumed that you've already called
1653
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1654
+	 *                                         malicious javascript. However, if
1655
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1656
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1657
+	 *                                         and every other field, before insertion. We provide this parameter
1658
+	 *                                         because model objects perform their prepare_for_set function on all
1659
+	 *                                         their values, and so don't need to be called again (and in many cases,
1660
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1661
+	 *                                         prepare_for_set method...)
1662
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1663
+	 *                                         in this model's entity map according to $fields_n_values that match
1664
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1665
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1666
+	 *                                         could get out-of-sync with the database
1667
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1668
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1669
+	 *                                         bad)
1670
+	 * @throws EE_Error
1671
+	 */
1672
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1673
+	{
1674
+		if (! is_array($query_params)) {
1675
+			EE_Error::doing_it_wrong(
1676
+				'EEM_Base::update',
1677
+				sprintf(
1678
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1679
+					gettype($query_params)
1680
+				),
1681
+				'4.6.0'
1682
+			);
1683
+			$query_params = array();
1684
+		}
1685
+		/**
1686
+		 * Action called before a model update call has been made.
1687
+		 *
1688
+		 * @param EEM_Base $model
1689
+		 * @param array    $fields_n_values the updated fields and their new values
1690
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1691
+		 */
1692
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1693
+		/**
1694
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1695
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1696
+		 *
1697
+		 * @param array    $fields_n_values fields and their new values
1698
+		 * @param EEM_Base $model           the model being queried
1699
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1700
+		 */
1701
+		$fields_n_values = (array) apply_filters(
1702
+			'FHEE__EEM_Base__update__fields_n_values',
1703
+			$fields_n_values,
1704
+			$this,
1705
+			$query_params
1706
+		);
1707
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1708
+		// to do that, for each table, verify that it's PK isn't null.
1709
+		$tables = $this->get_tables();
1710
+		// 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
1711
+		// NOTE: we should make this code more efficient by NOT querying twice
1712
+		// before the real update, but that needs to first go through ALPHA testing
1713
+		// as it's dangerous. says Mike August 8 2014
1714
+		// we want to make sure the default_where strategy is ignored
1715
+		$this->_ignore_where_strategy = true;
1716
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1717
+		foreach ($wpdb_select_results as $wpdb_result) {
1718
+			// type cast stdClass as array
1719
+			$wpdb_result = (array) $wpdb_result;
1720
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1721
+			if ($this->has_primary_key_field()) {
1722
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1723
+			} else {
1724
+				// 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)
1725
+				$main_table_pk_value = null;
1726
+			}
1727
+			// 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
1728
+			// 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
1729
+			if (count($tables) > 1) {
1730
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1731
+				// in that table, and so we'll want to insert one
1732
+				foreach ($tables as $table_obj) {
1733
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1734
+					// if there is no private key for this table on the results, it means there's no entry
1735
+					// in this table, right? so insert a row in the current table, using any fields available
1736
+					if (
1737
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1738
+						   && $wpdb_result[ $this_table_pk_column ])
1739
+					) {
1740
+						$success = $this->_insert_into_specific_table(
1741
+							$table_obj,
1742
+							$fields_n_values,
1743
+							$main_table_pk_value
1744
+						);
1745
+						// if we died here, report the error
1746
+						if (! $success) {
1747
+							return false;
1748
+						}
1749
+					}
1750
+				}
1751
+			}
1752
+			//              //and now check that if we have cached any models by that ID on the model, that
1753
+			//              //they also get updated properly
1754
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1755
+			//              if( $model_object ){
1756
+			//                  foreach( $fields_n_values as $field => $value ){
1757
+			//                      $model_object->set($field, $value);
1758
+			// let's make sure default_where strategy is followed now
1759
+			$this->_ignore_where_strategy = false;
1760
+		}
1761
+		// if we want to keep model objects in sync, AND
1762
+		// if this wasn't called from a model object (to update itself)
1763
+		// then we want to make sure we keep all the existing
1764
+		// model objects in sync with the db
1765
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1766
+			if ($this->has_primary_key_field()) {
1767
+				$model_objs_affected_ids = $this->get_col($query_params);
1768
+			} else {
1769
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1770
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1771
+				$model_objs_affected_ids = array();
1772
+				foreach ($models_affected_key_columns as $row) {
1773
+					$combined_index_key = $this->get_index_primary_key_string($row);
1774
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1775
+				}
1776
+			}
1777
+			if (! $model_objs_affected_ids) {
1778
+				// wait wait wait- if nothing was affected let's stop here
1779
+				return 0;
1780
+			}
1781
+			foreach ($model_objs_affected_ids as $id) {
1782
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1783
+				if ($model_obj_in_entity_map) {
1784
+					foreach ($fields_n_values as $field => $new_value) {
1785
+						$model_obj_in_entity_map->set($field, $new_value);
1786
+					}
1787
+				}
1788
+			}
1789
+			// if there is a primary key on this model, we can now do a slight optimization
1790
+			if ($this->has_primary_key_field()) {
1791
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1792
+				$query_params = array(
1793
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1794
+					'limit'                    => count($model_objs_affected_ids),
1795
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1796
+				);
1797
+			}
1798
+		}
1799
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1800
+		$SQL = "UPDATE "
1801
+			   . $model_query_info->get_full_join_sql()
1802
+			   . " SET "
1803
+			   . $this->_construct_update_sql($fields_n_values)
1804
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1805
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1806
+		/**
1807
+		 * Action called after a model update call has been made.
1808
+		 *
1809
+		 * @param EEM_Base $model
1810
+		 * @param array    $fields_n_values the updated fields and their new values
1811
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1812
+		 * @param int      $rows_affected
1813
+		 */
1814
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1815
+		return $rows_affected;// how many supposedly got updated
1816
+	}
1817
+
1818
+
1819
+
1820
+	/**
1821
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1822
+	 * are teh values of the field specified (or by default the primary key field)
1823
+	 * that matched the query params. Note that you should pass the name of the
1824
+	 * model FIELD, not the database table's column name.
1825
+	 *
1826
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1827
+	 * @param string $field_to_select
1828
+	 * @return array just like $wpdb->get_col()
1829
+	 * @throws EE_Error
1830
+	 */
1831
+	public function get_col($query_params = array(), $field_to_select = null)
1832
+	{
1833
+		if ($field_to_select) {
1834
+			$field = $this->field_settings_for($field_to_select);
1835
+		} elseif ($this->has_primary_key_field()) {
1836
+			$field = $this->get_primary_key_field();
1837
+		} else {
1838
+			// no primary key, just grab the first column
1839
+			$field = reset($this->field_settings());
1840
+		}
1841
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1842
+		$select_expressions = $field->get_qualified_column();
1843
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1844
+		return $this->_do_wpdb_query('get_col', array($SQL));
1845
+	}
1846
+
1847
+
1848
+
1849
+	/**
1850
+	 * Returns a single column value for a single row from the database
1851
+	 *
1852
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1853
+	 * @param string $field_to_select @see EEM_Base::get_col()
1854
+	 * @return string
1855
+	 * @throws EE_Error
1856
+	 */
1857
+	public function get_var($query_params = array(), $field_to_select = null)
1858
+	{
1859
+		$query_params['limit'] = 1;
1860
+		$col = $this->get_col($query_params, $field_to_select);
1861
+		if (! empty($col)) {
1862
+			return reset($col);
1863
+		}
1864
+		return null;
1865
+	}
1866
+
1867
+
1868
+
1869
+	/**
1870
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1871
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1872
+	 * injection, but currently no further filtering is done
1873
+	 *
1874
+	 * @global      $wpdb
1875
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1876
+	 *                               be updated to in the DB
1877
+	 * @return string of SQL
1878
+	 * @throws EE_Error
1879
+	 */
1880
+	public function _construct_update_sql($fields_n_values)
1881
+	{
1882
+		/** @type WPDB $wpdb */
1883
+		global $wpdb;
1884
+		$cols_n_values = array();
1885
+		foreach ($fields_n_values as $field_name => $value) {
1886
+			$field_obj = $this->field_settings_for($field_name);
1887
+			// if the value is NULL, we want to assign the value to that.
1888
+			// wpdb->prepare doesn't really handle that properly
1889
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1890
+			$value_sql = $prepared_value === null ? 'NULL'
1891
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1892
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1893
+		}
1894
+		return implode(",", $cols_n_values);
1895
+	}
1896
+
1897
+
1898
+
1899
+	/**
1900
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1901
+	 * Performs a HARD delete, meaning the database row should always be removed,
1902
+	 * not just have a flag field on it switched
1903
+	 * Wrapper for EEM_Base::delete_permanently()
1904
+	 *
1905
+	 * @param mixed $id
1906
+	 * @param boolean $allow_blocking
1907
+	 * @return int the number of rows deleted
1908
+	 * @throws EE_Error
1909
+	 */
1910
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1911
+	{
1912
+		return $this->delete_permanently(
1913
+			array(
1914
+				array($this->get_primary_key_field()->get_name() => $id),
1915
+				'limit' => 1,
1916
+			),
1917
+			$allow_blocking
1918
+		);
1919
+	}
1920
+
1921
+
1922
+
1923
+	/**
1924
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1925
+	 * Wrapper for EEM_Base::delete()
1926
+	 *
1927
+	 * @param mixed $id
1928
+	 * @param boolean $allow_blocking
1929
+	 * @return int the number of rows deleted
1930
+	 * @throws EE_Error
1931
+	 */
1932
+	public function delete_by_ID($id, $allow_blocking = true)
1933
+	{
1934
+		return $this->delete(
1935
+			array(
1936
+				array($this->get_primary_key_field()->get_name() => $id),
1937
+				'limit' => 1,
1938
+			),
1939
+			$allow_blocking
1940
+		);
1941
+	}
1942
+
1943
+
1944
+
1945
+	/**
1946
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1947
+	 * meaning if the model has a field that indicates its been "trashed" or
1948
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1949
+	 *
1950
+	 * @see EEM_Base::delete_permanently
1951
+	 * @param array   $query_params
1952
+	 * @param boolean $allow_blocking
1953
+	 * @return int how many rows got deleted
1954
+	 * @throws EE_Error
1955
+	 */
1956
+	public function delete($query_params, $allow_blocking = true)
1957
+	{
1958
+		return $this->delete_permanently($query_params, $allow_blocking);
1959
+	}
1960
+
1961
+
1962
+
1963
+	/**
1964
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1965
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1966
+	 * as archived, not actually deleted
1967
+	 *
1968
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1969
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1970
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1971
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1972
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1973
+	 *                                DB
1974
+	 * @return int how many rows got deleted
1975
+	 * @throws EE_Error
1976
+	 */
1977
+	public function delete_permanently($query_params, $allow_blocking = true)
1978
+	{
1979
+		/**
1980
+		 * Action called just before performing a real deletion query. You can use the
1981
+		 * model and its $query_params to find exactly which items will be deleted
1982
+		 *
1983
+		 * @param EEM_Base $model
1984
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1985
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1986
+		 *                                 to block (prevent) this deletion
1987
+		 */
1988
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1989
+		// some MySQL databases may be running safe mode, which may restrict
1990
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1991
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1992
+		// to delete them
1993
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1994
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1995
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1996
+			$columns_and_ids_for_deleting
1997
+		);
1998
+		/**
1999
+		 * Allows client code to act on the items being deleted before the query is actually executed.
2000
+		 *
2001
+		 * @param EEM_Base $this  The model instance being acted on.
2002
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2003
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
2004
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
2005
+		 *                                                  derived from the incoming query parameters.
2006
+		 *                                                  @see details on the structure of this array in the phpdocs
2007
+		 *                                                  for the `_get_ids_for_delete_method`
2008
+		 *
2009
+		 */
2010
+		do_action(
2011
+			'AHEE__EEM_Base__delete__before_query',
2012
+			$this,
2013
+			$query_params,
2014
+			$allow_blocking,
2015
+			$columns_and_ids_for_deleting
2016
+		);
2017
+		if ($deletion_where_query_part) {
2018
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2019
+			$table_aliases = array_keys($this->_tables);
2020
+			$SQL = "DELETE "
2021
+				   . implode(", ", $table_aliases)
2022
+				   . " FROM "
2023
+				   . $model_query_info->get_full_join_sql()
2024
+				   . " WHERE "
2025
+				   . $deletion_where_query_part;
2026
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2027
+		} else {
2028
+			$rows_deleted = 0;
2029
+		}
2030
+
2031
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2032
+		// there was no error with the delete query.
2033
+		if (
2034
+			$this->has_primary_key_field()
2035
+			&& $rows_deleted !== false
2036
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2037
+		) {
2038
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2039
+			foreach ($ids_for_removal as $id) {
2040
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2041
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2042
+				}
2043
+			}
2044
+
2045
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2046
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2047
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2048
+			// (although it is possible).
2049
+			// Note this can be skipped by using the provided filter and returning false.
2050
+			if (
2051
+				apply_filters(
2052
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2053
+					! $this instanceof EEM_Extra_Meta,
2054
+					$this
2055
+				)
2056
+			) {
2057
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2058
+					0 => array(
2059
+						'EXM_type' => $this->get_this_model_name(),
2060
+						'OBJ_ID'   => array(
2061
+							'IN',
2062
+							$ids_for_removal
2063
+						)
2064
+					)
2065
+				));
2066
+			}
2067
+		}
2068
+
2069
+		/**
2070
+		 * Action called just after performing a real deletion query. Although at this point the
2071
+		 * items should have been deleted
2072
+		 *
2073
+		 * @param EEM_Base $model
2074
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2075
+		 * @param int      $rows_deleted
2076
+		 */
2077
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2078
+		return $rows_deleted;// how many supposedly got deleted
2079
+	}
2080
+
2081
+
2082
+
2083
+	/**
2084
+	 * Checks all the relations that throw error messages when there are blocking related objects
2085
+	 * for related model objects. If there are any related model objects on those relations,
2086
+	 * adds an EE_Error, and return true
2087
+	 *
2088
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2089
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2090
+	 *                                                 should be ignored when determining whether there are related
2091
+	 *                                                 model objects which block this model object's deletion. Useful
2092
+	 *                                                 if you know A is related to B and are considering deleting A,
2093
+	 *                                                 but want to see if A has any other objects blocking its deletion
2094
+	 *                                                 before removing the relation between A and B
2095
+	 * @return boolean
2096
+	 * @throws EE_Error
2097
+	 */
2098
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2099
+	{
2100
+		// first, if $ignore_this_model_obj was supplied, get its model
2101
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2102
+			$ignored_model = $ignore_this_model_obj->get_model();
2103
+		} else {
2104
+			$ignored_model = null;
2105
+		}
2106
+		// now check all the relations of $this_model_obj_or_id and see if there
2107
+		// are any related model objects blocking it?
2108
+		$is_blocked = false;
2109
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2110
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2111
+				// if $ignore_this_model_obj was supplied, then for the query
2112
+				// on that model needs to be told to ignore $ignore_this_model_obj
2113
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2114
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2115
+						array(
2116
+							$ignored_model->get_primary_key_field()->get_name() => array(
2117
+								'!=',
2118
+								$ignore_this_model_obj->ID(),
2119
+							),
2120
+						),
2121
+					));
2122
+				} else {
2123
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2124
+				}
2125
+				if ($related_model_objects) {
2126
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2127
+					$is_blocked = true;
2128
+				}
2129
+			}
2130
+		}
2131
+		return $is_blocked;
2132
+	}
2133
+
2134
+
2135
+	/**
2136
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2137
+	 * @param array $row_results_for_deleting
2138
+	 * @param bool  $allow_blocking
2139
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2140
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2141
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2142
+	 *                 deleted. Example:
2143
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2144
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2145
+	 *                 where each element is a group of columns and values that get deleted. Example:
2146
+	 *                      array(
2147
+	 *                          0 => array(
2148
+	 *                              'Term_Relationship.object_id' => 1
2149
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2150
+	 *                          ),
2151
+	 *                          1 => array(
2152
+	 *                              'Term_Relationship.object_id' => 1
2153
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2154
+	 *                          )
2155
+	 *                      )
2156
+	 * @throws EE_Error
2157
+	 */
2158
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2159
+	{
2160
+		$ids_to_delete_indexed_by_column = array();
2161
+		if ($this->has_primary_key_field()) {
2162
+			$primary_table = $this->_get_main_table();
2163
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2164
+			$other_tables = $this->_get_other_tables();
2165
+			$ids_to_delete_indexed_by_column = $query = array();
2166
+			foreach ($row_results_for_deleting as $item_to_delete) {
2167
+				// before we mark this item for deletion,
2168
+				// make sure there's no related entities blocking its deletion (if we're checking)
2169
+				if (
2170
+					$allow_blocking
2171
+					&& $this->delete_is_blocked_by_related_models(
2172
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2173
+					)
2174
+				) {
2175
+					continue;
2176
+				}
2177
+				// primary table deletes
2178
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2179
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2180
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2181
+				}
2182
+			}
2183
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2184
+			$fields = $this->get_combined_primary_key_fields();
2185
+			foreach ($row_results_for_deleting as $item_to_delete) {
2186
+				$ids_to_delete_indexed_by_column_for_row = array();
2187
+				foreach ($fields as $cpk_field) {
2188
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2189
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2190
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2191
+					}
2192
+				}
2193
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2194
+			}
2195
+		} else {
2196
+			// so there's no primary key and no combined key...
2197
+			// sorry, can't help you
2198
+			throw new EE_Error(
2199
+				sprintf(
2200
+					__(
2201
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2202
+						"event_espresso"
2203
+					),
2204
+					get_class($this)
2205
+				)
2206
+			);
2207
+		}
2208
+		return $ids_to_delete_indexed_by_column;
2209
+	}
2210
+
2211
+
2212
+	/**
2213
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2214
+	 * the corresponding query_part for the query performing the delete.
2215
+	 *
2216
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2217
+	 * @return string
2218
+	 * @throws EE_Error
2219
+	 */
2220
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2221
+	{
2222
+		$query_part = '';
2223
+		if (empty($ids_to_delete_indexed_by_column)) {
2224
+			return $query_part;
2225
+		} elseif ($this->has_primary_key_field()) {
2226
+			$query = array();
2227
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2228
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2229
+			}
2230
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2231
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2232
+			$ways_to_identify_a_row = array();
2233
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2234
+				$values_for_each_combined_primary_key_for_a_row = array();
2235
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2236
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2237
+				}
2238
+				$ways_to_identify_a_row[] = '('
2239
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2240
+											. ')';
2241
+			}
2242
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2243
+		}
2244
+		return $query_part;
2245
+	}
2246
+
2247
+
2248
+
2249
+	/**
2250
+	 * Gets the model field by the fully qualified name
2251
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2252
+	 * @return EE_Model_Field_Base
2253
+	 */
2254
+	public function get_field_by_column($qualified_column_name)
2255
+	{
2256
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2257
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2258
+				return $field_obj;
2259
+			}
2260
+		}
2261
+		throw new EE_Error(
2262
+			sprintf(
2263
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2264
+				$this->get_this_model_name(),
2265
+				$qualified_column_name
2266
+			)
2267
+		);
2268
+	}
2269
+
2270
+
2271
+
2272
+	/**
2273
+	 * Count all the rows that match criteria the model query params.
2274
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2275
+	 * column
2276
+	 *
2277
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2278
+	 * @param string $field_to_count field on model to count by (not column name)
2279
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2280
+	 *                               that by the setting $distinct to TRUE;
2281
+	 * @return int
2282
+	 * @throws EE_Error
2283
+	 */
2284
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2285
+	{
2286
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2287
+		if ($field_to_count) {
2288
+			$field_obj = $this->field_settings_for($field_to_count);
2289
+			$column_to_count = $field_obj->get_qualified_column();
2290
+		} elseif ($this->has_primary_key_field()) {
2291
+			$pk_field_obj = $this->get_primary_key_field();
2292
+			$column_to_count = $pk_field_obj->get_qualified_column();
2293
+		} else {
2294
+			// there's no primary key
2295
+			// if we're counting distinct items, and there's no primary key,
2296
+			// we need to list out the columns for distinction;
2297
+			// otherwise we can just use star
2298
+			if ($distinct) {
2299
+				$columns_to_use = array();
2300
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2301
+					$columns_to_use[] = $field_obj->get_qualified_column();
2302
+				}
2303
+				$column_to_count = implode(',', $columns_to_use);
2304
+			} else {
2305
+				$column_to_count = '*';
2306
+			}
2307
+		}
2308
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2309
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2310
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2311
+	}
2312
+
2313
+
2314
+
2315
+	/**
2316
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2317
+	 *
2318
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2319
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2320
+	 * @return float
2321
+	 * @throws EE_Error
2322
+	 */
2323
+	public function sum($query_params, $field_to_sum = null)
2324
+	{
2325
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2326
+		if ($field_to_sum) {
2327
+			$field_obj = $this->field_settings_for($field_to_sum);
2328
+		} else {
2329
+			$field_obj = $this->get_primary_key_field();
2330
+		}
2331
+		$column_to_count = $field_obj->get_qualified_column();
2332
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2333
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2334
+		$data_type = $field_obj->get_wpdb_data_type();
2335
+		if ($data_type === '%d' || $data_type === '%s') {
2336
+			return (float) $return_value;
2337
+		}
2338
+		// must be %f
2339
+		return (float) $return_value;
2340
+	}
2341
+
2342
+
2343
+
2344
+	/**
2345
+	 * Just calls the specified method on $wpdb with the given arguments
2346
+	 * Consolidates a little extra error handling code
2347
+	 *
2348
+	 * @param string $wpdb_method
2349
+	 * @param array  $arguments_to_provide
2350
+	 * @throws EE_Error
2351
+	 * @global wpdb  $wpdb
2352
+	 * @return mixed
2353
+	 */
2354
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2355
+	{
2356
+		// if we're in maintenance mode level 2, DON'T run any queries
2357
+		// because level 2 indicates the database needs updating and
2358
+		// is probably out of sync with the code
2359
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2360
+			throw new EE_Error(sprintf(__(
2361
+				"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.",
2362
+				"event_espresso"
2363
+			)));
2364
+		}
2365
+		/** @type WPDB $wpdb */
2366
+		global $wpdb;
2367
+		if (! method_exists($wpdb, $wpdb_method)) {
2368
+			throw new EE_Error(sprintf(__(
2369
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2370
+				'event_espresso'
2371
+			), $wpdb_method));
2372
+		}
2373
+		if (WP_DEBUG) {
2374
+			$old_show_errors_value = $wpdb->show_errors;
2375
+			$wpdb->show_errors(false);
2376
+		}
2377
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2378
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2379
+		if (WP_DEBUG) {
2380
+			$wpdb->show_errors($old_show_errors_value);
2381
+			if (! empty($wpdb->last_error)) {
2382
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2383
+			}
2384
+			if ($result === false) {
2385
+				throw new EE_Error(sprintf(__(
2386
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2387
+					'event_espresso'
2388
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2389
+			}
2390
+		} elseif ($result === false) {
2391
+			EE_Error::add_error(
2392
+				sprintf(
2393
+					__(
2394
+						'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"',
2395
+						'event_espresso'
2396
+					),
2397
+					$wpdb_method,
2398
+					var_export($arguments_to_provide, true),
2399
+					$wpdb->last_error
2400
+				),
2401
+				__FILE__,
2402
+				__FUNCTION__,
2403
+				__LINE__
2404
+			);
2405
+		}
2406
+		return $result;
2407
+	}
2408
+
2409
+
2410
+
2411
+	/**
2412
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2413
+	 * and if there's an error tries to verify the DB is correct. Uses
2414
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2415
+	 * we should try to fix the EE core db, the addons, or just give up
2416
+	 *
2417
+	 * @param string $wpdb_method
2418
+	 * @param array  $arguments_to_provide
2419
+	 * @return mixed
2420
+	 */
2421
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2422
+	{
2423
+		/** @type WPDB $wpdb */
2424
+		global $wpdb;
2425
+		$wpdb->last_error = null;
2426
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2427
+		// was there an error running the query? but we don't care on new activations
2428
+		// (we're going to setup the DB anyway on new activations)
2429
+		if (
2430
+			($result === false || ! empty($wpdb->last_error))
2431
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2432
+		) {
2433
+			switch (EEM_Base::$_db_verification_level) {
2434
+				case EEM_Base::db_verified_none:
2435
+					// let's double-check core's DB
2436
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2437
+					break;
2438
+				case EEM_Base::db_verified_core:
2439
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2440
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2441
+					break;
2442
+				case EEM_Base::db_verified_addons:
2443
+					// ummmm... you in trouble
2444
+					return $result;
2445
+					break;
2446
+			}
2447
+			if (! empty($error_message)) {
2448
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2449
+				trigger_error($error_message);
2450
+			}
2451
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2452
+		}
2453
+		return $result;
2454
+	}
2455
+
2456
+
2457
+
2458
+	/**
2459
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2460
+	 * EEM_Base::$_db_verification_level
2461
+	 *
2462
+	 * @param string $wpdb_method
2463
+	 * @param array  $arguments_to_provide
2464
+	 * @return string
2465
+	 */
2466
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2467
+	{
2468
+		/** @type WPDB $wpdb */
2469
+		global $wpdb;
2470
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2471
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2472
+		$error_message = sprintf(
2473
+			__(
2474
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2475
+				'event_espresso'
2476
+			),
2477
+			$wpdb->last_error,
2478
+			$wpdb_method,
2479
+			wp_json_encode($arguments_to_provide)
2480
+		);
2481
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2482
+		return $error_message;
2483
+	}
2484
+
2485
+
2486
+
2487
+	/**
2488
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2489
+	 * EEM_Base::$_db_verification_level
2490
+	 *
2491
+	 * @param $wpdb_method
2492
+	 * @param $arguments_to_provide
2493
+	 * @return string
2494
+	 */
2495
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2496
+	{
2497
+		/** @type WPDB $wpdb */
2498
+		global $wpdb;
2499
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2500
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2501
+		$error_message = sprintf(
2502
+			__(
2503
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2504
+				'event_espresso'
2505
+			),
2506
+			$wpdb->last_error,
2507
+			$wpdb_method,
2508
+			wp_json_encode($arguments_to_provide)
2509
+		);
2510
+		EE_System::instance()->initialize_addons();
2511
+		return $error_message;
2512
+	}
2513
+
2514
+
2515
+
2516
+	/**
2517
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2518
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2519
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2520
+	 * ..."
2521
+	 *
2522
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2523
+	 * @return string
2524
+	 */
2525
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2526
+	{
2527
+		return " FROM " . $model_query_info->get_full_join_sql() .
2528
+			   $model_query_info->get_where_sql() .
2529
+			   $model_query_info->get_group_by_sql() .
2530
+			   $model_query_info->get_having_sql() .
2531
+			   $model_query_info->get_order_by_sql() .
2532
+			   $model_query_info->get_limit_sql();
2533
+	}
2534
+
2535
+
2536
+
2537
+	/**
2538
+	 * Set to easily debug the next X queries ran from this model.
2539
+	 *
2540
+	 * @param int $count
2541
+	 */
2542
+	public function show_next_x_db_queries($count = 1)
2543
+	{
2544
+		$this->_show_next_x_db_queries = $count;
2545
+	}
2546
+
2547
+
2548
+
2549
+	/**
2550
+	 * @param $sql_query
2551
+	 */
2552
+	public function show_db_query_if_previously_requested($sql_query)
2553
+	{
2554
+		if ($this->_show_next_x_db_queries > 0) {
2555
+			echo $sql_query;
2556
+			$this->_show_next_x_db_queries--;
2557
+		}
2558
+	}
2559
+
2560
+
2561
+
2562
+	/**
2563
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2564
+	 * There are the 3 cases:
2565
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2566
+	 * $otherModelObject has no ID, it is first saved.
2567
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2568
+	 * has no ID, it is first saved.
2569
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2570
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2571
+	 * join table
2572
+	 *
2573
+	 * @param        EE_Base_Class                     /int $thisModelObject
2574
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2575
+	 * @param string $relationName                     , key in EEM_Base::_relations
2576
+	 *                                                 an attendee to a group, you also want to specify which role they
2577
+	 *                                                 will have in that group. So you would use this parameter to
2578
+	 *                                                 specify array('role-column-name'=>'role-id')
2579
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2580
+	 *                                                 to for relation to methods that allow you to further specify
2581
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2582
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2583
+	 *                                                 because these will be inserted in any new rows created as well.
2584
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2585
+	 * @throws EE_Error
2586
+	 */
2587
+	public function add_relationship_to(
2588
+		$id_or_obj,
2589
+		$other_model_id_or_obj,
2590
+		$relationName,
2591
+		$extra_join_model_fields_n_values = array()
2592
+	) {
2593
+		$relation_obj = $this->related_settings_for($relationName);
2594
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2595
+	}
2596
+
2597
+
2598
+
2599
+	/**
2600
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2601
+	 * There are the 3 cases:
2602
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2603
+	 * error
2604
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2605
+	 * an error
2606
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2607
+	 *
2608
+	 * @param        EE_Base_Class /int $id_or_obj
2609
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2610
+	 * @param string $relationName key in EEM_Base::_relations
2611
+	 * @return boolean of success
2612
+	 * @throws EE_Error
2613
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2614
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2615
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2616
+	 *                             because these will be inserted in any new rows created as well.
2617
+	 */
2618
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2619
+	{
2620
+		$relation_obj = $this->related_settings_for($relationName);
2621
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2622
+	}
2623
+
2624
+
2625
+
2626
+	/**
2627
+	 * @param mixed           $id_or_obj
2628
+	 * @param string          $relationName
2629
+	 * @param array           $where_query_params
2630
+	 * @param EE_Base_Class[] objects to which relations were removed
2631
+	 * @return \EE_Base_Class[]
2632
+	 * @throws EE_Error
2633
+	 */
2634
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2635
+	{
2636
+		$relation_obj = $this->related_settings_for($relationName);
2637
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2638
+	}
2639
+
2640
+
2641
+
2642
+	/**
2643
+	 * Gets all the related items of the specified $model_name, using $query_params.
2644
+	 * Note: by default, we remove the "default query params"
2645
+	 * because we want to get even deleted items etc.
2646
+	 *
2647
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2648
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2649
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2650
+	 * @return EE_Base_Class[]
2651
+	 * @throws EE_Error
2652
+	 */
2653
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2654
+	{
2655
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2656
+		$relation_settings = $this->related_settings_for($model_name);
2657
+		return $relation_settings->get_all_related($model_obj, $query_params);
2658
+	}
2659
+
2660
+
2661
+
2662
+	/**
2663
+	 * Deletes all the model objects across the relation indicated by $model_name
2664
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2665
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2666
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2667
+	 *
2668
+	 * @param EE_Base_Class|int|string $id_or_obj
2669
+	 * @param string                   $model_name
2670
+	 * @param array                    $query_params
2671
+	 * @return int how many deleted
2672
+	 * @throws EE_Error
2673
+	 */
2674
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2675
+	{
2676
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2677
+		$relation_settings = $this->related_settings_for($model_name);
2678
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2679
+	}
2680
+
2681
+
2682
+
2683
+	/**
2684
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2685
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2686
+	 * the model objects can't be hard deleted because of blocking related model objects,
2687
+	 * just does a soft-delete on them instead.
2688
+	 *
2689
+	 * @param EE_Base_Class|int|string $id_or_obj
2690
+	 * @param string                   $model_name
2691
+	 * @param array                    $query_params
2692
+	 * @return int how many deleted
2693
+	 * @throws EE_Error
2694
+	 */
2695
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2696
+	{
2697
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2698
+		$relation_settings = $this->related_settings_for($model_name);
2699
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2700
+	}
2701
+
2702
+
2703
+
2704
+	/**
2705
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2706
+	 * unless otherwise specified in the $query_params
2707
+	 *
2708
+	 * @param        int             /EE_Base_Class $id_or_obj
2709
+	 * @param string $model_name     like 'Event', or 'Registration'
2710
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2711
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2712
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2713
+	 *                               that by the setting $distinct to TRUE;
2714
+	 * @return int
2715
+	 * @throws EE_Error
2716
+	 */
2717
+	public function count_related(
2718
+		$id_or_obj,
2719
+		$model_name,
2720
+		$query_params = array(),
2721
+		$field_to_count = null,
2722
+		$distinct = false
2723
+	) {
2724
+		$related_model = $this->get_related_model_obj($model_name);
2725
+		// we're just going to use the query params on the related model's normal get_all query,
2726
+		// except add a condition to say to match the current mod
2727
+		if (! isset($query_params['default_where_conditions'])) {
2728
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2729
+		}
2730
+		$this_model_name = $this->get_this_model_name();
2731
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2732
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2733
+		return $related_model->count($query_params, $field_to_count, $distinct);
2734
+	}
2735
+
2736
+
2737
+
2738
+	/**
2739
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2740
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2741
+	 *
2742
+	 * @param        int           /EE_Base_Class $id_or_obj
2743
+	 * @param string $model_name   like 'Event', or 'Registration'
2744
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2745
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2746
+	 * @return float
2747
+	 * @throws EE_Error
2748
+	 */
2749
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2750
+	{
2751
+		$related_model = $this->get_related_model_obj($model_name);
2752
+		if (! is_array($query_params)) {
2753
+			EE_Error::doing_it_wrong(
2754
+				'EEM_Base::sum_related',
2755
+				sprintf(
2756
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2757
+					gettype($query_params)
2758
+				),
2759
+				'4.6.0'
2760
+			);
2761
+			$query_params = array();
2762
+		}
2763
+		// we're just going to use the query params on the related model's normal get_all query,
2764
+		// except add a condition to say to match the current mod
2765
+		if (! isset($query_params['default_where_conditions'])) {
2766
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2767
+		}
2768
+		$this_model_name = $this->get_this_model_name();
2769
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2770
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2771
+		return $related_model->sum($query_params, $field_to_sum);
2772
+	}
2773
+
2774
+
2775
+
2776
+	/**
2777
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2778
+	 * $modelObject
2779
+	 *
2780
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2781
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2782
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2783
+	 * @return EE_Base_Class
2784
+	 * @throws EE_Error
2785
+	 */
2786
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2787
+	{
2788
+		$query_params['limit'] = 1;
2789
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2790
+		if ($results) {
2791
+			return array_shift($results);
2792
+		}
2793
+		return null;
2794
+	}
2795
+
2796
+
2797
+
2798
+	/**
2799
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2800
+	 *
2801
+	 * @return string
2802
+	 */
2803
+	public function get_this_model_name()
2804
+	{
2805
+		return str_replace("EEM_", "", get_class($this));
2806
+	}
2807
+
2808
+
2809
+
2810
+	/**
2811
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2812
+	 *
2813
+	 * @return EE_Any_Foreign_Model_Name_Field
2814
+	 * @throws EE_Error
2815
+	 */
2816
+	public function get_field_containing_related_model_name()
2817
+	{
2818
+		foreach ($this->field_settings(true) as $field) {
2819
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2820
+				$field_with_model_name = $field;
2821
+			}
2822
+		}
2823
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2824
+			throw new EE_Error(sprintf(
2825
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2826
+				$this->get_this_model_name()
2827
+			));
2828
+		}
2829
+		return $field_with_model_name;
2830
+	}
2831
+
2832
+
2833
+
2834
+	/**
2835
+	 * Inserts a new entry into the database, for each table.
2836
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2837
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2838
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2839
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2840
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2841
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2842
+	 *
2843
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2844
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2845
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2846
+	 *                              of EEM_Base)
2847
+	 * @return int|string new primary key on main table that got inserted
2848
+	 * @throws EE_Error
2849
+	 */
2850
+	public function insert($field_n_values)
2851
+	{
2852
+		/**
2853
+		 * Filters the fields and their values before inserting an item using the models
2854
+		 *
2855
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2856
+		 * @param EEM_Base $model           the model used
2857
+		 */
2858
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2859
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2860
+			$main_table = $this->_get_main_table();
2861
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2862
+			if ($new_id !== false) {
2863
+				foreach ($this->_get_other_tables() as $other_table) {
2864
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2865
+				}
2866
+			}
2867
+			/**
2868
+			 * Done just after attempting to insert a new model object
2869
+			 *
2870
+			 * @param EEM_Base   $model           used
2871
+			 * @param array      $fields_n_values fields and their values
2872
+			 * @param int|string the              ID of the newly-inserted model object
2873
+			 */
2874
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2875
+			return $new_id;
2876
+		}
2877
+		return false;
2878
+	}
2879
+
2880
+
2881
+
2882
+	/**
2883
+	 * Checks that the result would satisfy the unique indexes on this model
2884
+	 *
2885
+	 * @param array  $field_n_values
2886
+	 * @param string $action
2887
+	 * @return boolean
2888
+	 * @throws EE_Error
2889
+	 */
2890
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2891
+	{
2892
+		foreach ($this->unique_indexes() as $index_name => $index) {
2893
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2894
+			if ($this->exists(array($uniqueness_where_params))) {
2895
+				EE_Error::add_error(
2896
+					sprintf(
2897
+						__(
2898
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2899
+							"event_espresso"
2900
+						),
2901
+						$action,
2902
+						$this->_get_class_name(),
2903
+						$index_name,
2904
+						implode(",", $index->field_names()),
2905
+						http_build_query($uniqueness_where_params)
2906
+					),
2907
+					__FILE__,
2908
+					__FUNCTION__,
2909
+					__LINE__
2910
+				);
2911
+				return false;
2912
+			}
2913
+		}
2914
+		return true;
2915
+	}
2916
+
2917
+
2918
+
2919
+	/**
2920
+	 * Checks the database for an item that conflicts (ie, if this item were
2921
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2922
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2923
+	 * can be either an EE_Base_Class or an array of fields n values
2924
+	 *
2925
+	 * @param EE_Base_Class|array $obj_or_fields_array
2926
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2927
+	 *                                                 when looking for conflicts
2928
+	 *                                                 (ie, if false, we ignore the model object's primary key
2929
+	 *                                                 when finding "conflicts". If true, it's also considered).
2930
+	 *                                                 Only works for INT primary key,
2931
+	 *                                                 STRING primary keys cannot be ignored
2932
+	 * @throws EE_Error
2933
+	 * @return EE_Base_Class|array
2934
+	 */
2935
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2936
+	{
2937
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2938
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2939
+		} elseif (is_array($obj_or_fields_array)) {
2940
+			$fields_n_values = $obj_or_fields_array;
2941
+		} else {
2942
+			throw new EE_Error(
2943
+				sprintf(
2944
+					__(
2945
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2946
+						"event_espresso"
2947
+					),
2948
+					get_class($this),
2949
+					$obj_or_fields_array
2950
+				)
2951
+			);
2952
+		}
2953
+		$query_params = array();
2954
+		if (
2955
+			$this->has_primary_key_field()
2956
+			&& ($include_primary_key
2957
+				|| $this->get_primary_key_field()
2958
+				   instanceof
2959
+				   EE_Primary_Key_String_Field)
2960
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2961
+		) {
2962
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2963
+		}
2964
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2965
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2966
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2967
+		}
2968
+		// if there is nothing to base this search on, then we shouldn't find anything
2969
+		if (empty($query_params)) {
2970
+			return array();
2971
+		}
2972
+		return $this->get_one($query_params);
2973
+	}
2974
+
2975
+
2976
+
2977
+	/**
2978
+	 * Like count, but is optimized and returns a boolean instead of an int
2979
+	 *
2980
+	 * @param array $query_params
2981
+	 * @return boolean
2982
+	 * @throws EE_Error
2983
+	 */
2984
+	public function exists($query_params)
2985
+	{
2986
+		$query_params['limit'] = 1;
2987
+		return $this->count($query_params) > 0;
2988
+	}
2989
+
2990
+
2991
+
2992
+	/**
2993
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2994
+	 *
2995
+	 * @param int|string $id
2996
+	 * @return boolean
2997
+	 * @throws EE_Error
2998
+	 */
2999
+	public function exists_by_ID($id)
3000
+	{
3001
+		return $this->exists(
3002
+			array(
3003
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3004
+				array(
3005
+					$this->primary_key_name() => $id,
3006
+				),
3007
+			)
3008
+		);
3009
+	}
3010
+
3011
+
3012
+
3013
+	/**
3014
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3015
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3016
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3017
+	 * on the main table)
3018
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3019
+	 * cases where we want to call it directly rather than via insert().
3020
+	 *
3021
+	 * @access   protected
3022
+	 * @param EE_Table_Base $table
3023
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3024
+	 *                                       float
3025
+	 * @param int           $new_id          for now we assume only int keys
3026
+	 * @throws EE_Error
3027
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3028
+	 * @return int ID of new row inserted, or FALSE on failure
3029
+	 */
3030
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3031
+	{
3032
+		global $wpdb;
3033
+		$insertion_col_n_values = array();
3034
+		$format_for_insertion = array();
3035
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
3036
+		foreach ($fields_on_table as $field_name => $field_obj) {
3037
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3038
+			if ($field_obj->is_auto_increment()) {
3039
+				continue;
3040
+			}
3041
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3042
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3043
+			if ($prepared_value !== null) {
3044
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3045
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
3046
+			}
3047
+		}
3048
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3049
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3050
+			// so add the fk to the main table as a column
3051
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3052
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3053
+		}
3054
+		// insert the new entry
3055
+		$result = $this->_do_wpdb_query(
3056
+			'insert',
3057
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3058
+		);
3059
+		if ($result === false) {
3060
+			return false;
3061
+		}
3062
+		// ok, now what do we return for the ID of the newly-inserted thing?
3063
+		if ($this->has_primary_key_field()) {
3064
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3065
+				return $wpdb->insert_id;
3066
+			}
3067
+			// it's not an auto-increment primary key, so
3068
+			// it must have been supplied
3069
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3070
+		}
3071
+		// we can't return a  primary key because there is none. instead return
3072
+		// a unique string indicating this model
3073
+		return $this->get_index_primary_key_string($fields_n_values);
3074
+	}
3075
+
3076
+
3077
+
3078
+	/**
3079
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3080
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3081
+	 * and there is no default, we pass it along. WPDB will take care of it)
3082
+	 *
3083
+	 * @param EE_Model_Field_Base $field_obj
3084
+	 * @param array               $fields_n_values
3085
+	 * @return mixed string|int|float depending on what the table column will be expecting
3086
+	 * @throws EE_Error
3087
+	 */
3088
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3089
+	{
3090
+		// if this field doesn't allow nullable, don't allow it
3091
+		if (
3092
+			! $field_obj->is_nullable()
3093
+			&& (
3094
+				! isset($fields_n_values[ $field_obj->get_name() ])
3095
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3096
+			)
3097
+		) {
3098
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3099
+		}
3100
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3101
+			? $fields_n_values[ $field_obj->get_name() ]
3102
+			: null;
3103
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3104
+	}
3105
+
3106
+
3107
+
3108
+	/**
3109
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3110
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3111
+	 * the field's prepare_for_set() method.
3112
+	 *
3113
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3114
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3115
+	 *                                   top of file)
3116
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3117
+	 *                                   $value is a custom selection
3118
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3119
+	 */
3120
+	private function _prepare_value_for_use_in_db($value, $field)
3121
+	{
3122
+		if ($field && $field instanceof EE_Model_Field_Base) {
3123
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3124
+			switch ($this->_values_already_prepared_by_model_object) {
3125
+				/** @noinspection PhpMissingBreakStatementInspection */
3126
+				case self::not_prepared_by_model_object:
3127
+					$value = $field->prepare_for_set($value);
3128
+				// purposefully left out "return"
3129
+				// no break
3130
+				case self::prepared_by_model_object:
3131
+					/** @noinspection SuspiciousAssignmentsInspection */
3132
+					$value = $field->prepare_for_use_in_db($value);
3133
+					// no break
3134
+				case self::prepared_for_use_in_db:
3135
+					// leave the value alone
3136
+			}
3137
+			return $value;
3138
+			// phpcs:enable
3139
+		}
3140
+		return $value;
3141
+	}
3142
+
3143
+
3144
+
3145
+	/**
3146
+	 * Returns the main table on this model
3147
+	 *
3148
+	 * @return EE_Primary_Table
3149
+	 * @throws EE_Error
3150
+	 */
3151
+	protected function _get_main_table()
3152
+	{
3153
+		foreach ($this->_tables as $table) {
3154
+			if ($table instanceof EE_Primary_Table) {
3155
+				return $table;
3156
+			}
3157
+		}
3158
+		throw new EE_Error(sprintf(__(
3159
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3160
+			'event_espresso'
3161
+		), get_class($this)));
3162
+	}
3163
+
3164
+
3165
+
3166
+	/**
3167
+	 * table
3168
+	 * returns EE_Primary_Table table name
3169
+	 *
3170
+	 * @return string
3171
+	 * @throws EE_Error
3172
+	 */
3173
+	public function table()
3174
+	{
3175
+		return $this->_get_main_table()->get_table_name();
3176
+	}
3177
+
3178
+
3179
+
3180
+	/**
3181
+	 * table
3182
+	 * returns first EE_Secondary_Table table name
3183
+	 *
3184
+	 * @return string
3185
+	 */
3186
+	public function second_table()
3187
+	{
3188
+		// grab second table from tables array
3189
+		$second_table = end($this->_tables);
3190
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3191
+	}
3192
+
3193
+
3194
+
3195
+	/**
3196
+	 * get_table_obj_by_alias
3197
+	 * returns table name given it's alias
3198
+	 *
3199
+	 * @param string $table_alias
3200
+	 * @return EE_Primary_Table | EE_Secondary_Table
3201
+	 */
3202
+	public function get_table_obj_by_alias($table_alias = '')
3203
+	{
3204
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3205
+	}
3206
+
3207
+
3208
+
3209
+	/**
3210
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3211
+	 *
3212
+	 * @return EE_Secondary_Table[]
3213
+	 */
3214
+	protected function _get_other_tables()
3215
+	{
3216
+		$other_tables = array();
3217
+		foreach ($this->_tables as $table_alias => $table) {
3218
+			if ($table instanceof EE_Secondary_Table) {
3219
+				$other_tables[ $table_alias ] = $table;
3220
+			}
3221
+		}
3222
+		return $other_tables;
3223
+	}
3224
+
3225
+
3226
+
3227
+	/**
3228
+	 * Finds all the fields that correspond to the given table
3229
+	 *
3230
+	 * @param string $table_alias , array key in EEM_Base::_tables
3231
+	 * @return EE_Model_Field_Base[]
3232
+	 */
3233
+	public function _get_fields_for_table($table_alias)
3234
+	{
3235
+		return $this->_fields[ $table_alias ];
3236
+	}
3237
+
3238
+
3239
+
3240
+	/**
3241
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3242
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3243
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3244
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3245
+	 * related Registration, Transaction, and Payment models.
3246
+	 *
3247
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3248
+	 * @return EE_Model_Query_Info_Carrier
3249
+	 * @throws EE_Error
3250
+	 */
3251
+	public function _extract_related_models_from_query($query_params)
3252
+	{
3253
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3254
+		if (array_key_exists(0, $query_params)) {
3255
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3256
+		}
3257
+		if (array_key_exists('group_by', $query_params)) {
3258
+			if (is_array($query_params['group_by'])) {
3259
+				$this->_extract_related_models_from_sub_params_array_values(
3260
+					$query_params['group_by'],
3261
+					$query_info_carrier,
3262
+					'group_by'
3263
+				);
3264
+			} elseif (! empty($query_params['group_by'])) {
3265
+				$this->_extract_related_model_info_from_query_param(
3266
+					$query_params['group_by'],
3267
+					$query_info_carrier,
3268
+					'group_by'
3269
+				);
3270
+			}
3271
+		}
3272
+		if (array_key_exists('having', $query_params)) {
3273
+			$this->_extract_related_models_from_sub_params_array_keys(
3274
+				$query_params[0],
3275
+				$query_info_carrier,
3276
+				'having'
3277
+			);
3278
+		}
3279
+		if (array_key_exists('order_by', $query_params)) {
3280
+			if (is_array($query_params['order_by'])) {
3281
+				$this->_extract_related_models_from_sub_params_array_keys(
3282
+					$query_params['order_by'],
3283
+					$query_info_carrier,
3284
+					'order_by'
3285
+				);
3286
+			} elseif (! empty($query_params['order_by'])) {
3287
+				$this->_extract_related_model_info_from_query_param(
3288
+					$query_params['order_by'],
3289
+					$query_info_carrier,
3290
+					'order_by'
3291
+				);
3292
+			}
3293
+		}
3294
+		if (array_key_exists('force_join', $query_params)) {
3295
+			$this->_extract_related_models_from_sub_params_array_values(
3296
+				$query_params['force_join'],
3297
+				$query_info_carrier,
3298
+				'force_join'
3299
+			);
3300
+		}
3301
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3302
+		return $query_info_carrier;
3303
+	}
3304
+
3305
+
3306
+
3307
+	/**
3308
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3309
+	 *
3310
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3311
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3312
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3313
+	 * @throws EE_Error
3314
+	 * @return \EE_Model_Query_Info_Carrier
3315
+	 */
3316
+	private function _extract_related_models_from_sub_params_array_keys(
3317
+		$sub_query_params,
3318
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3319
+		$query_param_type
3320
+	) {
3321
+		if (! empty($sub_query_params)) {
3322
+			$sub_query_params = (array) $sub_query_params;
3323
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3324
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3325
+				$this->_extract_related_model_info_from_query_param(
3326
+					$param,
3327
+					$model_query_info_carrier,
3328
+					$query_param_type
3329
+				);
3330
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3331
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3332
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3333
+				// of array('Registration.TXN_ID'=>23)
3334
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3335
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3336
+					if (! is_array($possibly_array_of_params)) {
3337
+						throw new EE_Error(sprintf(
3338
+							__(
3339
+								"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'))",
3340
+								"event_espresso"
3341
+							),
3342
+							$param,
3343
+							$possibly_array_of_params
3344
+						));
3345
+					}
3346
+					$this->_extract_related_models_from_sub_params_array_keys(
3347
+						$possibly_array_of_params,
3348
+						$model_query_info_carrier,
3349
+						$query_param_type
3350
+					);
3351
+				} elseif (
3352
+					$query_param_type === 0 // ie WHERE
3353
+						  && is_array($possibly_array_of_params)
3354
+						  && isset($possibly_array_of_params[2])
3355
+						  && $possibly_array_of_params[2] == true
3356
+				) {
3357
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3358
+					// indicating that $possible_array_of_params[1] is actually a field name,
3359
+					// from which we should extract query parameters!
3360
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3361
+						throw new EE_Error(sprintf(__(
3362
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3363
+							"event_espresso"
3364
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3365
+					}
3366
+					$this->_extract_related_model_info_from_query_param(
3367
+						$possibly_array_of_params[1],
3368
+						$model_query_info_carrier,
3369
+						$query_param_type
3370
+					);
3371
+				}
3372
+			}
3373
+		}
3374
+		return $model_query_info_carrier;
3375
+	}
3376
+
3377
+
3378
+
3379
+	/**
3380
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3381
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3382
+	 *
3383
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3384
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3385
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3386
+	 * @throws EE_Error
3387
+	 * @return \EE_Model_Query_Info_Carrier
3388
+	 */
3389
+	private function _extract_related_models_from_sub_params_array_values(
3390
+		$sub_query_params,
3391
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3392
+		$query_param_type
3393
+	) {
3394
+		if (! empty($sub_query_params)) {
3395
+			if (! is_array($sub_query_params)) {
3396
+				throw new EE_Error(sprintf(
3397
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3398
+					$sub_query_params
3399
+				));
3400
+			}
3401
+			foreach ($sub_query_params as $param) {
3402
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3403
+				$this->_extract_related_model_info_from_query_param(
3404
+					$param,
3405
+					$model_query_info_carrier,
3406
+					$query_param_type
3407
+				);
3408
+			}
3409
+		}
3410
+		return $model_query_info_carrier;
3411
+	}
3412
+
3413
+
3414
+	/**
3415
+	 * Extract all the query parts from  model query params
3416
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3417
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3418
+	 * but use them in a different order. Eg, we need to know what models we are querying
3419
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3420
+	 * other models before we can finalize the where clause SQL.
3421
+	 *
3422
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3423
+	 * @throws EE_Error
3424
+	 * @return EE_Model_Query_Info_Carrier
3425
+	 * @throws ModelConfigurationException
3426
+	 */
3427
+	public function _create_model_query_info_carrier($query_params)
3428
+	{
3429
+		if (! is_array($query_params)) {
3430
+			EE_Error::doing_it_wrong(
3431
+				'EEM_Base::_create_model_query_info_carrier',
3432
+				sprintf(
3433
+					__(
3434
+						'$query_params should be an array, you passed a variable of type %s',
3435
+						'event_espresso'
3436
+					),
3437
+					gettype($query_params)
3438
+				),
3439
+				'4.6.0'
3440
+			);
3441
+			$query_params = array();
3442
+		}
3443
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3444
+		// first check if we should alter the query to account for caps or not
3445
+		// because the caps might require us to do extra joins
3446
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3447
+			$query_params[0] = array_replace_recursive(
3448
+				$query_params[0],
3449
+				$this->caps_where_conditions($query_params['caps'])
3450
+			);
3451
+		}
3452
+
3453
+		// check if we should alter the query to remove data related to protected
3454
+		// custom post types
3455
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3456
+			$where_param_key_for_password = $this->modelChainAndPassword();
3457
+			// only include if related to a cpt where no password has been set
3458
+			$query_params[0]['OR*nopassword'] = array(
3459
+				$where_param_key_for_password => '',
3460
+				$where_param_key_for_password . '*' => array('IS_NULL')
3461
+			);
3462
+		}
3463
+		$query_object = $this->_extract_related_models_from_query($query_params);
3464
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3465
+		foreach ($query_params[0] as $key => $value) {
3466
+			if (is_int($key)) {
3467
+				throw new EE_Error(
3468
+					sprintf(
3469
+						__(
3470
+							"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.",
3471
+							"event_espresso"
3472
+						),
3473
+						$key,
3474
+						var_export($value, true),
3475
+						var_export($query_params, true),
3476
+						get_class($this)
3477
+					)
3478
+				);
3479
+			}
3480
+		}
3481
+		if (
3482
+			array_key_exists('default_where_conditions', $query_params)
3483
+			&& ! empty($query_params['default_where_conditions'])
3484
+		) {
3485
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3486
+		} else {
3487
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3488
+		}
3489
+		$query_params[0] = array_merge(
3490
+			$this->_get_default_where_conditions_for_models_in_query(
3491
+				$query_object,
3492
+				$use_default_where_conditions,
3493
+				$query_params[0]
3494
+			),
3495
+			$query_params[0]
3496
+		);
3497
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3498
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3499
+		// So we need to setup a subquery and use that for the main join.
3500
+		// Note for now this only works on the primary table for the model.
3501
+		// So for instance, you could set the limit array like this:
3502
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3503
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3504
+			$query_object->set_main_model_join_sql(
3505
+				$this->_construct_limit_join_select(
3506
+					$query_params['on_join_limit'][0],
3507
+					$query_params['on_join_limit'][1]
3508
+				)
3509
+			);
3510
+		}
3511
+		// set limit
3512
+		if (array_key_exists('limit', $query_params)) {
3513
+			if (is_array($query_params['limit'])) {
3514
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3515
+					$e = sprintf(
3516
+						__(
3517
+							"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)",
3518
+							"event_espresso"
3519
+						),
3520
+						http_build_query($query_params['limit'])
3521
+					);
3522
+					throw new EE_Error($e . "|" . $e);
3523
+				}
3524
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3525
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3526
+			} elseif (! empty($query_params['limit'])) {
3527
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3528
+			}
3529
+		}
3530
+		// set order by
3531
+		if (array_key_exists('order_by', $query_params)) {
3532
+			if (is_array($query_params['order_by'])) {
3533
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3534
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3535
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3536
+				if (array_key_exists('order', $query_params)) {
3537
+					throw new EE_Error(
3538
+						sprintf(
3539
+							__(
3540
+								"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 ",
3541
+								"event_espresso"
3542
+							),
3543
+							get_class($this),
3544
+							implode(", ", array_keys($query_params['order_by'])),
3545
+							implode(", ", $query_params['order_by']),
3546
+							$query_params['order']
3547
+						)
3548
+					);
3549
+				}
3550
+				$this->_extract_related_models_from_sub_params_array_keys(
3551
+					$query_params['order_by'],
3552
+					$query_object,
3553
+					'order_by'
3554
+				);
3555
+				// assume it's an array of fields to order by
3556
+				$order_array = array();
3557
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3558
+					$order = $this->_extract_order($order);
3559
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3560
+				}
3561
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3562
+			} elseif (! empty($query_params['order_by'])) {
3563
+				$this->_extract_related_model_info_from_query_param(
3564
+					$query_params['order_by'],
3565
+					$query_object,
3566
+					'order',
3567
+					$query_params['order_by']
3568
+				);
3569
+				$order = isset($query_params['order'])
3570
+					? $this->_extract_order($query_params['order'])
3571
+					: 'DESC';
3572
+				$query_object->set_order_by_sql(
3573
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3574
+				);
3575
+			}
3576
+		}
3577
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3578
+		if (
3579
+			! array_key_exists('order_by', $query_params)
3580
+			&& array_key_exists('order', $query_params)
3581
+			&& ! empty($query_params['order'])
3582
+		) {
3583
+			$pk_field = $this->get_primary_key_field();
3584
+			$order = $this->_extract_order($query_params['order']);
3585
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3586
+		}
3587
+		// set group by
3588
+		if (array_key_exists('group_by', $query_params)) {
3589
+			if (is_array($query_params['group_by'])) {
3590
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3591
+				$group_by_array = array();
3592
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3593
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3594
+				}
3595
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3596
+			} elseif (! empty($query_params['group_by'])) {
3597
+				$query_object->set_group_by_sql(
3598
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3599
+				);
3600
+			}
3601
+		}
3602
+		// set having
3603
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3604
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3605
+		}
3606
+		// now, just verify they didn't pass anything wack
3607
+		foreach ($query_params as $query_key => $query_value) {
3608
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3609
+				throw new EE_Error(
3610
+					sprintf(
3611
+						__(
3612
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3613
+							'event_espresso'
3614
+						),
3615
+						$query_key,
3616
+						get_class($this),
3617
+						//                      print_r( $this->_allowed_query_params, TRUE )
3618
+						implode(',', $this->_allowed_query_params)
3619
+					)
3620
+				);
3621
+			}
3622
+		}
3623
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3624
+		if (empty($main_model_join_sql)) {
3625
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3626
+		}
3627
+		return $query_object;
3628
+	}
3629
+
3630
+
3631
+
3632
+	/**
3633
+	 * Gets the where conditions that should be imposed on the query based on the
3634
+	 * context (eg reading frontend, backend, edit or delete).
3635
+	 *
3636
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3637
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3638
+	 * @throws EE_Error
3639
+	 */
3640
+	public function caps_where_conditions($context = self::caps_read)
3641
+	{
3642
+		EEM_Base::verify_is_valid_cap_context($context);
3643
+		$cap_where_conditions = array();
3644
+		$cap_restrictions = $this->caps_missing($context);
3645
+		/**
3646
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3647
+		 */
3648
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3649
+			$cap_where_conditions = array_replace_recursive(
3650
+				$cap_where_conditions,
3651
+				$restriction_if_no_cap->get_default_where_conditions()
3652
+			);
3653
+		}
3654
+		return apply_filters(
3655
+			'FHEE__EEM_Base__caps_where_conditions__return',
3656
+			$cap_where_conditions,
3657
+			$this,
3658
+			$context,
3659
+			$cap_restrictions
3660
+		);
3661
+	}
3662
+
3663
+
3664
+
3665
+	/**
3666
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3667
+	 * otherwise throws an exception
3668
+	 *
3669
+	 * @param string $should_be_order_string
3670
+	 * @return string either ASC, asc, DESC or desc
3671
+	 * @throws EE_Error
3672
+	 */
3673
+	private function _extract_order($should_be_order_string)
3674
+	{
3675
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3676
+			return $should_be_order_string;
3677
+		}
3678
+		throw new EE_Error(
3679
+			sprintf(
3680
+				__(
3681
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3682
+					"event_espresso"
3683
+				),
3684
+				get_class($this),
3685
+				$should_be_order_string
3686
+			)
3687
+		);
3688
+	}
3689
+
3690
+
3691
+
3692
+	/**
3693
+	 * Looks at all the models which are included in this query, and asks each
3694
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3695
+	 * so they can be merged
3696
+	 *
3697
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3698
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3699
+	 *                                                                  'none' means NO default where conditions will
3700
+	 *                                                                  be used AT ALL during this query.
3701
+	 *                                                                  'other_models_only' means default where
3702
+	 *                                                                  conditions from other models will be used, but
3703
+	 *                                                                  not for this primary model. 'all', the default,
3704
+	 *                                                                  means default where conditions will apply as
3705
+	 *                                                                  normal
3706
+	 * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3707
+	 * @throws EE_Error
3708
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3709
+	 */
3710
+	private function _get_default_where_conditions_for_models_in_query(
3711
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3712
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3713
+		$where_query_params = array()
3714
+	) {
3715
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3716
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3717
+			throw new EE_Error(sprintf(
3718
+				__(
3719
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3720
+					"event_espresso"
3721
+				),
3722
+				$use_default_where_conditions,
3723
+				implode(", ", $allowed_used_default_where_conditions_values)
3724
+			));
3725
+		}
3726
+		$universal_query_params = array();
3727
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3728
+			$universal_query_params = $this->_get_default_where_conditions();
3729
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3730
+			$universal_query_params = $this->_get_minimum_where_conditions();
3731
+		}
3732
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3733
+			$related_model = $this->get_related_model_obj($model_name);
3734
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3735
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3736
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3737
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3738
+			} else {
3739
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3740
+				continue;
3741
+			}
3742
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3743
+				$related_model_universal_where_params,
3744
+				$where_query_params,
3745
+				$related_model,
3746
+				$model_relation_path
3747
+			);
3748
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3749
+				$universal_query_params,
3750
+				$overrides
3751
+			);
3752
+		}
3753
+		return $universal_query_params;
3754
+	}
3755
+
3756
+
3757
+
3758
+	/**
3759
+	 * Determines whether or not we should use default where conditions for the model in question
3760
+	 * (this model, or other related models).
3761
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3762
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3763
+	 * We should use default where conditions on related models when they requested to use default where conditions
3764
+	 * on all models, or specifically just on other related models
3765
+	 * @param      $default_where_conditions_value
3766
+	 * @param bool $for_this_model false means this is for OTHER related models
3767
+	 * @return bool
3768
+	 */
3769
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3770
+	{
3771
+		return (
3772
+				   $for_this_model
3773
+				   && in_array(
3774
+					   $default_where_conditions_value,
3775
+					   array(
3776
+						   EEM_Base::default_where_conditions_all,
3777
+						   EEM_Base::default_where_conditions_this_only,
3778
+						   EEM_Base::default_where_conditions_minimum_others,
3779
+					   ),
3780
+					   true
3781
+				   )
3782
+			   )
3783
+			   || (
3784
+				   ! $for_this_model
3785
+				   && in_array(
3786
+					   $default_where_conditions_value,
3787
+					   array(
3788
+						   EEM_Base::default_where_conditions_all,
3789
+						   EEM_Base::default_where_conditions_others_only,
3790
+					   ),
3791
+					   true
3792
+				   )
3793
+			   );
3794
+	}
3795
+
3796
+	/**
3797
+	 * Determines whether or not we should use default minimum conditions for the model in question
3798
+	 * (this model, or other related models).
3799
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3800
+	 * where conditions.
3801
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3802
+	 * on this model or others
3803
+	 * @param      $default_where_conditions_value
3804
+	 * @param bool $for_this_model false means this is for OTHER related models
3805
+	 * @return bool
3806
+	 */
3807
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3808
+	{
3809
+		return (
3810
+				   $for_this_model
3811
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3812
+			   )
3813
+			   || (
3814
+				   ! $for_this_model
3815
+				   && in_array(
3816
+					   $default_where_conditions_value,
3817
+					   array(
3818
+						   EEM_Base::default_where_conditions_minimum_others,
3819
+						   EEM_Base::default_where_conditions_minimum_all,
3820
+					   ),
3821
+					   true
3822
+				   )
3823
+			   );
3824
+	}
3825
+
3826
+
3827
+	/**
3828
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3829
+	 * then we also add a special where condition which allows for that model's primary key
3830
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3831
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3832
+	 *
3833
+	 * @param array    $default_where_conditions
3834
+	 * @param array    $provided_where_conditions
3835
+	 * @param EEM_Base $model
3836
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3837
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3838
+	 * @throws EE_Error
3839
+	 */
3840
+	private function _override_defaults_or_make_null_friendly(
3841
+		$default_where_conditions,
3842
+		$provided_where_conditions,
3843
+		$model,
3844
+		$model_relation_path
3845
+	) {
3846
+		$null_friendly_where_conditions = array();
3847
+		$none_overridden = true;
3848
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3849
+		foreach ($default_where_conditions as $key => $val) {
3850
+			if (isset($provided_where_conditions[ $key ])) {
3851
+				$none_overridden = false;
3852
+			} else {
3853
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3854
+			}
3855
+		}
3856
+		if ($none_overridden && $default_where_conditions) {
3857
+			if ($model->has_primary_key_field()) {
3858
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3859
+																				. "."
3860
+																				. $model->primary_key_name() ] = array('IS NULL');
3861
+			}/*else{
3862 3862
                 //@todo NO PK, use other defaults
3863 3863
             }*/
3864
-        }
3865
-        return $null_friendly_where_conditions;
3866
-    }
3867
-
3868
-
3869
-
3870
-    /**
3871
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3872
-     * default where conditions on all get_all, update, and delete queries done by this model.
3873
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3874
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3875
-     *
3876
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3877
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3878
-     */
3879
-    private function _get_default_where_conditions($model_relation_path = '')
3880
-    {
3881
-        if ($this->_ignore_where_strategy) {
3882
-            return array();
3883
-        }
3884
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3885
-    }
3886
-
3887
-
3888
-
3889
-    /**
3890
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3891
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3892
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3893
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3894
-     * Similar to _get_default_where_conditions
3895
-     *
3896
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3897
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3898
-     */
3899
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3900
-    {
3901
-        if ($this->_ignore_where_strategy) {
3902
-            return array();
3903
-        }
3904
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3905
-    }
3906
-
3907
-
3908
-
3909
-    /**
3910
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3911
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3912
-     *
3913
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3914
-     * @return string
3915
-     * @throws EE_Error
3916
-     */
3917
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3918
-    {
3919
-        $selects = $this->_get_columns_to_select_for_this_model();
3920
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included) {
3921
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3922
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3923
-            foreach ($other_model_selects as $key => $value) {
3924
-                $selects[] = $value;
3925
-            }
3926
-        }
3927
-        return implode(", ", $selects);
3928
-    }
3929
-
3930
-
3931
-
3932
-    /**
3933
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3934
-     * So that's going to be the columns for all the fields on the model
3935
-     *
3936
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3937
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3938
-     */
3939
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3940
-    {
3941
-        $fields = $this->field_settings();
3942
-        $selects = array();
3943
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3944
-            $model_relation_chain,
3945
-            $this->get_this_model_name()
3946
-        );
3947
-        foreach ($fields as $field_obj) {
3948
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3949
-                         . $field_obj->get_table_alias()
3950
-                         . "."
3951
-                         . $field_obj->get_table_column()
3952
-                         . " AS '"
3953
-                         . $table_alias_with_model_relation_chain_prefix
3954
-                         . $field_obj->get_table_alias()
3955
-                         . "."
3956
-                         . $field_obj->get_table_column()
3957
-                         . "'";
3958
-        }
3959
-        // make sure we are also getting the PKs of each table
3960
-        $tables = $this->get_tables();
3961
-        if (count($tables) > 1) {
3962
-            foreach ($tables as $table_obj) {
3963
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3964
-                                       . $table_obj->get_fully_qualified_pk_column();
3965
-                if (! in_array($qualified_pk_column, $selects)) {
3966
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3967
-                }
3968
-            }
3969
-        }
3970
-        return $selects;
3971
-    }
3972
-
3973
-
3974
-
3975
-    /**
3976
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3977
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3978
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3979
-     * SQL for joining, and the data types
3980
-     *
3981
-     * @param null|string                 $original_query_param
3982
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3983
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3984
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3985
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3986
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3987
-     *                                                          or 'Registration's
3988
-     * @param string                      $original_query_param what it originally was (eg
3989
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3990
-     *                                                          matches $query_param
3991
-     * @throws EE_Error
3992
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3993
-     */
3994
-    private function _extract_related_model_info_from_query_param(
3995
-        $query_param,
3996
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3997
-        $query_param_type,
3998
-        $original_query_param = null
3999
-    ) {
4000
-        if ($original_query_param === null) {
4001
-            $original_query_param = $query_param;
4002
-        }
4003
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4004
-        // check to see if we have a field on this model
4005
-        $this_model_fields = $this->field_settings(true);
4006
-        if (array_key_exists($query_param, $this_model_fields)) {
4007
-            $field_is_allowed = in_array(
4008
-                $query_param_type,
4009
-                [0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4010
-                true
4011
-            );
4012
-            if ($field_is_allowed) {
4013
-                return;
4014
-            }
4015
-            throw new EE_Error(
4016
-                sprintf(
4017
-                    __(
4018
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4019
-                        "event_espresso"
4020
-                    ),
4021
-                    $query_param,
4022
-                    get_class($this),
4023
-                    $query_param_type,
4024
-                    $original_query_param
4025
-                )
4026
-            );
4027
-        }
4028
-        // check if this is a special logic query param
4029
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4030
-            $operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4031
-            if ($operator_is_allowed) {
4032
-                return;
4033
-            }
4034
-            throw new EE_Error(
4035
-                sprintf(
4036
-                    __(
4037
-                        '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',
4038
-                        'event_espresso'
4039
-                    ),
4040
-                    implode('", "', $this->_logic_query_param_keys),
4041
-                    $query_param,
4042
-                    get_class($this),
4043
-                    '<br />',
4044
-                    "\t"
4045
-                    . ' $passed_in_query_info = <pre>'
4046
-                    . print_r($passed_in_query_info, true)
4047
-                    . '</pre>'
4048
-                    . "\n\t"
4049
-                    . ' $query_param_type = '
4050
-                    . $query_param_type
4051
-                    . "\n\t"
4052
-                    . ' $original_query_param = '
4053
-                    . $original_query_param
4054
-                )
4055
-            );
4056
-        }
4057
-        // check if it's a custom selection
4058
-        if (
4059
-            $this->_custom_selections instanceof CustomSelects
4060
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4061
-        ) {
4062
-            return;
4063
-        }
4064
-        // check if has a model name at the beginning
4065
-        // and
4066
-        // check if it's a field on a related model
4067
-        if (
4068
-            $this->extractJoinModelFromQueryParams(
4069
-                $passed_in_query_info,
4070
-                $query_param,
4071
-                $original_query_param,
4072
-                $query_param_type
4073
-            )
4074
-        ) {
4075
-            return;
4076
-        }
4077
-
4078
-        // ok so $query_param didn't start with a model name
4079
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4080
-        // it's wack, that's what it is
4081
-        throw new EE_Error(
4082
-            sprintf(
4083
-                esc_html__(
4084
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4085
-                    "event_espresso"
4086
-                ),
4087
-                $query_param,
4088
-                get_class($this),
4089
-                $query_param_type,
4090
-                $original_query_param
4091
-            )
4092
-        );
4093
-    }
4094
-
4095
-
4096
-    /**
4097
-     * Extracts any possible join model information from the provided possible_join_string.
4098
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4099
-     * parts that should be added to the query.
4100
-     *
4101
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4102
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4103
-     * @param null|string                 $original_query_param
4104
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4105
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4106
-     * @return bool  returns true if a join was added and false if not.
4107
-     * @throws EE_Error
4108
-     */
4109
-    private function extractJoinModelFromQueryParams(
4110
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4111
-        $possible_join_string,
4112
-        $original_query_param,
4113
-        $query_parameter_type
4114
-    ) {
4115
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4116
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4117
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4118
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4119
-                if ($possible_join_string === '') {
4120
-                    // nothing left to $query_param
4121
-                    // we should actually end in a field name, not a model like this!
4122
-                    throw new EE_Error(
4123
-                        sprintf(
4124
-                            esc_html__(
4125
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4126
-                                "event_espresso"
4127
-                            ),
4128
-                            $possible_join_string,
4129
-                            $query_parameter_type,
4130
-                            get_class($this),
4131
-                            $valid_related_model_name
4132
-                        )
4133
-                    );
4134
-                }
4135
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4136
-                $related_model_obj->_extract_related_model_info_from_query_param(
4137
-                    $possible_join_string,
4138
-                    $query_info_carrier,
4139
-                    $query_parameter_type,
4140
-                    $original_query_param
4141
-                );
4142
-                return true;
4143
-            }
4144
-            if ($possible_join_string === $valid_related_model_name) {
4145
-                $this->_add_join_to_model(
4146
-                    $valid_related_model_name,
4147
-                    $query_info_carrier,
4148
-                    $original_query_param
4149
-                );
4150
-                return true;
4151
-            }
4152
-        }
4153
-        return false;
4154
-    }
4155
-
4156
-
4157
-    /**
4158
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4159
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4160
-     * @throws EE_Error
4161
-     */
4162
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4163
-    {
4164
-        if (
4165
-            $this->_custom_selections instanceof CustomSelects
4166
-            && (
4167
-                $this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4168
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4169
-            )
4170
-        ) {
4171
-            $original_selects = $this->_custom_selections->originalSelects();
4172
-            foreach ($original_selects as $alias => $select_configuration) {
4173
-                $this->extractJoinModelFromQueryParams(
4174
-                    $query_info_carrier,
4175
-                    $select_configuration[0],
4176
-                    $select_configuration[0],
4177
-                    'custom_selects'
4178
-                );
4179
-            }
4180
-        }
4181
-    }
4182
-
4183
-
4184
-
4185
-    /**
4186
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4187
-     * and store it on $passed_in_query_info
4188
-     *
4189
-     * @param string                      $model_name
4190
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4191
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4192
-     *                                                          model and $model_name. Eg, if we are querying Event,
4193
-     *                                                          and are adding a join to 'Payment' with the original
4194
-     *                                                          query param key
4195
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4196
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4197
-     *                                                          Payment wants to add default query params so that it
4198
-     *                                                          will know what models to prepend onto its default query
4199
-     *                                                          params or in case it wants to rename tables (in case
4200
-     *                                                          there are multiple joins to the same table)
4201
-     * @return void
4202
-     * @throws EE_Error
4203
-     */
4204
-    private function _add_join_to_model(
4205
-        $model_name,
4206
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4207
-        $original_query_param
4208
-    ) {
4209
-        $relation_obj = $this->related_settings_for($model_name);
4210
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4211
-        // check if the relation is HABTM, because then we're essentially doing two joins
4212
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4213
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4214
-            $join_model_obj = $relation_obj->get_join_model();
4215
-            // replace the model specified with the join model for this relation chain, whi
4216
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4217
-                $model_name,
4218
-                $join_model_obj->get_this_model_name(),
4219
-                $model_relation_chain
4220
-            );
4221
-            $passed_in_query_info->merge(
4222
-                new EE_Model_Query_Info_Carrier(
4223
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4224
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4225
-                )
4226
-            );
4227
-        }
4228
-        // now just join to the other table pointed to by the relation object, and add its data types
4229
-        $passed_in_query_info->merge(
4230
-            new EE_Model_Query_Info_Carrier(
4231
-                array($model_relation_chain => $model_name),
4232
-                $relation_obj->get_join_statement($model_relation_chain)
4233
-            )
4234
-        );
4235
-    }
4236
-
4237
-
4238
-
4239
-    /**
4240
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4241
-     *
4242
-     * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4243
-     * @return string of SQL
4244
-     * @throws EE_Error
4245
-     */
4246
-    private function _construct_where_clause($where_params)
4247
-    {
4248
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4249
-        if ($SQL) {
4250
-            return " WHERE " . $SQL;
4251
-        }
4252
-        return '';
4253
-    }
4254
-
4255
-
4256
-
4257
-    /**
4258
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4259
-     * and should be passed HAVING parameters, not WHERE parameters
4260
-     *
4261
-     * @param array $having_params
4262
-     * @return string
4263
-     * @throws EE_Error
4264
-     */
4265
-    private function _construct_having_clause($having_params)
4266
-    {
4267
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4268
-        if ($SQL) {
4269
-            return " HAVING " . $SQL;
4270
-        }
4271
-        return '';
4272
-    }
4273
-
4274
-
4275
-    /**
4276
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4277
-     * Event_Meta.meta_value = 'foo'))"
4278
-     *
4279
-     * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4280
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4281
-     * @throws EE_Error
4282
-     * @return string of SQL
4283
-     */
4284
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4285
-    {
4286
-        $where_clauses = array();
4287
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4288
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4289
-            if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4290
-                switch ($query_param) {
4291
-                    case 'not':
4292
-                    case 'NOT':
4293
-                        $where_clauses[] = "! ("
4294
-                                           . $this->_construct_condition_clause_recursive(
4295
-                                               $op_and_value_or_sub_condition,
4296
-                                               $glue
4297
-                                           )
4298
-                                           . ")";
4299
-                        break;
4300
-                    case 'and':
4301
-                    case 'AND':
4302
-                        $where_clauses[] = " ("
4303
-                                           . $this->_construct_condition_clause_recursive(
4304
-                                               $op_and_value_or_sub_condition,
4305
-                                               ' AND '
4306
-                                           )
4307
-                                           . ")";
4308
-                        break;
4309
-                    case 'or':
4310
-                    case 'OR':
4311
-                        $where_clauses[] = " ("
4312
-                                           . $this->_construct_condition_clause_recursive(
4313
-                                               $op_and_value_or_sub_condition,
4314
-                                               ' OR '
4315
-                                           )
4316
-                                           . ")";
4317
-                        break;
4318
-                }
4319
-            } else {
4320
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4321
-                // if it's not a normal field, maybe it's a custom selection?
4322
-                if (! $field_obj) {
4323
-                    if ($this->_custom_selections instanceof CustomSelects) {
4324
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4325
-                    } else {
4326
-                        throw new EE_Error(sprintf(__(
4327
-                            "%s is neither a valid model field name, nor a custom selection",
4328
-                            "event_espresso"
4329
-                        ), $query_param));
4330
-                    }
4331
-                }
4332
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4333
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4334
-            }
4335
-        }
4336
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4337
-    }
4338
-
4339
-
4340
-
4341
-    /**
4342
-     * Takes the input parameter and extract the table name (alias) and column name
4343
-     *
4344
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4345
-     * @throws EE_Error
4346
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4347
-     */
4348
-    private function _deduce_column_name_from_query_param($query_param)
4349
-    {
4350
-        $field = $this->_deduce_field_from_query_param($query_param);
4351
-        if ($field) {
4352
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4353
-                $field->get_model_name(),
4354
-                $query_param
4355
-            );
4356
-            return $table_alias_prefix . $field->get_qualified_column();
4357
-        }
4358
-        if (
4359
-            $this->_custom_selections instanceof CustomSelects
4360
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4361
-        ) {
4362
-            // maybe it's custom selection item?
4363
-            // if so, just use it as the "column name"
4364
-            return $query_param;
4365
-        }
4366
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4367
-            ? implode(',', $this->_custom_selections->columnAliases())
4368
-            : '';
4369
-        throw new EE_Error(
4370
-            sprintf(
4371
-                __(
4372
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4373
-                    "event_espresso"
4374
-                ),
4375
-                $query_param,
4376
-                $custom_select_aliases
4377
-            )
4378
-        );
4379
-    }
4380
-
4381
-
4382
-
4383
-    /**
4384
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4385
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4386
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4387
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4388
-     *
4389
-     * @param string $condition_query_param_key
4390
-     * @return string
4391
-     */
4392
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4393
-    {
4394
-        $pos_of_star = strpos($condition_query_param_key, '*');
4395
-        if ($pos_of_star === false) {
4396
-            return $condition_query_param_key;
4397
-        }
4398
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4399
-        return $condition_query_param_sans_star;
4400
-    }
4401
-
4402
-
4403
-
4404
-    /**
4405
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4406
-     *
4407
-     * @param                            mixed      array | string    $op_and_value
4408
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4409
-     * @throws EE_Error
4410
-     * @return string
4411
-     */
4412
-    private function _construct_op_and_value($op_and_value, $field_obj)
4413
-    {
4414
-        if (is_array($op_and_value)) {
4415
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4416
-            if (! $operator) {
4417
-                $php_array_like_string = array();
4418
-                foreach ($op_and_value as $key => $value) {
4419
-                    $php_array_like_string[] = "$key=>$value";
4420
-                }
4421
-                throw new EE_Error(
4422
-                    sprintf(
4423
-                        __(
4424
-                            "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))",
4425
-                            "event_espresso"
4426
-                        ),
4427
-                        implode(",", $php_array_like_string)
4428
-                    )
4429
-                );
4430
-            }
4431
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4432
-        } else {
4433
-            $operator = '=';
4434
-            $value = $op_and_value;
4435
-        }
4436
-        // check to see if the value is actually another field
4437
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4438
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4439
-        }
4440
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4441
-            // in this case, the value should be an array, or at least a comma-separated list
4442
-            // it will need to handle a little differently
4443
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4444
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4445
-            return $operator . SP . $cleaned_value;
4446
-        }
4447
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4448
-            // the value should be an array with count of two.
4449
-            if (count($value) !== 2) {
4450
-                throw new EE_Error(
4451
-                    sprintf(
4452
-                        __(
4453
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4454
-                            'event_espresso'
4455
-                        ),
4456
-                        "BETWEEN"
4457
-                    )
4458
-                );
4459
-            }
4460
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4461
-            return $operator . SP . $cleaned_value;
4462
-        }
4463
-        if (in_array($operator, $this->valid_null_style_operators())) {
4464
-            if ($value !== null) {
4465
-                throw new EE_Error(
4466
-                    sprintf(
4467
-                        __(
4468
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4469
-                            "event_espresso"
4470
-                        ),
4471
-                        $value,
4472
-                        $operator
4473
-                    )
4474
-                );
4475
-            }
4476
-            return $operator;
4477
-        }
4478
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4479
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4480
-            // remove other junk. So just treat it as a string.
4481
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4482
-        }
4483
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4484
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4485
-        }
4486
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4487
-            throw new EE_Error(
4488
-                sprintf(
4489
-                    __(
4490
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4491
-                        'event_espresso'
4492
-                    ),
4493
-                    $operator,
4494
-                    $operator
4495
-                )
4496
-            );
4497
-        }
4498
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4499
-            throw new EE_Error(
4500
-                sprintf(
4501
-                    __(
4502
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4503
-                        'event_espresso'
4504
-                    ),
4505
-                    $operator,
4506
-                    $operator
4507
-                )
4508
-            );
4509
-        }
4510
-        throw new EE_Error(
4511
-            sprintf(
4512
-                __(
4513
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4514
-                    "event_espresso"
4515
-                ),
4516
-                http_build_query($op_and_value)
4517
-            )
4518
-        );
4519
-    }
4520
-
4521
-
4522
-
4523
-    /**
4524
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4525
-     *
4526
-     * @param array                      $values
4527
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4528
-     *                                              '%s'
4529
-     * @return string
4530
-     * @throws EE_Error
4531
-     */
4532
-    public function _construct_between_value($values, $field_obj)
4533
-    {
4534
-        $cleaned_values = array();
4535
-        foreach ($values as $value) {
4536
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4537
-        }
4538
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4539
-    }
4540
-
4541
-
4542
-    /**
4543
-     * Takes an array or a comma-separated list of $values and cleans them
4544
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4545
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4546
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4547
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4548
-     *
4549
-     * @param mixed                      $values    array or comma-separated string
4550
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4551
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4552
-     * @throws EE_Error
4553
-     */
4554
-    public function _construct_in_value($values, $field_obj)
4555
-    {
4556
-        $prepped = [];
4557
-        // check if the value is a CSV list
4558
-        if (is_string($values)) {
4559
-            // in which case, turn it into an array
4560
-            $values = explode(',', $values);
4561
-        }
4562
-        // make sure we only have one of each value in the list
4563
-        $values = array_unique($values);
4564
-        foreach ($values as $value) {
4565
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4566
-        }
4567
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4568
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4569
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4570
-        if (empty($prepped)) {
4571
-            $all_fields = $this->field_settings();
4572
-            $first_field    = reset($all_fields);
4573
-            $main_table = $this->_get_main_table();
4574
-            $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4575
-        }
4576
-        return '(' . implode(',', $prepped) . ')';
4577
-    }
4578
-
4579
-
4580
-
4581
-    /**
4582
-     * @param mixed                      $value
4583
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4584
-     * @throws EE_Error
4585
-     * @return false|null|string
4586
-     */
4587
-    private function _wpdb_prepare_using_field($value, $field_obj)
4588
-    {
4589
-        /** @type WPDB $wpdb */
4590
-        global $wpdb;
4591
-        if ($field_obj instanceof EE_Model_Field_Base) {
4592
-            return $wpdb->prepare(
4593
-                $field_obj->get_wpdb_data_type(),
4594
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4595
-            );
4596
-        } //$field_obj should really just be a data type
4597
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4598
-            throw new EE_Error(
4599
-                sprintf(
4600
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4601
-                    $field_obj,
4602
-                    implode(",", $this->_valid_wpdb_data_types)
4603
-                )
4604
-            );
4605
-        }
4606
-        return $wpdb->prepare($field_obj, $value);
4607
-    }
4608
-
4609
-
4610
-
4611
-    /**
4612
-     * Takes the input parameter and finds the model field that it indicates.
4613
-     *
4614
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4615
-     * @throws EE_Error
4616
-     * @return EE_Model_Field_Base
4617
-     */
4618
-    protected function _deduce_field_from_query_param($query_param_name)
4619
-    {
4620
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4621
-        // which will help us find the database table and column
4622
-        $query_param_parts = explode(".", $query_param_name);
4623
-        if (empty($query_param_parts)) {
4624
-            throw new EE_Error(sprintf(__(
4625
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4626
-                'event_espresso'
4627
-            ), $query_param_name));
4628
-        }
4629
-        $number_of_parts = count($query_param_parts);
4630
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4631
-        if ($number_of_parts === 1) {
4632
-            $field_name = $last_query_param_part;
4633
-            $model_obj = $this;
4634
-        } else {// $number_of_parts >= 2
4635
-            // the last part is the column name, and there are only 2parts. therefore...
4636
-            $field_name = $last_query_param_part;
4637
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4638
-        }
4639
-        try {
4640
-            return $model_obj->field_settings_for($field_name);
4641
-        } catch (EE_Error $e) {
4642
-            return null;
4643
-        }
4644
-    }
4645
-
4646
-
4647
-
4648
-    /**
4649
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4650
-     * alias and column which corresponds to it
4651
-     *
4652
-     * @param string $field_name
4653
-     * @throws EE_Error
4654
-     * @return string
4655
-     */
4656
-    public function _get_qualified_column_for_field($field_name)
4657
-    {
4658
-        $all_fields = $this->field_settings();
4659
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4660
-        if ($field) {
4661
-            return $field->get_qualified_column();
4662
-        }
4663
-        throw new EE_Error(
4664
-            sprintf(
4665
-                __(
4666
-                    "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.",
4667
-                    'event_espresso'
4668
-                ),
4669
-                $field_name,
4670
-                get_class($this)
4671
-            )
4672
-        );
4673
-    }
4674
-
4675
-
4676
-
4677
-    /**
4678
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4679
-     * Example usage:
4680
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4681
-     *      array(),
4682
-     *      ARRAY_A,
4683
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4684
-     *  );
4685
-     * is equivalent to
4686
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4687
-     * and
4688
-     *  EEM_Event::instance()->get_all_wpdb_results(
4689
-     *      array(
4690
-     *          array(
4691
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4692
-     *          ),
4693
-     *          ARRAY_A,
4694
-     *          implode(
4695
-     *              ', ',
4696
-     *              array_merge(
4697
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4698
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4699
-     *              )
4700
-     *          )
4701
-     *      )
4702
-     *  );
4703
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4704
-     *
4705
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4706
-     *                                            and the one whose fields you are selecting for example: when querying
4707
-     *                                            tickets model and selecting fields from the tickets model you would
4708
-     *                                            leave this parameter empty, because no models are needed to join
4709
-     *                                            between the queried model and the selected one. Likewise when
4710
-     *                                            querying the datetime model and selecting fields from the tickets
4711
-     *                                            model, it would also be left empty, because there is a direct
4712
-     *                                            relation from datetimes to tickets, so no model is needed to join
4713
-     *                                            them together. However, when querying from the event model and
4714
-     *                                            selecting fields from the ticket model, you should provide the string
4715
-     *                                            'Datetime', indicating that the event model must first join to the
4716
-     *                                            datetime model in order to find its relation to ticket model.
4717
-     *                                            Also, when querying from the venue model and selecting fields from
4718
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4719
-     *                                            indicating you need to join the venue model to the event model,
4720
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4721
-     *                                            This string is used to deduce the prefix that gets added onto the
4722
-     *                                            models' tables qualified columns
4723
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4724
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4725
-     *                                            qualified column names
4726
-     * @return array|string
4727
-     */
4728
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4729
-    {
4730
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4731
-        $qualified_columns = array();
4732
-        foreach ($this->field_settings() as $field_name => $field) {
4733
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4734
-        }
4735
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4736
-    }
4737
-
4738
-
4739
-
4740
-    /**
4741
-     * constructs the select use on special limit joins
4742
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4743
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4744
-     * (as that is typically where the limits would be set).
4745
-     *
4746
-     * @param  string       $table_alias The table the select is being built for
4747
-     * @param  mixed|string $limit       The limit for this select
4748
-     * @return string                The final select join element for the query.
4749
-     */
4750
-    public function _construct_limit_join_select($table_alias, $limit)
4751
-    {
4752
-        $SQL = '';
4753
-        foreach ($this->_tables as $table_obj) {
4754
-            if ($table_obj instanceof EE_Primary_Table) {
4755
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4756
-                    ? $table_obj->get_select_join_limit($limit)
4757
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4758
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4759
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4760
-                    ? $table_obj->get_select_join_limit_join($limit)
4761
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4762
-            }
4763
-        }
4764
-        return $SQL;
4765
-    }
4766
-
4767
-
4768
-
4769
-    /**
4770
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4771
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4772
-     *
4773
-     * @return string SQL
4774
-     * @throws EE_Error
4775
-     */
4776
-    public function _construct_internal_join()
4777
-    {
4778
-        $SQL = $this->_get_main_table()->get_table_sql();
4779
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4780
-        return $SQL;
4781
-    }
4782
-
4783
-
4784
-
4785
-    /**
4786
-     * Constructs the SQL for joining all the tables on this model.
4787
-     * Normally $alias should be the primary table's alias, but in cases where
4788
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4789
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4790
-     * alias, this will construct SQL like:
4791
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4792
-     * With $alias being a secondary table's alias, this will construct SQL like:
4793
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4794
-     *
4795
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4796
-     * @return string
4797
-     */
4798
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4799
-    {
4800
-        $SQL = '';
4801
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4802
-        foreach ($this->_tables as $table_obj) {
4803
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4804
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4805
-                    // so we're joining to this table, meaning the table is already in
4806
-                    // the FROM statement, BUT the primary table isn't. So we want
4807
-                    // to add the inverse join sql
4808
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4809
-                } else {
4810
-                    // just add a regular JOIN to this table from the primary table
4811
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4812
-                }
4813
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4814
-        }
4815
-        return $SQL;
4816
-    }
4817
-
4818
-
4819
-
4820
-    /**
4821
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4822
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4823
-     * their data type (eg, '%s', '%d', etc)
4824
-     *
4825
-     * @return array
4826
-     */
4827
-    public function _get_data_types()
4828
-    {
4829
-        $data_types = array();
4830
-        foreach ($this->field_settings() as $field_obj) {
4831
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4832
-            /** @var $field_obj EE_Model_Field_Base */
4833
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4834
-        }
4835
-        return $data_types;
4836
-    }
4837
-
4838
-
4839
-
4840
-    /**
4841
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4842
-     *
4843
-     * @param string $model_name
4844
-     * @throws EE_Error
4845
-     * @return EEM_Base
4846
-     */
4847
-    public function get_related_model_obj($model_name)
4848
-    {
4849
-        $model_classname = "EEM_" . $model_name;
4850
-        if (! class_exists($model_classname)) {
4851
-            throw new EE_Error(sprintf(__(
4852
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4853
-                'event_espresso'
4854
-            ), $model_name, $model_classname));
4855
-        }
4856
-        return call_user_func($model_classname . "::instance");
4857
-    }
4858
-
4859
-
4860
-
4861
-    /**
4862
-     * Returns the array of EE_ModelRelations for this model.
4863
-     *
4864
-     * @return EE_Model_Relation_Base[]
4865
-     */
4866
-    public function relation_settings()
4867
-    {
4868
-        return $this->_model_relations;
4869
-    }
4870
-
4871
-
4872
-
4873
-    /**
4874
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4875
-     * because without THOSE models, this model probably doesn't have much purpose.
4876
-     * (Eg, without an event, datetimes have little purpose.)
4877
-     *
4878
-     * @return EE_Belongs_To_Relation[]
4879
-     */
4880
-    public function belongs_to_relations()
4881
-    {
4882
-        $belongs_to_relations = array();
4883
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4884
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4885
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4886
-            }
4887
-        }
4888
-        return $belongs_to_relations;
4889
-    }
4890
-
4891
-
4892
-
4893
-    /**
4894
-     * Returns the specified EE_Model_Relation, or throws an exception
4895
-     *
4896
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4897
-     * @throws EE_Error
4898
-     * @return EE_Model_Relation_Base
4899
-     */
4900
-    public function related_settings_for($relation_name)
4901
-    {
4902
-        $relatedModels = $this->relation_settings();
4903
-        if (! array_key_exists($relation_name, $relatedModels)) {
4904
-            throw new EE_Error(
4905
-                sprintf(
4906
-                    __(
4907
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4908
-                        'event_espresso'
4909
-                    ),
4910
-                    $relation_name,
4911
-                    $this->_get_class_name(),
4912
-                    implode(', ', array_keys($relatedModels))
4913
-                )
4914
-            );
4915
-        }
4916
-        return $relatedModels[ $relation_name ];
4917
-    }
4918
-
4919
-
4920
-
4921
-    /**
4922
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4923
-     * fields
4924
-     *
4925
-     * @param string $fieldName
4926
-     * @param boolean $include_db_only_fields
4927
-     * @throws EE_Error
4928
-     * @return EE_Model_Field_Base
4929
-     */
4930
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4931
-    {
4932
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4933
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4934
-            throw new EE_Error(sprintf(
4935
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4936
-                $fieldName,
4937
-                get_class($this)
4938
-            ));
4939
-        }
4940
-        return $fieldSettings[ $fieldName ];
4941
-    }
4942
-
4943
-
4944
-
4945
-    /**
4946
-     * Checks if this field exists on this model
4947
-     *
4948
-     * @param string $fieldName a key in the model's _field_settings array
4949
-     * @return boolean
4950
-     */
4951
-    public function has_field($fieldName)
4952
-    {
4953
-        $fieldSettings = $this->field_settings(true);
4954
-        if (isset($fieldSettings[ $fieldName ])) {
4955
-            return true;
4956
-        }
4957
-        return false;
4958
-    }
4959
-
4960
-
4961
-
4962
-    /**
4963
-     * Returns whether or not this model has a relation to the specified model
4964
-     *
4965
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4966
-     * @return boolean
4967
-     */
4968
-    public function has_relation($relation_name)
4969
-    {
4970
-        $relations = $this->relation_settings();
4971
-        if (isset($relations[ $relation_name ])) {
4972
-            return true;
4973
-        }
4974
-        return false;
4975
-    }
4976
-
4977
-
4978
-
4979
-    /**
4980
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4981
-     * Eg, on EE_Answer that would be ANS_ID field object
4982
-     *
4983
-     * @param $field_obj
4984
-     * @return boolean
4985
-     */
4986
-    public function is_primary_key_field($field_obj)
4987
-    {
4988
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4989
-    }
4990
-
4991
-
4992
-
4993
-    /**
4994
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4995
-     * Eg, on EE_Answer that would be ANS_ID field object
4996
-     *
4997
-     * @return EE_Model_Field_Base
4998
-     * @throws EE_Error
4999
-     */
5000
-    public function get_primary_key_field()
5001
-    {
5002
-        if ($this->_primary_key_field === null) {
5003
-            foreach ($this->field_settings(true) as $field_obj) {
5004
-                if ($this->is_primary_key_field($field_obj)) {
5005
-                    $this->_primary_key_field = $field_obj;
5006
-                    break;
5007
-                }
5008
-            }
5009
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5010
-                throw new EE_Error(sprintf(
5011
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
5012
-                    get_class($this)
5013
-                ));
5014
-            }
5015
-        }
5016
-        return $this->_primary_key_field;
5017
-    }
5018
-
5019
-
5020
-
5021
-    /**
5022
-     * Returns whether or not not there is a primary key on this model.
5023
-     * Internally does some caching.
5024
-     *
5025
-     * @return boolean
5026
-     */
5027
-    public function has_primary_key_field()
5028
-    {
5029
-        if ($this->_has_primary_key_field === null) {
5030
-            try {
5031
-                $this->get_primary_key_field();
5032
-                $this->_has_primary_key_field = true;
5033
-            } catch (EE_Error $e) {
5034
-                $this->_has_primary_key_field = false;
5035
-            }
5036
-        }
5037
-        return $this->_has_primary_key_field;
5038
-    }
5039
-
5040
-
5041
-
5042
-    /**
5043
-     * Finds the first field of type $field_class_name.
5044
-     *
5045
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5046
-     *                                 EE_Foreign_Key_Field, etc
5047
-     * @return EE_Model_Field_Base or null if none is found
5048
-     */
5049
-    public function get_a_field_of_type($field_class_name)
5050
-    {
5051
-        foreach ($this->field_settings() as $field) {
5052
-            if ($field instanceof $field_class_name) {
5053
-                return $field;
5054
-            }
5055
-        }
5056
-        return null;
5057
-    }
5058
-
5059
-
5060
-
5061
-    /**
5062
-     * Gets a foreign key field pointing to model.
5063
-     *
5064
-     * @param string $model_name eg Event, Registration, not EEM_Event
5065
-     * @return EE_Foreign_Key_Field_Base
5066
-     * @throws EE_Error
5067
-     */
5068
-    public function get_foreign_key_to($model_name)
5069
-    {
5070
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5071
-            foreach ($this->field_settings() as $field) {
5072
-                if (
5073
-                    $field instanceof EE_Foreign_Key_Field_Base
5074
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5075
-                ) {
5076
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5077
-                    break;
5078
-                }
5079
-            }
5080
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5081
-                throw new EE_Error(sprintf(__(
5082
-                    "There is no foreign key field pointing to model %s on model %s",
5083
-                    'event_espresso'
5084
-                ), $model_name, get_class($this)));
5085
-            }
5086
-        }
5087
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5088
-    }
5089
-
5090
-
5091
-
5092
-    /**
5093
-     * Gets the table name (including $wpdb->prefix) for the table alias
5094
-     *
5095
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5096
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5097
-     *                            Either one works
5098
-     * @return string
5099
-     */
5100
-    public function get_table_for_alias($table_alias)
5101
-    {
5102
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5103
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5104
-    }
5105
-
5106
-
5107
-
5108
-    /**
5109
-     * Returns a flat array of all field son this model, instead of organizing them
5110
-     * by table_alias as they are in the constructor.
5111
-     *
5112
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5113
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5114
-     */
5115
-    public function field_settings($include_db_only_fields = false)
5116
-    {
5117
-        if ($include_db_only_fields) {
5118
-            if ($this->_cached_fields === null) {
5119
-                $this->_cached_fields = array();
5120
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5121
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5122
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5123
-                    }
5124
-                }
5125
-            }
5126
-            return $this->_cached_fields;
5127
-        }
5128
-        if ($this->_cached_fields_non_db_only === null) {
5129
-            $this->_cached_fields_non_db_only = array();
5130
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5131
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5132
-                    /** @var $field_obj EE_Model_Field_Base */
5133
-                    if (! $field_obj->is_db_only_field()) {
5134
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5135
-                    }
5136
-                }
5137
-            }
5138
-        }
5139
-        return $this->_cached_fields_non_db_only;
5140
-    }
5141
-
5142
-
5143
-
5144
-    /**
5145
-     *        cycle though array of attendees and create objects out of each item
5146
-     *
5147
-     * @access        private
5148
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5149
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5150
-     *                           numerically indexed)
5151
-     * @throws EE_Error
5152
-     */
5153
-    protected function _create_objects($rows = array())
5154
-    {
5155
-        $array_of_objects = array();
5156
-        if (empty($rows)) {
5157
-            return array();
5158
-        }
5159
-        $count_if_model_has_no_primary_key = 0;
5160
-        $has_primary_key = $this->has_primary_key_field();
5161
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5162
-        foreach ((array) $rows as $row) {
5163
-            if (empty($row)) {
5164
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5165
-                return array();
5166
-            }
5167
-            // check if we've already set this object in the results array,
5168
-            // in which case there's no need to process it further (again)
5169
-            if ($has_primary_key) {
5170
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5171
-                    $row,
5172
-                    $primary_key_field->get_qualified_column(),
5173
-                    $primary_key_field->get_table_column()
5174
-                );
5175
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5176
-                    continue;
5177
-                }
5178
-            }
5179
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5180
-            if (! $classInstance) {
5181
-                throw new EE_Error(
5182
-                    sprintf(
5183
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5184
-                        $this->get_this_model_name(),
5185
-                        http_build_query($row)
5186
-                    )
5187
-                );
5188
-            }
5189
-            // set the timezone on the instantiated objects
5190
-            $classInstance->set_timezone($this->_timezone);
5191
-            // make sure if there is any timezone setting present that we set the timezone for the object
5192
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5193
-            $array_of_objects[ $key ] = $classInstance;
5194
-            // also, for all the relations of type BelongsTo, see if we can cache
5195
-            // those related models
5196
-            // (we could do this for other relations too, but if there are conditions
5197
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5198
-            // so it requires a little more thought than just caching them immediately...)
5199
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5200
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5201
-                    // check if this model's INFO is present. If so, cache it on the model
5202
-                    $other_model = $relation_obj->get_other_model();
5203
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5204
-                    // if we managed to make a model object from the results, cache it on the main model object
5205
-                    if ($other_model_obj_maybe) {
5206
-                        // set timezone on these other model objects if they are present
5207
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5208
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5209
-                    }
5210
-                }
5211
-            }
5212
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5213
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5214
-            // the field in the CustomSelects object
5215
-            if ($this->_custom_selections instanceof CustomSelects) {
5216
-                $classInstance->setCustomSelectsValues(
5217
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5218
-                );
5219
-            }
5220
-        }
5221
-        return $array_of_objects;
5222
-    }
5223
-
5224
-
5225
-    /**
5226
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5227
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5228
-     *
5229
-     * @param array $db_results_row
5230
-     * @return array
5231
-     */
5232
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5233
-    {
5234
-        $results = array();
5235
-        if ($this->_custom_selections instanceof CustomSelects) {
5236
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5237
-                if (isset($db_results_row[ $alias ])) {
5238
-                    $results[ $alias ] = $this->convertValueToDataType(
5239
-                        $db_results_row[ $alias ],
5240
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5241
-                    );
5242
-                }
5243
-            }
5244
-        }
5245
-        return $results;
5246
-    }
5247
-
5248
-
5249
-    /**
5250
-     * This will set the value for the given alias
5251
-     * @param string $value
5252
-     * @param string $datatype (one of %d, %s, %f)
5253
-     * @return int|string|float (int for %d, string for %s, float for %f)
5254
-     */
5255
-    protected function convertValueToDataType($value, $datatype)
5256
-    {
5257
-        switch ($datatype) {
5258
-            case '%f':
5259
-                return (float) $value;
5260
-            case '%d':
5261
-                return (int) $value;
5262
-            default:
5263
-                return (string) $value;
5264
-        }
5265
-    }
5266
-
5267
-
5268
-    /**
5269
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5270
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5271
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5272
-     * object (as set in the model_field!).
5273
-     *
5274
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5275
-     */
5276
-    public function create_default_object()
5277
-    {
5278
-        $this_model_fields_and_values = array();
5279
-        // setup the row using default values;
5280
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5281
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5282
-        }
5283
-        $className = $this->_get_class_name();
5284
-        $classInstance = EE_Registry::instance()
5285
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5286
-        return $classInstance;
5287
-    }
5288
-
5289
-
5290
-
5291
-    /**
5292
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5293
-     *                             or an stdClass where each property is the name of a column,
5294
-     * @return EE_Base_Class
5295
-     * @throws EE_Error
5296
-     */
5297
-    public function instantiate_class_from_array_or_object($cols_n_values)
5298
-    {
5299
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5300
-            $cols_n_values = get_object_vars($cols_n_values);
5301
-        }
5302
-        $primary_key = null;
5303
-        // make sure the array only has keys that are fields/columns on this model
5304
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5305
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5306
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5307
-        }
5308
-        $className = $this->_get_class_name();
5309
-        // check we actually found results that we can use to build our model object
5310
-        // if not, return null
5311
-        if ($this->has_primary_key_field()) {
5312
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5313
-                return null;
5314
-            }
5315
-        } elseif ($this->unique_indexes()) {
5316
-            $first_column = reset($this_model_fields_n_values);
5317
-            if (empty($first_column)) {
5318
-                return null;
5319
-            }
5320
-        }
5321
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5322
-        if ($primary_key) {
5323
-            $classInstance = $this->get_from_entity_map($primary_key);
5324
-            if (! $classInstance) {
5325
-                $classInstance = EE_Registry::instance()
5326
-                                            ->load_class(
5327
-                                                $className,
5328
-                                                array($this_model_fields_n_values, $this->_timezone),
5329
-                                                true,
5330
-                                                false
5331
-                                            );
5332
-                // add this new object to the entity map
5333
-                $classInstance = $this->add_to_entity_map($classInstance);
5334
-            }
5335
-        } else {
5336
-            $classInstance = EE_Registry::instance()
5337
-                                        ->load_class(
5338
-                                            $className,
5339
-                                            array($this_model_fields_n_values, $this->_timezone),
5340
-                                            true,
5341
-                                            false
5342
-                                        );
5343
-        }
5344
-        return $classInstance;
5345
-    }
5346
-
5347
-
5348
-
5349
-    /**
5350
-     * Gets the model object from the  entity map if it exists
5351
-     *
5352
-     * @param int|string $id the ID of the model object
5353
-     * @return EE_Base_Class
5354
-     */
5355
-    public function get_from_entity_map($id)
5356
-    {
5357
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5358
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5359
-    }
5360
-
5361
-
5362
-
5363
-    /**
5364
-     * add_to_entity_map
5365
-     * Adds the object to the model's entity mappings
5366
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5367
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5368
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5369
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5370
-     *        then this method should be called immediately after the update query
5371
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5372
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5373
-     *
5374
-     * @param    EE_Base_Class $object
5375
-     * @throws EE_Error
5376
-     * @return \EE_Base_Class
5377
-     */
5378
-    public function add_to_entity_map(EE_Base_Class $object)
5379
-    {
5380
-        $className = $this->_get_class_name();
5381
-        if (! $object instanceof $className) {
5382
-            throw new EE_Error(sprintf(
5383
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5384
-                is_object($object) ? get_class($object) : $object,
5385
-                $className
5386
-            ));
5387
-        }
5388
-        /** @var $object EE_Base_Class */
5389
-        if (! $object->ID()) {
5390
-            throw new EE_Error(sprintf(__(
5391
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5392
-                "event_espresso"
5393
-            ), get_class($this)));
5394
-        }
5395
-        // double check it's not already there
5396
-        $classInstance = $this->get_from_entity_map($object->ID());
5397
-        if ($classInstance) {
5398
-            return $classInstance;
5399
-        }
5400
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5401
-        return $object;
5402
-    }
5403
-
5404
-
5405
-
5406
-    /**
5407
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5408
-     * if no identifier is provided, then the entire entity map is emptied
5409
-     *
5410
-     * @param int|string $id the ID of the model object
5411
-     * @return boolean
5412
-     */
5413
-    public function clear_entity_map($id = null)
5414
-    {
5415
-        if (empty($id)) {
5416
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5417
-            return true;
5418
-        }
5419
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5420
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5421
-            return true;
5422
-        }
5423
-        return false;
5424
-    }
5425
-
5426
-
5427
-
5428
-    /**
5429
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5430
-     * Given an array where keys are column (or column alias) names and values,
5431
-     * returns an array of their corresponding field names and database values
5432
-     *
5433
-     * @param array $cols_n_values
5434
-     * @return array
5435
-     */
5436
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5437
-    {
5438
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5439
-    }
5440
-
5441
-
5442
-
5443
-    /**
5444
-     * _deduce_fields_n_values_from_cols_n_values
5445
-     * Given an array where keys are column (or column alias) names and values,
5446
-     * returns an array of their corresponding field names and database values
5447
-     *
5448
-     * @param string $cols_n_values
5449
-     * @return array
5450
-     */
5451
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5452
-    {
5453
-        $this_model_fields_n_values = array();
5454
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5455
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5456
-                $cols_n_values,
5457
-                $table_obj->get_fully_qualified_pk_column(),
5458
-                $table_obj->get_pk_column()
5459
-            );
5460
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5461
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5462
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5463
-                    if (! $field_obj->is_db_only_field()) {
5464
-                        // prepare field as if its coming from db
5465
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5466
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5467
-                    }
5468
-                }
5469
-            } else {
5470
-                // the table's rows existed. Use their values
5471
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5472
-                    if (! $field_obj->is_db_only_field()) {
5473
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5474
-                            $cols_n_values,
5475
-                            $field_obj->get_qualified_column(),
5476
-                            $field_obj->get_table_column()
5477
-                        );
5478
-                    }
5479
-                }
5480
-            }
5481
-        }
5482
-        return $this_model_fields_n_values;
5483
-    }
5484
-
5485
-
5486
-    /**
5487
-     * @param $cols_n_values
5488
-     * @param $qualified_column
5489
-     * @param $regular_column
5490
-     * @return null
5491
-     * @throws EE_Error
5492
-     * @throws ReflectionException
5493
-     */
5494
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5495
-    {
5496
-        $value = null;
5497
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5498
-        // does the field on the model relate to this column retrieved from the db?
5499
-        // or is it a db-only field? (not relating to the model)
5500
-        if (isset($cols_n_values[ $qualified_column ])) {
5501
-            $value = $cols_n_values[ $qualified_column ];
5502
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5503
-            $value = $cols_n_values[ $regular_column ];
5504
-        } elseif (! empty($this->foreign_key_aliases)) {
5505
-            // no PK?  ok check if there is a foreign key alias set for this table
5506
-            // then check if that alias exists in the incoming data
5507
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5508
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5509
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5510
-                    $value = $cols_n_values[ $FK_alias ];
5511
-                    [$pk_class] = explode('.', $PK_column);
5512
-                    $pk_model_name = "EEM_{$pk_class}";
5513
-                    /** @var EEM_Base $pk_model */
5514
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5515
-                    if ($pk_model instanceof EEM_Base) {
5516
-                        // make sure object is pulled from db and added to entity map
5517
-                        $pk_model->get_one_by_ID($value);
5518
-                    }
5519
-                    break;
5520
-                }
5521
-            }
5522
-        }
5523
-        return $value;
5524
-    }
5525
-
5526
-
5527
-
5528
-    /**
5529
-     * refresh_entity_map_from_db
5530
-     * Makes sure the model object in the entity map at $id assumes the values
5531
-     * of the database (opposite of EE_base_Class::save())
5532
-     *
5533
-     * @param int|string $id
5534
-     * @return EE_Base_Class
5535
-     * @throws EE_Error
5536
-     */
5537
-    public function refresh_entity_map_from_db($id)
5538
-    {
5539
-        $obj_in_map = $this->get_from_entity_map($id);
5540
-        if ($obj_in_map) {
5541
-            $wpdb_results = $this->_get_all_wpdb_results(
5542
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5543
-            );
5544
-            if ($wpdb_results && is_array($wpdb_results)) {
5545
-                $one_row = reset($wpdb_results);
5546
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5547
-                    $obj_in_map->set_from_db($field_name, $db_value);
5548
-                }
5549
-                // clear the cache of related model objects
5550
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5551
-                    $obj_in_map->clear_cache($relation_name, null, true);
5552
-                }
5553
-            }
5554
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5555
-            return $obj_in_map;
5556
-        }
5557
-        return $this->get_one_by_ID($id);
5558
-    }
5559
-
5560
-
5561
-
5562
-    /**
5563
-     * refresh_entity_map_with
5564
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5565
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5566
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5567
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5568
-     *
5569
-     * @param int|string    $id
5570
-     * @param EE_Base_Class $replacing_model_obj
5571
-     * @return \EE_Base_Class
5572
-     * @throws EE_Error
5573
-     */
5574
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5575
-    {
5576
-        $obj_in_map = $this->get_from_entity_map($id);
5577
-        if ($obj_in_map) {
5578
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5579
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5580
-                    $obj_in_map->set($field_name, $value);
5581
-                }
5582
-                // make the model object in the entity map's cache match the $replacing_model_obj
5583
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5584
-                    $obj_in_map->clear_cache($relation_name, null, true);
5585
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5586
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5587
-                    }
5588
-                }
5589
-            }
5590
-            return $obj_in_map;
5591
-        }
5592
-        $this->add_to_entity_map($replacing_model_obj);
5593
-        return $replacing_model_obj;
5594
-    }
5595
-
5596
-
5597
-
5598
-    /**
5599
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5600
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5601
-     * require_once($this->_getClassName().".class.php");
5602
-     *
5603
-     * @return string
5604
-     */
5605
-    private function _get_class_name()
5606
-    {
5607
-        return "EE_" . $this->get_this_model_name();
5608
-    }
5609
-
5610
-
5611
-
5612
-    /**
5613
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5614
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5615
-     * it would be 'Events'.
5616
-     *
5617
-     * @param int $quantity
5618
-     * @return string
5619
-     */
5620
-    public function item_name($quantity = 1)
5621
-    {
5622
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5623
-    }
5624
-
5625
-
5626
-
5627
-    /**
5628
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5629
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5630
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5631
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5632
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5633
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5634
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5635
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5636
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5637
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5638
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5639
-     *        return $previousReturnValue.$returnString;
5640
-     * }
5641
-     * require('EEM_Answer.model.php');
5642
-     * $answer=EEM_Answer::instance();
5643
-     * echo $answer->my_callback('monkeys',100);
5644
-     * //will output "you called my_callback! and passed args:monkeys,100"
5645
-     *
5646
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5647
-     * @param array  $args       array of original arguments passed to the function
5648
-     * @throws EE_Error
5649
-     * @return mixed whatever the plugin which calls add_filter decides
5650
-     */
5651
-    public function __call($methodName, $args)
5652
-    {
5653
-        $className = get_class($this);
5654
-        $tagName = "FHEE__{$className}__{$methodName}";
5655
-        if (! has_filter($tagName)) {
5656
-            throw new EE_Error(
5657
-                sprintf(
5658
-                    __(
5659
-                        '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 );',
5660
-                        'event_espresso'
5661
-                    ),
5662
-                    $methodName,
5663
-                    $className,
5664
-                    $tagName,
5665
-                    '<br />'
5666
-                )
5667
-            );
5668
-        }
5669
-        return apply_filters($tagName, null, $this, $args);
5670
-    }
5671
-
5672
-
5673
-
5674
-    /**
5675
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5676
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5677
-     *
5678
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5679
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5680
-     *                                                       the object's class name
5681
-     *                                                       or object's ID
5682
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5683
-     *                                                       exists in the database. If it does not, we add it
5684
-     * @throws EE_Error
5685
-     * @return EE_Base_Class
5686
-     */
5687
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5688
-    {
5689
-        $className = $this->_get_class_name();
5690
-        if ($base_class_obj_or_id instanceof $className) {
5691
-            $model_object = $base_class_obj_or_id;
5692
-        } else {
5693
-            $primary_key_field = $this->get_primary_key_field();
5694
-            if (
5695
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5696
-                && (
5697
-                    is_int($base_class_obj_or_id)
5698
-                    || is_string($base_class_obj_or_id)
5699
-                )
5700
-            ) {
5701
-                // assume it's an ID.
5702
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5703
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5704
-            } elseif (
5705
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5706
-                && is_string($base_class_obj_or_id)
5707
-            ) {
5708
-                // assume its a string representation of the object
5709
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5710
-            } else {
5711
-                throw new EE_Error(
5712
-                    sprintf(
5713
-                        __(
5714
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5715
-                            'event_espresso'
5716
-                        ),
5717
-                        $base_class_obj_or_id,
5718
-                        $this->_get_class_name(),
5719
-                        print_r($base_class_obj_or_id, true)
5720
-                    )
5721
-                );
5722
-            }
5723
-        }
5724
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5725
-            $model_object->save();
5726
-        }
5727
-        return $model_object;
5728
-    }
5729
-
5730
-
5731
-
5732
-    /**
5733
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5734
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5735
-     * returns it ID.
5736
-     *
5737
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5738
-     * @return int|string depending on the type of this model object's ID
5739
-     * @throws EE_Error
5740
-     */
5741
-    public function ensure_is_ID($base_class_obj_or_id)
5742
-    {
5743
-        $className = $this->_get_class_name();
5744
-        if ($base_class_obj_or_id instanceof $className) {
5745
-            /** @var $base_class_obj_or_id EE_Base_Class */
5746
-            $id = $base_class_obj_or_id->ID();
5747
-        } elseif (is_int($base_class_obj_or_id)) {
5748
-            // assume it's an ID
5749
-            $id = $base_class_obj_or_id;
5750
-        } elseif (is_string($base_class_obj_or_id)) {
5751
-            // assume its a string representation of the object
5752
-            $id = $base_class_obj_or_id;
5753
-        } else {
5754
-            throw new EE_Error(sprintf(
5755
-                __(
5756
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5757
-                    'event_espresso'
5758
-                ),
5759
-                $base_class_obj_or_id,
5760
-                $this->_get_class_name(),
5761
-                print_r($base_class_obj_or_id, true)
5762
-            ));
5763
-        }
5764
-        return $id;
5765
-    }
5766
-
5767
-
5768
-
5769
-    /**
5770
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5771
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5772
-     * been sanitized and converted into the appropriate domain.
5773
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5774
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5775
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5776
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5777
-     * $EVT = EEM_Event::instance(); $old_setting =
5778
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5779
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5780
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5781
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5782
-     *
5783
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5784
-     * @return void
5785
-     */
5786
-    public function assume_values_already_prepared_by_model_object(
5787
-        $values_already_prepared = self::not_prepared_by_model_object
5788
-    ) {
5789
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5790
-    }
5791
-
5792
-
5793
-
5794
-    /**
5795
-     * Read comments for assume_values_already_prepared_by_model_object()
5796
-     *
5797
-     * @return int
5798
-     */
5799
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5800
-    {
5801
-        return $this->_values_already_prepared_by_model_object;
5802
-    }
5803
-
5804
-
5805
-
5806
-    /**
5807
-     * Gets all the indexes on this model
5808
-     *
5809
-     * @return EE_Index[]
5810
-     */
5811
-    public function indexes()
5812
-    {
5813
-        return $this->_indexes;
5814
-    }
5815
-
5816
-
5817
-
5818
-    /**
5819
-     * Gets all the Unique Indexes on this model
5820
-     *
5821
-     * @return EE_Unique_Index[]
5822
-     */
5823
-    public function unique_indexes()
5824
-    {
5825
-        $unique_indexes = array();
5826
-        foreach ($this->_indexes as $name => $index) {
5827
-            if ($index instanceof EE_Unique_Index) {
5828
-                $unique_indexes [ $name ] = $index;
5829
-            }
5830
-        }
5831
-        return $unique_indexes;
5832
-    }
5833
-
5834
-
5835
-
5836
-    /**
5837
-     * Gets all the fields which, when combined, make the primary key.
5838
-     * This is usually just an array with 1 element (the primary key), but in cases
5839
-     * where there is no primary key, it's a combination of fields as defined
5840
-     * on a primary index
5841
-     *
5842
-     * @return EE_Model_Field_Base[] indexed by the field's name
5843
-     * @throws EE_Error
5844
-     */
5845
-    public function get_combined_primary_key_fields()
5846
-    {
5847
-        foreach ($this->indexes() as $index) {
5848
-            if ($index instanceof EE_Primary_Key_Index) {
5849
-                return $index->fields();
5850
-            }
5851
-        }
5852
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5853
-    }
5854
-
5855
-
5856
-
5857
-    /**
5858
-     * Used to build a primary key string (when the model has no primary key),
5859
-     * which can be used a unique string to identify this model object.
5860
-     *
5861
-     * @param array $fields_n_values keys are field names, values are their values.
5862
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5863
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5864
-     *                               before passing it to this function (that will convert it from columns-n-values
5865
-     *                               to field-names-n-values).
5866
-     * @return string
5867
-     * @throws EE_Error
5868
-     */
5869
-    public function get_index_primary_key_string($fields_n_values)
5870
-    {
5871
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5872
-            $fields_n_values,
5873
-            $this->get_combined_primary_key_fields()
5874
-        );
5875
-        return http_build_query($cols_n_values_for_primary_key_index);
5876
-    }
5877
-
5878
-
5879
-
5880
-    /**
5881
-     * Gets the field values from the primary key string
5882
-     *
5883
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5884
-     * @param string $index_primary_key_string
5885
-     * @return null|array
5886
-     * @throws EE_Error
5887
-     */
5888
-    public function parse_index_primary_key_string($index_primary_key_string)
5889
-    {
5890
-        $key_fields = $this->get_combined_primary_key_fields();
5891
-        // check all of them are in the $id
5892
-        $key_vals_in_combined_pk = array();
5893
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5894
-        foreach ($key_fields as $key_field_name => $field_obj) {
5895
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5896
-                return null;
5897
-            }
5898
-        }
5899
-        return $key_vals_in_combined_pk;
5900
-    }
5901
-
5902
-
5903
-
5904
-    /**
5905
-     * verifies that an array of key-value pairs for model fields has a key
5906
-     * for each field comprising the primary key index
5907
-     *
5908
-     * @param array $key_vals
5909
-     * @return boolean
5910
-     * @throws EE_Error
5911
-     */
5912
-    public function has_all_combined_primary_key_fields($key_vals)
5913
-    {
5914
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5915
-        foreach ($keys_it_should_have as $key) {
5916
-            if (! isset($key_vals[ $key ])) {
5917
-                return false;
5918
-            }
5919
-        }
5920
-        return true;
5921
-    }
5922
-
5923
-
5924
-
5925
-    /**
5926
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5927
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5928
-     *
5929
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5930
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5931
-     * @throws EE_Error
5932
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5933
-     *                                                              indexed)
5934
-     */
5935
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5936
-    {
5937
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5938
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5939
-        } elseif (is_array($model_object_or_attributes_array)) {
5940
-            $attributes_array = $model_object_or_attributes_array;
5941
-        } else {
5942
-            throw new EE_Error(sprintf(__(
5943
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5944
-                "event_espresso"
5945
-            ), $model_object_or_attributes_array));
5946
-        }
5947
-        // even copies obviously won't have the same ID, so remove the primary key
5948
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5949
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5950
-            unset($attributes_array[ $this->primary_key_name() ]);
5951
-        }
5952
-        if (isset($query_params[0])) {
5953
-            $query_params[0] = array_merge($attributes_array, $query_params);
5954
-        } else {
5955
-            $query_params[0] = $attributes_array;
5956
-        }
5957
-        return $this->get_all($query_params);
5958
-    }
5959
-
5960
-
5961
-
5962
-    /**
5963
-     * Gets the first copy we find. See get_all_copies for more details
5964
-     *
5965
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5966
-     * @param array $query_params
5967
-     * @return EE_Base_Class
5968
-     * @throws EE_Error
5969
-     */
5970
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5971
-    {
5972
-        if (! is_array($query_params)) {
5973
-            EE_Error::doing_it_wrong(
5974
-                'EEM_Base::get_one_copy',
5975
-                sprintf(
5976
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5977
-                    gettype($query_params)
5978
-                ),
5979
-                '4.6.0'
5980
-            );
5981
-            $query_params = array();
5982
-        }
5983
-        $query_params['limit'] = 1;
5984
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5985
-        if (is_array($copies)) {
5986
-            return array_shift($copies);
5987
-        }
5988
-        return null;
5989
-    }
5990
-
5991
-
5992
-
5993
-    /**
5994
-     * Updates the item with the specified id. Ignores default query parameters because
5995
-     * we have specified the ID, and its assumed we KNOW what we're doing
5996
-     *
5997
-     * @param array      $fields_n_values keys are field names, values are their new values
5998
-     * @param int|string $id              the value of the primary key to update
5999
-     * @return int number of rows updated
6000
-     * @throws EE_Error
6001
-     */
6002
-    public function update_by_ID($fields_n_values, $id)
6003
-    {
6004
-        $query_params = array(
6005
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
6006
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6007
-        );
6008
-        return $this->update($fields_n_values, $query_params);
6009
-    }
6010
-
6011
-
6012
-
6013
-    /**
6014
-     * Changes an operator which was supplied to the models into one usable in SQL
6015
-     *
6016
-     * @param string $operator_supplied
6017
-     * @return string an operator which can be used in SQL
6018
-     * @throws EE_Error
6019
-     */
6020
-    private function _prepare_operator_for_sql($operator_supplied)
6021
-    {
6022
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6023
-            : null;
6024
-        if ($sql_operator) {
6025
-            return $sql_operator;
6026
-        }
6027
-        throw new EE_Error(
6028
-            sprintf(
6029
-                __(
6030
-                    "The operator '%s' is not in the list of valid operators: %s",
6031
-                    "event_espresso"
6032
-                ),
6033
-                $operator_supplied,
6034
-                implode(",", array_keys($this->_valid_operators))
6035
-            )
6036
-        );
6037
-    }
6038
-
6039
-
6040
-
6041
-    /**
6042
-     * Gets the valid operators
6043
-     * @return array keys are accepted strings, values are the SQL they are converted to
6044
-     */
6045
-    public function valid_operators()
6046
-    {
6047
-        return $this->_valid_operators;
6048
-    }
6049
-
6050
-
6051
-
6052
-    /**
6053
-     * Gets the between-style operators (take 2 arguments).
6054
-     * @return array keys are accepted strings, values are the SQL they are converted to
6055
-     */
6056
-    public function valid_between_style_operators()
6057
-    {
6058
-        return array_intersect(
6059
-            $this->valid_operators(),
6060
-            $this->_between_style_operators
6061
-        );
6062
-    }
6063
-
6064
-    /**
6065
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6066
-     * @return array keys are accepted strings, values are the SQL they are converted to
6067
-     */
6068
-    public function valid_like_style_operators()
6069
-    {
6070
-        return array_intersect(
6071
-            $this->valid_operators(),
6072
-            $this->_like_style_operators
6073
-        );
6074
-    }
6075
-
6076
-    /**
6077
-     * Gets the "in"-style operators
6078
-     * @return array keys are accepted strings, values are the SQL they are converted to
6079
-     */
6080
-    public function valid_in_style_operators()
6081
-    {
6082
-        return array_intersect(
6083
-            $this->valid_operators(),
6084
-            $this->_in_style_operators
6085
-        );
6086
-    }
6087
-
6088
-    /**
6089
-     * Gets the "null"-style operators (accept no arguments)
6090
-     * @return array keys are accepted strings, values are the SQL they are converted to
6091
-     */
6092
-    public function valid_null_style_operators()
6093
-    {
6094
-        return array_intersect(
6095
-            $this->valid_operators(),
6096
-            $this->_null_style_operators
6097
-        );
6098
-    }
6099
-
6100
-    /**
6101
-     * Gets an array where keys are the primary keys and values are their 'names'
6102
-     * (as determined by the model object's name() function, which is often overridden)
6103
-     *
6104
-     * @param array $query_params like get_all's
6105
-     * @return string[]
6106
-     * @throws EE_Error
6107
-     */
6108
-    public function get_all_names($query_params = array())
6109
-    {
6110
-        $objs = $this->get_all($query_params);
6111
-        $names = array();
6112
-        foreach ($objs as $obj) {
6113
-            $names[ $obj->ID() ] = $obj->name();
6114
-        }
6115
-        return $names;
6116
-    }
6117
-
6118
-
6119
-
6120
-    /**
6121
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6122
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6123
-     * this is duplicated effort and reduces efficiency) you would be better to use
6124
-     * array_keys() on $model_objects.
6125
-     *
6126
-     * @param \EE_Base_Class[] $model_objects
6127
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6128
-     *                                               in the returned array
6129
-     * @return array
6130
-     * @throws EE_Error
6131
-     */
6132
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6133
-    {
6134
-        if (! $this->has_primary_key_field()) {
6135
-            if (WP_DEBUG) {
6136
-                EE_Error::add_error(
6137
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6138
-                    __FILE__,
6139
-                    __FUNCTION__,
6140
-                    __LINE__
6141
-                );
6142
-            }
6143
-        }
6144
-        $IDs = array();
6145
-        foreach ($model_objects as $model_object) {
6146
-            $id = $model_object->ID();
6147
-            if (! $id) {
6148
-                if ($filter_out_empty_ids) {
6149
-                    continue;
6150
-                }
6151
-                if (WP_DEBUG) {
6152
-                    EE_Error::add_error(
6153
-                        __(
6154
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6155
-                            'event_espresso'
6156
-                        ),
6157
-                        __FILE__,
6158
-                        __FUNCTION__,
6159
-                        __LINE__
6160
-                    );
6161
-                }
6162
-            }
6163
-            $IDs[] = $id;
6164
-        }
6165
-        return $IDs;
6166
-    }
6167
-
6168
-
6169
-
6170
-    /**
6171
-     * Returns the string used in capabilities relating to this model. If there
6172
-     * are no capabilities that relate to this model returns false
6173
-     *
6174
-     * @return string|false
6175
-     */
6176
-    public function cap_slug()
6177
-    {
6178
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6179
-    }
6180
-
6181
-
6182
-
6183
-    /**
6184
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6185
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6186
-     * only returns the cap restrictions array in that context (ie, the array
6187
-     * at that key)
6188
-     *
6189
-     * @param string $context
6190
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6191
-     * @throws EE_Error
6192
-     */
6193
-    public function cap_restrictions($context = EEM_Base::caps_read)
6194
-    {
6195
-        EEM_Base::verify_is_valid_cap_context($context);
6196
-        // check if we ought to run the restriction generator first
6197
-        if (
6198
-            isset($this->_cap_restriction_generators[ $context ])
6199
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6200
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6201
-        ) {
6202
-            $this->_cap_restrictions[ $context ] = array_merge(
6203
-                $this->_cap_restrictions[ $context ],
6204
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6205
-            );
6206
-        }
6207
-        // and make sure we've finalized the construction of each restriction
6208
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6209
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6210
-                $where_conditions_obj->_finalize_construct($this);
6211
-            }
6212
-        }
6213
-        return $this->_cap_restrictions[ $context ];
6214
-    }
6215
-
6216
-
6217
-
6218
-    /**
6219
-     * Indicating whether or not this model thinks its a wp core model
6220
-     *
6221
-     * @return boolean
6222
-     */
6223
-    public function is_wp_core_model()
6224
-    {
6225
-        return $this->_wp_core_model;
6226
-    }
6227
-
6228
-
6229
-
6230
-    /**
6231
-     * Gets all the caps that are missing which impose a restriction on
6232
-     * queries made in this context
6233
-     *
6234
-     * @param string $context one of EEM_Base::caps_ constants
6235
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6236
-     * @throws EE_Error
6237
-     */
6238
-    public function caps_missing($context = EEM_Base::caps_read)
6239
-    {
6240
-        $missing_caps = array();
6241
-        $cap_restrictions = $this->cap_restrictions($context);
6242
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6243
-            if (
6244
-                ! EE_Capabilities::instance()
6245
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6246
-            ) {
6247
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6248
-            }
6249
-        }
6250
-        return $missing_caps;
6251
-    }
6252
-
6253
-
6254
-
6255
-    /**
6256
-     * Gets the mapping from capability contexts to action strings used in capability names
6257
-     *
6258
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6259
-     * one of 'read', 'edit', or 'delete'
6260
-     */
6261
-    public function cap_contexts_to_cap_action_map()
6262
-    {
6263
-        return apply_filters(
6264
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6265
-            $this->_cap_contexts_to_cap_action_map,
6266
-            $this
6267
-        );
6268
-    }
6269
-
6270
-
6271
-
6272
-    /**
6273
-     * Gets the action string for the specified capability context
6274
-     *
6275
-     * @param string $context
6276
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6277
-     * @throws EE_Error
6278
-     */
6279
-    public function cap_action_for_context($context)
6280
-    {
6281
-        $mapping = $this->cap_contexts_to_cap_action_map();
6282
-        if (isset($mapping[ $context ])) {
6283
-            return $mapping[ $context ];
6284
-        }
6285
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6286
-            return $action;
6287
-        }
6288
-        throw new EE_Error(
6289
-            sprintf(
6290
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6291
-                $context,
6292
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6293
-            )
6294
-        );
6295
-    }
6296
-
6297
-
6298
-
6299
-    /**
6300
-     * Returns all the capability contexts which are valid when querying models
6301
-     *
6302
-     * @return array
6303
-     */
6304
-    public static function valid_cap_contexts()
6305
-    {
6306
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6307
-            self::caps_read,
6308
-            self::caps_read_admin,
6309
-            self::caps_edit,
6310
-            self::caps_delete,
6311
-        ));
6312
-    }
6313
-
6314
-
6315
-
6316
-    /**
6317
-     * Returns all valid options for 'default_where_conditions'
6318
-     *
6319
-     * @return array
6320
-     */
6321
-    public static function valid_default_where_conditions()
6322
-    {
6323
-        return array(
6324
-            EEM_Base::default_where_conditions_all,
6325
-            EEM_Base::default_where_conditions_this_only,
6326
-            EEM_Base::default_where_conditions_others_only,
6327
-            EEM_Base::default_where_conditions_minimum_all,
6328
-            EEM_Base::default_where_conditions_minimum_others,
6329
-            EEM_Base::default_where_conditions_none
6330
-        );
6331
-    }
6332
-
6333
-    // public static function default_where_conditions_full
6334
-    /**
6335
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6336
-     *
6337
-     * @param string $context
6338
-     * @return bool
6339
-     * @throws EE_Error
6340
-     */
6341
-    public static function verify_is_valid_cap_context($context)
6342
-    {
6343
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6344
-        if (in_array($context, $valid_cap_contexts)) {
6345
-            return true;
6346
-        }
6347
-        throw new EE_Error(
6348
-            sprintf(
6349
-                __(
6350
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6351
-                    'event_espresso'
6352
-                ),
6353
-                $context,
6354
-                'EEM_Base',
6355
-                implode(',', $valid_cap_contexts)
6356
-            )
6357
-        );
6358
-    }
6359
-
6360
-
6361
-
6362
-    /**
6363
-     * Clears all the models field caches. This is only useful when a sub-class
6364
-     * might have added a field or something and these caches might be invalidated
6365
-     */
6366
-    protected function _invalidate_field_caches()
6367
-    {
6368
-        $this->_cache_foreign_key_to_fields = array();
6369
-        $this->_cached_fields = null;
6370
-        $this->_cached_fields_non_db_only = null;
6371
-    }
6372
-
6373
-
6374
-
6375
-    /**
6376
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6377
-     * (eg "and", "or", "not").
6378
-     *
6379
-     * @return array
6380
-     */
6381
-    public function logic_query_param_keys()
6382
-    {
6383
-        return $this->_logic_query_param_keys;
6384
-    }
6385
-
6386
-
6387
-
6388
-    /**
6389
-     * Determines whether or not the where query param array key is for a logic query param.
6390
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6391
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6392
-     *
6393
-     * @param $query_param_key
6394
-     * @return bool
6395
-     */
6396
-    public function is_logic_query_param_key($query_param_key)
6397
-    {
6398
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6399
-            if (
6400
-                $query_param_key === $logic_query_param_key
6401
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6402
-            ) {
6403
-                return true;
6404
-            }
6405
-        }
6406
-        return false;
6407
-    }
6408
-
6409
-    /**
6410
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6411
-     * @since 4.9.74.p
6412
-     * @return boolean
6413
-     */
6414
-    public function hasPassword()
6415
-    {
6416
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6417
-        if ($this->has_password_field === null) {
6418
-            $password_field = $this->getPasswordField();
6419
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6420
-        }
6421
-        return $this->has_password_field;
6422
-    }
6423
-
6424
-    /**
6425
-     * Returns the password field on this model, if there is one
6426
-     * @since 4.9.74.p
6427
-     * @return EE_Password_Field|null
6428
-     */
6429
-    public function getPasswordField()
6430
-    {
6431
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6432
-        // there's no need to search for it. If we don't know yet, then find out
6433
-        if ($this->has_password_field === null && $this->password_field === null) {
6434
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6435
-        }
6436
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6437
-        return $this->password_field;
6438
-    }
6439
-
6440
-
6441
-    /**
6442
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6443
-     * @since 4.9.74.p
6444
-     * @return EE_Model_Field_Base[]
6445
-     * @throws EE_Error
6446
-     */
6447
-    public function getPasswordProtectedFields()
6448
-    {
6449
-        $password_field = $this->getPasswordField();
6450
-        $fields = array();
6451
-        if ($password_field instanceof EE_Password_Field) {
6452
-            $field_names = $password_field->protectedFields();
6453
-            foreach ($field_names as $field_name) {
6454
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6455
-            }
6456
-        }
6457
-        return $fields;
6458
-    }
6459
-
6460
-
6461
-    /**
6462
-     * Checks if the current user can perform the requested action on this model
6463
-     * @since 4.9.74.p
6464
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6465
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6466
-     * @return bool
6467
-     * @throws EE_Error
6468
-     * @throws InvalidArgumentException
6469
-     * @throws InvalidDataTypeException
6470
-     * @throws InvalidInterfaceException
6471
-     * @throws ReflectionException
6472
-     * @throws UnexpectedEntityException
6473
-     */
6474
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6475
-    {
6476
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6477
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6478
-        }
6479
-        if (!is_array($model_obj_or_fields_n_values)) {
6480
-            throw new UnexpectedEntityException(
6481
-                $model_obj_or_fields_n_values,
6482
-                'EE_Base_Class',
6483
-                sprintf(
6484
-                    esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6485
-                    __FUNCTION__
6486
-                )
6487
-            );
6488
-        }
6489
-        return $this->exists(
6490
-            $this->alter_query_params_to_restrict_by_ID(
6491
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6492
-                array(
6493
-                    'default_where_conditions' => 'none',
6494
-                    'caps'                     => $cap_to_check,
6495
-                )
6496
-            )
6497
-        );
6498
-    }
6499
-
6500
-    /**
6501
-     * Returns the query param where conditions key to the password affecting this model.
6502
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6503
-     * @since 4.9.74.p
6504
-     * @return null|string
6505
-     * @throws EE_Error
6506
-     * @throws InvalidArgumentException
6507
-     * @throws InvalidDataTypeException
6508
-     * @throws InvalidInterfaceException
6509
-     * @throws ModelConfigurationException
6510
-     * @throws ReflectionException
6511
-     */
6512
-    public function modelChainAndPassword()
6513
-    {
6514
-        if ($this->model_chain_to_password === null) {
6515
-            throw new ModelConfigurationException(
6516
-                $this,
6517
-                esc_html_x(
6518
-                // @codingStandardsIgnoreStart
6519
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6520
-                    // @codingStandardsIgnoreEnd
6521
-                    '1: model name',
6522
-                    'event_espresso'
6523
-                )
6524
-            );
6525
-        }
6526
-        if ($this->model_chain_to_password === '') {
6527
-            $model_with_password = $this;
6528
-        } else {
6529
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6530
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6531
-            } else {
6532
-                $last_model_in_chain = $this->model_chain_to_password;
6533
-            }
6534
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6535
-        }
6536
-
6537
-        $password_field = $model_with_password->getPasswordField();
6538
-        if ($password_field instanceof EE_Password_Field) {
6539
-            $password_field_name = $password_field->get_name();
6540
-        } else {
6541
-            throw new ModelConfigurationException(
6542
-                $this,
6543
-                sprintf(
6544
-                    esc_html_x(
6545
-                        '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"',
6546
-                        '1: model name, 2: special string',
6547
-                        'event_espresso'
6548
-                    ),
6549
-                    $model_with_password->get_this_model_name(),
6550
-                    $this->model_chain_to_password
6551
-                )
6552
-            );
6553
-        }
6554
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6555
-    }
6556
-
6557
-    /**
6558
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6559
-     * or if this model itself has a password affecting access to some of its other fields.
6560
-     * @since 4.9.74.p
6561
-     * @return boolean
6562
-     */
6563
-    public function restrictedByRelatedModelPassword()
6564
-    {
6565
-        return $this->model_chain_to_password !== null;
6566
-    }
3864
+		}
3865
+		return $null_friendly_where_conditions;
3866
+	}
3867
+
3868
+
3869
+
3870
+	/**
3871
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3872
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3873
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3874
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3875
+	 *
3876
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3877
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3878
+	 */
3879
+	private function _get_default_where_conditions($model_relation_path = '')
3880
+	{
3881
+		if ($this->_ignore_where_strategy) {
3882
+			return array();
3883
+		}
3884
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3885
+	}
3886
+
3887
+
3888
+
3889
+	/**
3890
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3891
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3892
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3893
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3894
+	 * Similar to _get_default_where_conditions
3895
+	 *
3896
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3897
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3898
+	 */
3899
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3900
+	{
3901
+		if ($this->_ignore_where_strategy) {
3902
+			return array();
3903
+		}
3904
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3905
+	}
3906
+
3907
+
3908
+
3909
+	/**
3910
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3911
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3912
+	 *
3913
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3914
+	 * @return string
3915
+	 * @throws EE_Error
3916
+	 */
3917
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3918
+	{
3919
+		$selects = $this->_get_columns_to_select_for_this_model();
3920
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included) {
3921
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3922
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3923
+			foreach ($other_model_selects as $key => $value) {
3924
+				$selects[] = $value;
3925
+			}
3926
+		}
3927
+		return implode(", ", $selects);
3928
+	}
3929
+
3930
+
3931
+
3932
+	/**
3933
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3934
+	 * So that's going to be the columns for all the fields on the model
3935
+	 *
3936
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3937
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3938
+	 */
3939
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3940
+	{
3941
+		$fields = $this->field_settings();
3942
+		$selects = array();
3943
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3944
+			$model_relation_chain,
3945
+			$this->get_this_model_name()
3946
+		);
3947
+		foreach ($fields as $field_obj) {
3948
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3949
+						 . $field_obj->get_table_alias()
3950
+						 . "."
3951
+						 . $field_obj->get_table_column()
3952
+						 . " AS '"
3953
+						 . $table_alias_with_model_relation_chain_prefix
3954
+						 . $field_obj->get_table_alias()
3955
+						 . "."
3956
+						 . $field_obj->get_table_column()
3957
+						 . "'";
3958
+		}
3959
+		// make sure we are also getting the PKs of each table
3960
+		$tables = $this->get_tables();
3961
+		if (count($tables) > 1) {
3962
+			foreach ($tables as $table_obj) {
3963
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3964
+									   . $table_obj->get_fully_qualified_pk_column();
3965
+				if (! in_array($qualified_pk_column, $selects)) {
3966
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3967
+				}
3968
+			}
3969
+		}
3970
+		return $selects;
3971
+	}
3972
+
3973
+
3974
+
3975
+	/**
3976
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3977
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3978
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3979
+	 * SQL for joining, and the data types
3980
+	 *
3981
+	 * @param null|string                 $original_query_param
3982
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3983
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3984
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3985
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3986
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3987
+	 *                                                          or 'Registration's
3988
+	 * @param string                      $original_query_param what it originally was (eg
3989
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3990
+	 *                                                          matches $query_param
3991
+	 * @throws EE_Error
3992
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3993
+	 */
3994
+	private function _extract_related_model_info_from_query_param(
3995
+		$query_param,
3996
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3997
+		$query_param_type,
3998
+		$original_query_param = null
3999
+	) {
4000
+		if ($original_query_param === null) {
4001
+			$original_query_param = $query_param;
4002
+		}
4003
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4004
+		// check to see if we have a field on this model
4005
+		$this_model_fields = $this->field_settings(true);
4006
+		if (array_key_exists($query_param, $this_model_fields)) {
4007
+			$field_is_allowed = in_array(
4008
+				$query_param_type,
4009
+				[0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4010
+				true
4011
+			);
4012
+			if ($field_is_allowed) {
4013
+				return;
4014
+			}
4015
+			throw new EE_Error(
4016
+				sprintf(
4017
+					__(
4018
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4019
+						"event_espresso"
4020
+					),
4021
+					$query_param,
4022
+					get_class($this),
4023
+					$query_param_type,
4024
+					$original_query_param
4025
+				)
4026
+			);
4027
+		}
4028
+		// check if this is a special logic query param
4029
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4030
+			$operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4031
+			if ($operator_is_allowed) {
4032
+				return;
4033
+			}
4034
+			throw new EE_Error(
4035
+				sprintf(
4036
+					__(
4037
+						'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',
4038
+						'event_espresso'
4039
+					),
4040
+					implode('", "', $this->_logic_query_param_keys),
4041
+					$query_param,
4042
+					get_class($this),
4043
+					'<br />',
4044
+					"\t"
4045
+					. ' $passed_in_query_info = <pre>'
4046
+					. print_r($passed_in_query_info, true)
4047
+					. '</pre>'
4048
+					. "\n\t"
4049
+					. ' $query_param_type = '
4050
+					. $query_param_type
4051
+					. "\n\t"
4052
+					. ' $original_query_param = '
4053
+					. $original_query_param
4054
+				)
4055
+			);
4056
+		}
4057
+		// check if it's a custom selection
4058
+		if (
4059
+			$this->_custom_selections instanceof CustomSelects
4060
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4061
+		) {
4062
+			return;
4063
+		}
4064
+		// check if has a model name at the beginning
4065
+		// and
4066
+		// check if it's a field on a related model
4067
+		if (
4068
+			$this->extractJoinModelFromQueryParams(
4069
+				$passed_in_query_info,
4070
+				$query_param,
4071
+				$original_query_param,
4072
+				$query_param_type
4073
+			)
4074
+		) {
4075
+			return;
4076
+		}
4077
+
4078
+		// ok so $query_param didn't start with a model name
4079
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4080
+		// it's wack, that's what it is
4081
+		throw new EE_Error(
4082
+			sprintf(
4083
+				esc_html__(
4084
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4085
+					"event_espresso"
4086
+				),
4087
+				$query_param,
4088
+				get_class($this),
4089
+				$query_param_type,
4090
+				$original_query_param
4091
+			)
4092
+		);
4093
+	}
4094
+
4095
+
4096
+	/**
4097
+	 * Extracts any possible join model information from the provided possible_join_string.
4098
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4099
+	 * parts that should be added to the query.
4100
+	 *
4101
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4102
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4103
+	 * @param null|string                 $original_query_param
4104
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4105
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4106
+	 * @return bool  returns true if a join was added and false if not.
4107
+	 * @throws EE_Error
4108
+	 */
4109
+	private function extractJoinModelFromQueryParams(
4110
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4111
+		$possible_join_string,
4112
+		$original_query_param,
4113
+		$query_parameter_type
4114
+	) {
4115
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4116
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4117
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4118
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4119
+				if ($possible_join_string === '') {
4120
+					// nothing left to $query_param
4121
+					// we should actually end in a field name, not a model like this!
4122
+					throw new EE_Error(
4123
+						sprintf(
4124
+							esc_html__(
4125
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4126
+								"event_espresso"
4127
+							),
4128
+							$possible_join_string,
4129
+							$query_parameter_type,
4130
+							get_class($this),
4131
+							$valid_related_model_name
4132
+						)
4133
+					);
4134
+				}
4135
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4136
+				$related_model_obj->_extract_related_model_info_from_query_param(
4137
+					$possible_join_string,
4138
+					$query_info_carrier,
4139
+					$query_parameter_type,
4140
+					$original_query_param
4141
+				);
4142
+				return true;
4143
+			}
4144
+			if ($possible_join_string === $valid_related_model_name) {
4145
+				$this->_add_join_to_model(
4146
+					$valid_related_model_name,
4147
+					$query_info_carrier,
4148
+					$original_query_param
4149
+				);
4150
+				return true;
4151
+			}
4152
+		}
4153
+		return false;
4154
+	}
4155
+
4156
+
4157
+	/**
4158
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4159
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4160
+	 * @throws EE_Error
4161
+	 */
4162
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4163
+	{
4164
+		if (
4165
+			$this->_custom_selections instanceof CustomSelects
4166
+			&& (
4167
+				$this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4168
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4169
+			)
4170
+		) {
4171
+			$original_selects = $this->_custom_selections->originalSelects();
4172
+			foreach ($original_selects as $alias => $select_configuration) {
4173
+				$this->extractJoinModelFromQueryParams(
4174
+					$query_info_carrier,
4175
+					$select_configuration[0],
4176
+					$select_configuration[0],
4177
+					'custom_selects'
4178
+				);
4179
+			}
4180
+		}
4181
+	}
4182
+
4183
+
4184
+
4185
+	/**
4186
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4187
+	 * and store it on $passed_in_query_info
4188
+	 *
4189
+	 * @param string                      $model_name
4190
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4191
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4192
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4193
+	 *                                                          and are adding a join to 'Payment' with the original
4194
+	 *                                                          query param key
4195
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4196
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4197
+	 *                                                          Payment wants to add default query params so that it
4198
+	 *                                                          will know what models to prepend onto its default query
4199
+	 *                                                          params or in case it wants to rename tables (in case
4200
+	 *                                                          there are multiple joins to the same table)
4201
+	 * @return void
4202
+	 * @throws EE_Error
4203
+	 */
4204
+	private function _add_join_to_model(
4205
+		$model_name,
4206
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4207
+		$original_query_param
4208
+	) {
4209
+		$relation_obj = $this->related_settings_for($model_name);
4210
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4211
+		// check if the relation is HABTM, because then we're essentially doing two joins
4212
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4213
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4214
+			$join_model_obj = $relation_obj->get_join_model();
4215
+			// replace the model specified with the join model for this relation chain, whi
4216
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4217
+				$model_name,
4218
+				$join_model_obj->get_this_model_name(),
4219
+				$model_relation_chain
4220
+			);
4221
+			$passed_in_query_info->merge(
4222
+				new EE_Model_Query_Info_Carrier(
4223
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4224
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4225
+				)
4226
+			);
4227
+		}
4228
+		// now just join to the other table pointed to by the relation object, and add its data types
4229
+		$passed_in_query_info->merge(
4230
+			new EE_Model_Query_Info_Carrier(
4231
+				array($model_relation_chain => $model_name),
4232
+				$relation_obj->get_join_statement($model_relation_chain)
4233
+			)
4234
+		);
4235
+	}
4236
+
4237
+
4238
+
4239
+	/**
4240
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4241
+	 *
4242
+	 * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4243
+	 * @return string of SQL
4244
+	 * @throws EE_Error
4245
+	 */
4246
+	private function _construct_where_clause($where_params)
4247
+	{
4248
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4249
+		if ($SQL) {
4250
+			return " WHERE " . $SQL;
4251
+		}
4252
+		return '';
4253
+	}
4254
+
4255
+
4256
+
4257
+	/**
4258
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4259
+	 * and should be passed HAVING parameters, not WHERE parameters
4260
+	 *
4261
+	 * @param array $having_params
4262
+	 * @return string
4263
+	 * @throws EE_Error
4264
+	 */
4265
+	private function _construct_having_clause($having_params)
4266
+	{
4267
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4268
+		if ($SQL) {
4269
+			return " HAVING " . $SQL;
4270
+		}
4271
+		return '';
4272
+	}
4273
+
4274
+
4275
+	/**
4276
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4277
+	 * Event_Meta.meta_value = 'foo'))"
4278
+	 *
4279
+	 * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4280
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4281
+	 * @throws EE_Error
4282
+	 * @return string of SQL
4283
+	 */
4284
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4285
+	{
4286
+		$where_clauses = array();
4287
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4288
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4289
+			if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4290
+				switch ($query_param) {
4291
+					case 'not':
4292
+					case 'NOT':
4293
+						$where_clauses[] = "! ("
4294
+										   . $this->_construct_condition_clause_recursive(
4295
+											   $op_and_value_or_sub_condition,
4296
+											   $glue
4297
+										   )
4298
+										   . ")";
4299
+						break;
4300
+					case 'and':
4301
+					case 'AND':
4302
+						$where_clauses[] = " ("
4303
+										   . $this->_construct_condition_clause_recursive(
4304
+											   $op_and_value_or_sub_condition,
4305
+											   ' AND '
4306
+										   )
4307
+										   . ")";
4308
+						break;
4309
+					case 'or':
4310
+					case 'OR':
4311
+						$where_clauses[] = " ("
4312
+										   . $this->_construct_condition_clause_recursive(
4313
+											   $op_and_value_or_sub_condition,
4314
+											   ' OR '
4315
+										   )
4316
+										   . ")";
4317
+						break;
4318
+				}
4319
+			} else {
4320
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4321
+				// if it's not a normal field, maybe it's a custom selection?
4322
+				if (! $field_obj) {
4323
+					if ($this->_custom_selections instanceof CustomSelects) {
4324
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4325
+					} else {
4326
+						throw new EE_Error(sprintf(__(
4327
+							"%s is neither a valid model field name, nor a custom selection",
4328
+							"event_espresso"
4329
+						), $query_param));
4330
+					}
4331
+				}
4332
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4333
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4334
+			}
4335
+		}
4336
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4337
+	}
4338
+
4339
+
4340
+
4341
+	/**
4342
+	 * Takes the input parameter and extract the table name (alias) and column name
4343
+	 *
4344
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4345
+	 * @throws EE_Error
4346
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4347
+	 */
4348
+	private function _deduce_column_name_from_query_param($query_param)
4349
+	{
4350
+		$field = $this->_deduce_field_from_query_param($query_param);
4351
+		if ($field) {
4352
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4353
+				$field->get_model_name(),
4354
+				$query_param
4355
+			);
4356
+			return $table_alias_prefix . $field->get_qualified_column();
4357
+		}
4358
+		if (
4359
+			$this->_custom_selections instanceof CustomSelects
4360
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4361
+		) {
4362
+			// maybe it's custom selection item?
4363
+			// if so, just use it as the "column name"
4364
+			return $query_param;
4365
+		}
4366
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4367
+			? implode(',', $this->_custom_selections->columnAliases())
4368
+			: '';
4369
+		throw new EE_Error(
4370
+			sprintf(
4371
+				__(
4372
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4373
+					"event_espresso"
4374
+				),
4375
+				$query_param,
4376
+				$custom_select_aliases
4377
+			)
4378
+		);
4379
+	}
4380
+
4381
+
4382
+
4383
+	/**
4384
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4385
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4386
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4387
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4388
+	 *
4389
+	 * @param string $condition_query_param_key
4390
+	 * @return string
4391
+	 */
4392
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4393
+	{
4394
+		$pos_of_star = strpos($condition_query_param_key, '*');
4395
+		if ($pos_of_star === false) {
4396
+			return $condition_query_param_key;
4397
+		}
4398
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4399
+		return $condition_query_param_sans_star;
4400
+	}
4401
+
4402
+
4403
+
4404
+	/**
4405
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4406
+	 *
4407
+	 * @param                            mixed      array | string    $op_and_value
4408
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4409
+	 * @throws EE_Error
4410
+	 * @return string
4411
+	 */
4412
+	private function _construct_op_and_value($op_and_value, $field_obj)
4413
+	{
4414
+		if (is_array($op_and_value)) {
4415
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4416
+			if (! $operator) {
4417
+				$php_array_like_string = array();
4418
+				foreach ($op_and_value as $key => $value) {
4419
+					$php_array_like_string[] = "$key=>$value";
4420
+				}
4421
+				throw new EE_Error(
4422
+					sprintf(
4423
+						__(
4424
+							"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))",
4425
+							"event_espresso"
4426
+						),
4427
+						implode(",", $php_array_like_string)
4428
+					)
4429
+				);
4430
+			}
4431
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4432
+		} else {
4433
+			$operator = '=';
4434
+			$value = $op_and_value;
4435
+		}
4436
+		// check to see if the value is actually another field
4437
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4438
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4439
+		}
4440
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4441
+			// in this case, the value should be an array, or at least a comma-separated list
4442
+			// it will need to handle a little differently
4443
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4444
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4445
+			return $operator . SP . $cleaned_value;
4446
+		}
4447
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4448
+			// the value should be an array with count of two.
4449
+			if (count($value) !== 2) {
4450
+				throw new EE_Error(
4451
+					sprintf(
4452
+						__(
4453
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4454
+							'event_espresso'
4455
+						),
4456
+						"BETWEEN"
4457
+					)
4458
+				);
4459
+			}
4460
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4461
+			return $operator . SP . $cleaned_value;
4462
+		}
4463
+		if (in_array($operator, $this->valid_null_style_operators())) {
4464
+			if ($value !== null) {
4465
+				throw new EE_Error(
4466
+					sprintf(
4467
+						__(
4468
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4469
+							"event_espresso"
4470
+						),
4471
+						$value,
4472
+						$operator
4473
+					)
4474
+				);
4475
+			}
4476
+			return $operator;
4477
+		}
4478
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4479
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4480
+			// remove other junk. So just treat it as a string.
4481
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4482
+		}
4483
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4484
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4485
+		}
4486
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4487
+			throw new EE_Error(
4488
+				sprintf(
4489
+					__(
4490
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4491
+						'event_espresso'
4492
+					),
4493
+					$operator,
4494
+					$operator
4495
+				)
4496
+			);
4497
+		}
4498
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4499
+			throw new EE_Error(
4500
+				sprintf(
4501
+					__(
4502
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4503
+						'event_espresso'
4504
+					),
4505
+					$operator,
4506
+					$operator
4507
+				)
4508
+			);
4509
+		}
4510
+		throw new EE_Error(
4511
+			sprintf(
4512
+				__(
4513
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4514
+					"event_espresso"
4515
+				),
4516
+				http_build_query($op_and_value)
4517
+			)
4518
+		);
4519
+	}
4520
+
4521
+
4522
+
4523
+	/**
4524
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4525
+	 *
4526
+	 * @param array                      $values
4527
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4528
+	 *                                              '%s'
4529
+	 * @return string
4530
+	 * @throws EE_Error
4531
+	 */
4532
+	public function _construct_between_value($values, $field_obj)
4533
+	{
4534
+		$cleaned_values = array();
4535
+		foreach ($values as $value) {
4536
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4537
+		}
4538
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4539
+	}
4540
+
4541
+
4542
+	/**
4543
+	 * Takes an array or a comma-separated list of $values and cleans them
4544
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4545
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4546
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4547
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4548
+	 *
4549
+	 * @param mixed                      $values    array or comma-separated string
4550
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4551
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4552
+	 * @throws EE_Error
4553
+	 */
4554
+	public function _construct_in_value($values, $field_obj)
4555
+	{
4556
+		$prepped = [];
4557
+		// check if the value is a CSV list
4558
+		if (is_string($values)) {
4559
+			// in which case, turn it into an array
4560
+			$values = explode(',', $values);
4561
+		}
4562
+		// make sure we only have one of each value in the list
4563
+		$values = array_unique($values);
4564
+		foreach ($values as $value) {
4565
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4566
+		}
4567
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4568
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4569
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4570
+		if (empty($prepped)) {
4571
+			$all_fields = $this->field_settings();
4572
+			$first_field    = reset($all_fields);
4573
+			$main_table = $this->_get_main_table();
4574
+			$prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4575
+		}
4576
+		return '(' . implode(',', $prepped) . ')';
4577
+	}
4578
+
4579
+
4580
+
4581
+	/**
4582
+	 * @param mixed                      $value
4583
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4584
+	 * @throws EE_Error
4585
+	 * @return false|null|string
4586
+	 */
4587
+	private function _wpdb_prepare_using_field($value, $field_obj)
4588
+	{
4589
+		/** @type WPDB $wpdb */
4590
+		global $wpdb;
4591
+		if ($field_obj instanceof EE_Model_Field_Base) {
4592
+			return $wpdb->prepare(
4593
+				$field_obj->get_wpdb_data_type(),
4594
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4595
+			);
4596
+		} //$field_obj should really just be a data type
4597
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4598
+			throw new EE_Error(
4599
+				sprintf(
4600
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4601
+					$field_obj,
4602
+					implode(",", $this->_valid_wpdb_data_types)
4603
+				)
4604
+			);
4605
+		}
4606
+		return $wpdb->prepare($field_obj, $value);
4607
+	}
4608
+
4609
+
4610
+
4611
+	/**
4612
+	 * Takes the input parameter and finds the model field that it indicates.
4613
+	 *
4614
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4615
+	 * @throws EE_Error
4616
+	 * @return EE_Model_Field_Base
4617
+	 */
4618
+	protected function _deduce_field_from_query_param($query_param_name)
4619
+	{
4620
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4621
+		// which will help us find the database table and column
4622
+		$query_param_parts = explode(".", $query_param_name);
4623
+		if (empty($query_param_parts)) {
4624
+			throw new EE_Error(sprintf(__(
4625
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4626
+				'event_espresso'
4627
+			), $query_param_name));
4628
+		}
4629
+		$number_of_parts = count($query_param_parts);
4630
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4631
+		if ($number_of_parts === 1) {
4632
+			$field_name = $last_query_param_part;
4633
+			$model_obj = $this;
4634
+		} else {// $number_of_parts >= 2
4635
+			// the last part is the column name, and there are only 2parts. therefore...
4636
+			$field_name = $last_query_param_part;
4637
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4638
+		}
4639
+		try {
4640
+			return $model_obj->field_settings_for($field_name);
4641
+		} catch (EE_Error $e) {
4642
+			return null;
4643
+		}
4644
+	}
4645
+
4646
+
4647
+
4648
+	/**
4649
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4650
+	 * alias and column which corresponds to it
4651
+	 *
4652
+	 * @param string $field_name
4653
+	 * @throws EE_Error
4654
+	 * @return string
4655
+	 */
4656
+	public function _get_qualified_column_for_field($field_name)
4657
+	{
4658
+		$all_fields = $this->field_settings();
4659
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4660
+		if ($field) {
4661
+			return $field->get_qualified_column();
4662
+		}
4663
+		throw new EE_Error(
4664
+			sprintf(
4665
+				__(
4666
+					"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.",
4667
+					'event_espresso'
4668
+				),
4669
+				$field_name,
4670
+				get_class($this)
4671
+			)
4672
+		);
4673
+	}
4674
+
4675
+
4676
+
4677
+	/**
4678
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4679
+	 * Example usage:
4680
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4681
+	 *      array(),
4682
+	 *      ARRAY_A,
4683
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4684
+	 *  );
4685
+	 * is equivalent to
4686
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4687
+	 * and
4688
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4689
+	 *      array(
4690
+	 *          array(
4691
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4692
+	 *          ),
4693
+	 *          ARRAY_A,
4694
+	 *          implode(
4695
+	 *              ', ',
4696
+	 *              array_merge(
4697
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4698
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4699
+	 *              )
4700
+	 *          )
4701
+	 *      )
4702
+	 *  );
4703
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4704
+	 *
4705
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4706
+	 *                                            and the one whose fields you are selecting for example: when querying
4707
+	 *                                            tickets model and selecting fields from the tickets model you would
4708
+	 *                                            leave this parameter empty, because no models are needed to join
4709
+	 *                                            between the queried model and the selected one. Likewise when
4710
+	 *                                            querying the datetime model and selecting fields from the tickets
4711
+	 *                                            model, it would also be left empty, because there is a direct
4712
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4713
+	 *                                            them together. However, when querying from the event model and
4714
+	 *                                            selecting fields from the ticket model, you should provide the string
4715
+	 *                                            'Datetime', indicating that the event model must first join to the
4716
+	 *                                            datetime model in order to find its relation to ticket model.
4717
+	 *                                            Also, when querying from the venue model and selecting fields from
4718
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4719
+	 *                                            indicating you need to join the venue model to the event model,
4720
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4721
+	 *                                            This string is used to deduce the prefix that gets added onto the
4722
+	 *                                            models' tables qualified columns
4723
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4724
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4725
+	 *                                            qualified column names
4726
+	 * @return array|string
4727
+	 */
4728
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4729
+	{
4730
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4731
+		$qualified_columns = array();
4732
+		foreach ($this->field_settings() as $field_name => $field) {
4733
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4734
+		}
4735
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4736
+	}
4737
+
4738
+
4739
+
4740
+	/**
4741
+	 * constructs the select use on special limit joins
4742
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4743
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4744
+	 * (as that is typically where the limits would be set).
4745
+	 *
4746
+	 * @param  string       $table_alias The table the select is being built for
4747
+	 * @param  mixed|string $limit       The limit for this select
4748
+	 * @return string                The final select join element for the query.
4749
+	 */
4750
+	public function _construct_limit_join_select($table_alias, $limit)
4751
+	{
4752
+		$SQL = '';
4753
+		foreach ($this->_tables as $table_obj) {
4754
+			if ($table_obj instanceof EE_Primary_Table) {
4755
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4756
+					? $table_obj->get_select_join_limit($limit)
4757
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4758
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4759
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4760
+					? $table_obj->get_select_join_limit_join($limit)
4761
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4762
+			}
4763
+		}
4764
+		return $SQL;
4765
+	}
4766
+
4767
+
4768
+
4769
+	/**
4770
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4771
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4772
+	 *
4773
+	 * @return string SQL
4774
+	 * @throws EE_Error
4775
+	 */
4776
+	public function _construct_internal_join()
4777
+	{
4778
+		$SQL = $this->_get_main_table()->get_table_sql();
4779
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4780
+		return $SQL;
4781
+	}
4782
+
4783
+
4784
+
4785
+	/**
4786
+	 * Constructs the SQL for joining all the tables on this model.
4787
+	 * Normally $alias should be the primary table's alias, but in cases where
4788
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4789
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4790
+	 * alias, this will construct SQL like:
4791
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4792
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4793
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4794
+	 *
4795
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4796
+	 * @return string
4797
+	 */
4798
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4799
+	{
4800
+		$SQL = '';
4801
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4802
+		foreach ($this->_tables as $table_obj) {
4803
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4804
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4805
+					// so we're joining to this table, meaning the table is already in
4806
+					// the FROM statement, BUT the primary table isn't. So we want
4807
+					// to add the inverse join sql
4808
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4809
+				} else {
4810
+					// just add a regular JOIN to this table from the primary table
4811
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4812
+				}
4813
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4814
+		}
4815
+		return $SQL;
4816
+	}
4817
+
4818
+
4819
+
4820
+	/**
4821
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4822
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4823
+	 * their data type (eg, '%s', '%d', etc)
4824
+	 *
4825
+	 * @return array
4826
+	 */
4827
+	public function _get_data_types()
4828
+	{
4829
+		$data_types = array();
4830
+		foreach ($this->field_settings() as $field_obj) {
4831
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4832
+			/** @var $field_obj EE_Model_Field_Base */
4833
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4834
+		}
4835
+		return $data_types;
4836
+	}
4837
+
4838
+
4839
+
4840
+	/**
4841
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4842
+	 *
4843
+	 * @param string $model_name
4844
+	 * @throws EE_Error
4845
+	 * @return EEM_Base
4846
+	 */
4847
+	public function get_related_model_obj($model_name)
4848
+	{
4849
+		$model_classname = "EEM_" . $model_name;
4850
+		if (! class_exists($model_classname)) {
4851
+			throw new EE_Error(sprintf(__(
4852
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4853
+				'event_espresso'
4854
+			), $model_name, $model_classname));
4855
+		}
4856
+		return call_user_func($model_classname . "::instance");
4857
+	}
4858
+
4859
+
4860
+
4861
+	/**
4862
+	 * Returns the array of EE_ModelRelations for this model.
4863
+	 *
4864
+	 * @return EE_Model_Relation_Base[]
4865
+	 */
4866
+	public function relation_settings()
4867
+	{
4868
+		return $this->_model_relations;
4869
+	}
4870
+
4871
+
4872
+
4873
+	/**
4874
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4875
+	 * because without THOSE models, this model probably doesn't have much purpose.
4876
+	 * (Eg, without an event, datetimes have little purpose.)
4877
+	 *
4878
+	 * @return EE_Belongs_To_Relation[]
4879
+	 */
4880
+	public function belongs_to_relations()
4881
+	{
4882
+		$belongs_to_relations = array();
4883
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4884
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4885
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4886
+			}
4887
+		}
4888
+		return $belongs_to_relations;
4889
+	}
4890
+
4891
+
4892
+
4893
+	/**
4894
+	 * Returns the specified EE_Model_Relation, or throws an exception
4895
+	 *
4896
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4897
+	 * @throws EE_Error
4898
+	 * @return EE_Model_Relation_Base
4899
+	 */
4900
+	public function related_settings_for($relation_name)
4901
+	{
4902
+		$relatedModels = $this->relation_settings();
4903
+		if (! array_key_exists($relation_name, $relatedModels)) {
4904
+			throw new EE_Error(
4905
+				sprintf(
4906
+					__(
4907
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4908
+						'event_espresso'
4909
+					),
4910
+					$relation_name,
4911
+					$this->_get_class_name(),
4912
+					implode(', ', array_keys($relatedModels))
4913
+				)
4914
+			);
4915
+		}
4916
+		return $relatedModels[ $relation_name ];
4917
+	}
4918
+
4919
+
4920
+
4921
+	/**
4922
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4923
+	 * fields
4924
+	 *
4925
+	 * @param string $fieldName
4926
+	 * @param boolean $include_db_only_fields
4927
+	 * @throws EE_Error
4928
+	 * @return EE_Model_Field_Base
4929
+	 */
4930
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4931
+	{
4932
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4933
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4934
+			throw new EE_Error(sprintf(
4935
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4936
+				$fieldName,
4937
+				get_class($this)
4938
+			));
4939
+		}
4940
+		return $fieldSettings[ $fieldName ];
4941
+	}
4942
+
4943
+
4944
+
4945
+	/**
4946
+	 * Checks if this field exists on this model
4947
+	 *
4948
+	 * @param string $fieldName a key in the model's _field_settings array
4949
+	 * @return boolean
4950
+	 */
4951
+	public function has_field($fieldName)
4952
+	{
4953
+		$fieldSettings = $this->field_settings(true);
4954
+		if (isset($fieldSettings[ $fieldName ])) {
4955
+			return true;
4956
+		}
4957
+		return false;
4958
+	}
4959
+
4960
+
4961
+
4962
+	/**
4963
+	 * Returns whether or not this model has a relation to the specified model
4964
+	 *
4965
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4966
+	 * @return boolean
4967
+	 */
4968
+	public function has_relation($relation_name)
4969
+	{
4970
+		$relations = $this->relation_settings();
4971
+		if (isset($relations[ $relation_name ])) {
4972
+			return true;
4973
+		}
4974
+		return false;
4975
+	}
4976
+
4977
+
4978
+
4979
+	/**
4980
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4981
+	 * Eg, on EE_Answer that would be ANS_ID field object
4982
+	 *
4983
+	 * @param $field_obj
4984
+	 * @return boolean
4985
+	 */
4986
+	public function is_primary_key_field($field_obj)
4987
+	{
4988
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4989
+	}
4990
+
4991
+
4992
+
4993
+	/**
4994
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4995
+	 * Eg, on EE_Answer that would be ANS_ID field object
4996
+	 *
4997
+	 * @return EE_Model_Field_Base
4998
+	 * @throws EE_Error
4999
+	 */
5000
+	public function get_primary_key_field()
5001
+	{
5002
+		if ($this->_primary_key_field === null) {
5003
+			foreach ($this->field_settings(true) as $field_obj) {
5004
+				if ($this->is_primary_key_field($field_obj)) {
5005
+					$this->_primary_key_field = $field_obj;
5006
+					break;
5007
+				}
5008
+			}
5009
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5010
+				throw new EE_Error(sprintf(
5011
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
5012
+					get_class($this)
5013
+				));
5014
+			}
5015
+		}
5016
+		return $this->_primary_key_field;
5017
+	}
5018
+
5019
+
5020
+
5021
+	/**
5022
+	 * Returns whether or not not there is a primary key on this model.
5023
+	 * Internally does some caching.
5024
+	 *
5025
+	 * @return boolean
5026
+	 */
5027
+	public function has_primary_key_field()
5028
+	{
5029
+		if ($this->_has_primary_key_field === null) {
5030
+			try {
5031
+				$this->get_primary_key_field();
5032
+				$this->_has_primary_key_field = true;
5033
+			} catch (EE_Error $e) {
5034
+				$this->_has_primary_key_field = false;
5035
+			}
5036
+		}
5037
+		return $this->_has_primary_key_field;
5038
+	}
5039
+
5040
+
5041
+
5042
+	/**
5043
+	 * Finds the first field of type $field_class_name.
5044
+	 *
5045
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5046
+	 *                                 EE_Foreign_Key_Field, etc
5047
+	 * @return EE_Model_Field_Base or null if none is found
5048
+	 */
5049
+	public function get_a_field_of_type($field_class_name)
5050
+	{
5051
+		foreach ($this->field_settings() as $field) {
5052
+			if ($field instanceof $field_class_name) {
5053
+				return $field;
5054
+			}
5055
+		}
5056
+		return null;
5057
+	}
5058
+
5059
+
5060
+
5061
+	/**
5062
+	 * Gets a foreign key field pointing to model.
5063
+	 *
5064
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5065
+	 * @return EE_Foreign_Key_Field_Base
5066
+	 * @throws EE_Error
5067
+	 */
5068
+	public function get_foreign_key_to($model_name)
5069
+	{
5070
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5071
+			foreach ($this->field_settings() as $field) {
5072
+				if (
5073
+					$field instanceof EE_Foreign_Key_Field_Base
5074
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5075
+				) {
5076
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5077
+					break;
5078
+				}
5079
+			}
5080
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5081
+				throw new EE_Error(sprintf(__(
5082
+					"There is no foreign key field pointing to model %s on model %s",
5083
+					'event_espresso'
5084
+				), $model_name, get_class($this)));
5085
+			}
5086
+		}
5087
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5088
+	}
5089
+
5090
+
5091
+
5092
+	/**
5093
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5094
+	 *
5095
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5096
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5097
+	 *                            Either one works
5098
+	 * @return string
5099
+	 */
5100
+	public function get_table_for_alias($table_alias)
5101
+	{
5102
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5103
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5104
+	}
5105
+
5106
+
5107
+
5108
+	/**
5109
+	 * Returns a flat array of all field son this model, instead of organizing them
5110
+	 * by table_alias as they are in the constructor.
5111
+	 *
5112
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5113
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5114
+	 */
5115
+	public function field_settings($include_db_only_fields = false)
5116
+	{
5117
+		if ($include_db_only_fields) {
5118
+			if ($this->_cached_fields === null) {
5119
+				$this->_cached_fields = array();
5120
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5121
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5122
+						$this->_cached_fields[ $field_name ] = $field_obj;
5123
+					}
5124
+				}
5125
+			}
5126
+			return $this->_cached_fields;
5127
+		}
5128
+		if ($this->_cached_fields_non_db_only === null) {
5129
+			$this->_cached_fields_non_db_only = array();
5130
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5131
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5132
+					/** @var $field_obj EE_Model_Field_Base */
5133
+					if (! $field_obj->is_db_only_field()) {
5134
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5135
+					}
5136
+				}
5137
+			}
5138
+		}
5139
+		return $this->_cached_fields_non_db_only;
5140
+	}
5141
+
5142
+
5143
+
5144
+	/**
5145
+	 *        cycle though array of attendees and create objects out of each item
5146
+	 *
5147
+	 * @access        private
5148
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5149
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5150
+	 *                           numerically indexed)
5151
+	 * @throws EE_Error
5152
+	 */
5153
+	protected function _create_objects($rows = array())
5154
+	{
5155
+		$array_of_objects = array();
5156
+		if (empty($rows)) {
5157
+			return array();
5158
+		}
5159
+		$count_if_model_has_no_primary_key = 0;
5160
+		$has_primary_key = $this->has_primary_key_field();
5161
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5162
+		foreach ((array) $rows as $row) {
5163
+			if (empty($row)) {
5164
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5165
+				return array();
5166
+			}
5167
+			// check if we've already set this object in the results array,
5168
+			// in which case there's no need to process it further (again)
5169
+			if ($has_primary_key) {
5170
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5171
+					$row,
5172
+					$primary_key_field->get_qualified_column(),
5173
+					$primary_key_field->get_table_column()
5174
+				);
5175
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5176
+					continue;
5177
+				}
5178
+			}
5179
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5180
+			if (! $classInstance) {
5181
+				throw new EE_Error(
5182
+					sprintf(
5183
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5184
+						$this->get_this_model_name(),
5185
+						http_build_query($row)
5186
+					)
5187
+				);
5188
+			}
5189
+			// set the timezone on the instantiated objects
5190
+			$classInstance->set_timezone($this->_timezone);
5191
+			// make sure if there is any timezone setting present that we set the timezone for the object
5192
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5193
+			$array_of_objects[ $key ] = $classInstance;
5194
+			// also, for all the relations of type BelongsTo, see if we can cache
5195
+			// those related models
5196
+			// (we could do this for other relations too, but if there are conditions
5197
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5198
+			// so it requires a little more thought than just caching them immediately...)
5199
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5200
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5201
+					// check if this model's INFO is present. If so, cache it on the model
5202
+					$other_model = $relation_obj->get_other_model();
5203
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5204
+					// if we managed to make a model object from the results, cache it on the main model object
5205
+					if ($other_model_obj_maybe) {
5206
+						// set timezone on these other model objects if they are present
5207
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5208
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5209
+					}
5210
+				}
5211
+			}
5212
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5213
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5214
+			// the field in the CustomSelects object
5215
+			if ($this->_custom_selections instanceof CustomSelects) {
5216
+				$classInstance->setCustomSelectsValues(
5217
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5218
+				);
5219
+			}
5220
+		}
5221
+		return $array_of_objects;
5222
+	}
5223
+
5224
+
5225
+	/**
5226
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5227
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5228
+	 *
5229
+	 * @param array $db_results_row
5230
+	 * @return array
5231
+	 */
5232
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5233
+	{
5234
+		$results = array();
5235
+		if ($this->_custom_selections instanceof CustomSelects) {
5236
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5237
+				if (isset($db_results_row[ $alias ])) {
5238
+					$results[ $alias ] = $this->convertValueToDataType(
5239
+						$db_results_row[ $alias ],
5240
+						$this->_custom_selections->getDataTypeForAlias($alias)
5241
+					);
5242
+				}
5243
+			}
5244
+		}
5245
+		return $results;
5246
+	}
5247
+
5248
+
5249
+	/**
5250
+	 * This will set the value for the given alias
5251
+	 * @param string $value
5252
+	 * @param string $datatype (one of %d, %s, %f)
5253
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5254
+	 */
5255
+	protected function convertValueToDataType($value, $datatype)
5256
+	{
5257
+		switch ($datatype) {
5258
+			case '%f':
5259
+				return (float) $value;
5260
+			case '%d':
5261
+				return (int) $value;
5262
+			default:
5263
+				return (string) $value;
5264
+		}
5265
+	}
5266
+
5267
+
5268
+	/**
5269
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5270
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5271
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5272
+	 * object (as set in the model_field!).
5273
+	 *
5274
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5275
+	 */
5276
+	public function create_default_object()
5277
+	{
5278
+		$this_model_fields_and_values = array();
5279
+		// setup the row using default values;
5280
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5281
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5282
+		}
5283
+		$className = $this->_get_class_name();
5284
+		$classInstance = EE_Registry::instance()
5285
+									->load_class($className, array($this_model_fields_and_values), false, false);
5286
+		return $classInstance;
5287
+	}
5288
+
5289
+
5290
+
5291
+	/**
5292
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5293
+	 *                             or an stdClass where each property is the name of a column,
5294
+	 * @return EE_Base_Class
5295
+	 * @throws EE_Error
5296
+	 */
5297
+	public function instantiate_class_from_array_or_object($cols_n_values)
5298
+	{
5299
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5300
+			$cols_n_values = get_object_vars($cols_n_values);
5301
+		}
5302
+		$primary_key = null;
5303
+		// make sure the array only has keys that are fields/columns on this model
5304
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5305
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5306
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5307
+		}
5308
+		$className = $this->_get_class_name();
5309
+		// check we actually found results that we can use to build our model object
5310
+		// if not, return null
5311
+		if ($this->has_primary_key_field()) {
5312
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5313
+				return null;
5314
+			}
5315
+		} elseif ($this->unique_indexes()) {
5316
+			$first_column = reset($this_model_fields_n_values);
5317
+			if (empty($first_column)) {
5318
+				return null;
5319
+			}
5320
+		}
5321
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5322
+		if ($primary_key) {
5323
+			$classInstance = $this->get_from_entity_map($primary_key);
5324
+			if (! $classInstance) {
5325
+				$classInstance = EE_Registry::instance()
5326
+											->load_class(
5327
+												$className,
5328
+												array($this_model_fields_n_values, $this->_timezone),
5329
+												true,
5330
+												false
5331
+											);
5332
+				// add this new object to the entity map
5333
+				$classInstance = $this->add_to_entity_map($classInstance);
5334
+			}
5335
+		} else {
5336
+			$classInstance = EE_Registry::instance()
5337
+										->load_class(
5338
+											$className,
5339
+											array($this_model_fields_n_values, $this->_timezone),
5340
+											true,
5341
+											false
5342
+										);
5343
+		}
5344
+		return $classInstance;
5345
+	}
5346
+
5347
+
5348
+
5349
+	/**
5350
+	 * Gets the model object from the  entity map if it exists
5351
+	 *
5352
+	 * @param int|string $id the ID of the model object
5353
+	 * @return EE_Base_Class
5354
+	 */
5355
+	public function get_from_entity_map($id)
5356
+	{
5357
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5358
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5359
+	}
5360
+
5361
+
5362
+
5363
+	/**
5364
+	 * add_to_entity_map
5365
+	 * Adds the object to the model's entity mappings
5366
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5367
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5368
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5369
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5370
+	 *        then this method should be called immediately after the update query
5371
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5372
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5373
+	 *
5374
+	 * @param    EE_Base_Class $object
5375
+	 * @throws EE_Error
5376
+	 * @return \EE_Base_Class
5377
+	 */
5378
+	public function add_to_entity_map(EE_Base_Class $object)
5379
+	{
5380
+		$className = $this->_get_class_name();
5381
+		if (! $object instanceof $className) {
5382
+			throw new EE_Error(sprintf(
5383
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5384
+				is_object($object) ? get_class($object) : $object,
5385
+				$className
5386
+			));
5387
+		}
5388
+		/** @var $object EE_Base_Class */
5389
+		if (! $object->ID()) {
5390
+			throw new EE_Error(sprintf(__(
5391
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5392
+				"event_espresso"
5393
+			), get_class($this)));
5394
+		}
5395
+		// double check it's not already there
5396
+		$classInstance = $this->get_from_entity_map($object->ID());
5397
+		if ($classInstance) {
5398
+			return $classInstance;
5399
+		}
5400
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5401
+		return $object;
5402
+	}
5403
+
5404
+
5405
+
5406
+	/**
5407
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5408
+	 * if no identifier is provided, then the entire entity map is emptied
5409
+	 *
5410
+	 * @param int|string $id the ID of the model object
5411
+	 * @return boolean
5412
+	 */
5413
+	public function clear_entity_map($id = null)
5414
+	{
5415
+		if (empty($id)) {
5416
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5417
+			return true;
5418
+		}
5419
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5420
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5421
+			return true;
5422
+		}
5423
+		return false;
5424
+	}
5425
+
5426
+
5427
+
5428
+	/**
5429
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5430
+	 * Given an array where keys are column (or column alias) names and values,
5431
+	 * returns an array of their corresponding field names and database values
5432
+	 *
5433
+	 * @param array $cols_n_values
5434
+	 * @return array
5435
+	 */
5436
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5437
+	{
5438
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5439
+	}
5440
+
5441
+
5442
+
5443
+	/**
5444
+	 * _deduce_fields_n_values_from_cols_n_values
5445
+	 * Given an array where keys are column (or column alias) names and values,
5446
+	 * returns an array of their corresponding field names and database values
5447
+	 *
5448
+	 * @param string $cols_n_values
5449
+	 * @return array
5450
+	 */
5451
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5452
+	{
5453
+		$this_model_fields_n_values = array();
5454
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5455
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5456
+				$cols_n_values,
5457
+				$table_obj->get_fully_qualified_pk_column(),
5458
+				$table_obj->get_pk_column()
5459
+			);
5460
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5461
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5462
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5463
+					if (! $field_obj->is_db_only_field()) {
5464
+						// prepare field as if its coming from db
5465
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5466
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5467
+					}
5468
+				}
5469
+			} else {
5470
+				// the table's rows existed. Use their values
5471
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5472
+					if (! $field_obj->is_db_only_field()) {
5473
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5474
+							$cols_n_values,
5475
+							$field_obj->get_qualified_column(),
5476
+							$field_obj->get_table_column()
5477
+						);
5478
+					}
5479
+				}
5480
+			}
5481
+		}
5482
+		return $this_model_fields_n_values;
5483
+	}
5484
+
5485
+
5486
+	/**
5487
+	 * @param $cols_n_values
5488
+	 * @param $qualified_column
5489
+	 * @param $regular_column
5490
+	 * @return null
5491
+	 * @throws EE_Error
5492
+	 * @throws ReflectionException
5493
+	 */
5494
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5495
+	{
5496
+		$value = null;
5497
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5498
+		// does the field on the model relate to this column retrieved from the db?
5499
+		// or is it a db-only field? (not relating to the model)
5500
+		if (isset($cols_n_values[ $qualified_column ])) {
5501
+			$value = $cols_n_values[ $qualified_column ];
5502
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5503
+			$value = $cols_n_values[ $regular_column ];
5504
+		} elseif (! empty($this->foreign_key_aliases)) {
5505
+			// no PK?  ok check if there is a foreign key alias set for this table
5506
+			// then check if that alias exists in the incoming data
5507
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5508
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5509
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5510
+					$value = $cols_n_values[ $FK_alias ];
5511
+					[$pk_class] = explode('.', $PK_column);
5512
+					$pk_model_name = "EEM_{$pk_class}";
5513
+					/** @var EEM_Base $pk_model */
5514
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5515
+					if ($pk_model instanceof EEM_Base) {
5516
+						// make sure object is pulled from db and added to entity map
5517
+						$pk_model->get_one_by_ID($value);
5518
+					}
5519
+					break;
5520
+				}
5521
+			}
5522
+		}
5523
+		return $value;
5524
+	}
5525
+
5526
+
5527
+
5528
+	/**
5529
+	 * refresh_entity_map_from_db
5530
+	 * Makes sure the model object in the entity map at $id assumes the values
5531
+	 * of the database (opposite of EE_base_Class::save())
5532
+	 *
5533
+	 * @param int|string $id
5534
+	 * @return EE_Base_Class
5535
+	 * @throws EE_Error
5536
+	 */
5537
+	public function refresh_entity_map_from_db($id)
5538
+	{
5539
+		$obj_in_map = $this->get_from_entity_map($id);
5540
+		if ($obj_in_map) {
5541
+			$wpdb_results = $this->_get_all_wpdb_results(
5542
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5543
+			);
5544
+			if ($wpdb_results && is_array($wpdb_results)) {
5545
+				$one_row = reset($wpdb_results);
5546
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5547
+					$obj_in_map->set_from_db($field_name, $db_value);
5548
+				}
5549
+				// clear the cache of related model objects
5550
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5551
+					$obj_in_map->clear_cache($relation_name, null, true);
5552
+				}
5553
+			}
5554
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5555
+			return $obj_in_map;
5556
+		}
5557
+		return $this->get_one_by_ID($id);
5558
+	}
5559
+
5560
+
5561
+
5562
+	/**
5563
+	 * refresh_entity_map_with
5564
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5565
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5566
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5567
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5568
+	 *
5569
+	 * @param int|string    $id
5570
+	 * @param EE_Base_Class $replacing_model_obj
5571
+	 * @return \EE_Base_Class
5572
+	 * @throws EE_Error
5573
+	 */
5574
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5575
+	{
5576
+		$obj_in_map = $this->get_from_entity_map($id);
5577
+		if ($obj_in_map) {
5578
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5579
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5580
+					$obj_in_map->set($field_name, $value);
5581
+				}
5582
+				// make the model object in the entity map's cache match the $replacing_model_obj
5583
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5584
+					$obj_in_map->clear_cache($relation_name, null, true);
5585
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5586
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5587
+					}
5588
+				}
5589
+			}
5590
+			return $obj_in_map;
5591
+		}
5592
+		$this->add_to_entity_map($replacing_model_obj);
5593
+		return $replacing_model_obj;
5594
+	}
5595
+
5596
+
5597
+
5598
+	/**
5599
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5600
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5601
+	 * require_once($this->_getClassName().".class.php");
5602
+	 *
5603
+	 * @return string
5604
+	 */
5605
+	private function _get_class_name()
5606
+	{
5607
+		return "EE_" . $this->get_this_model_name();
5608
+	}
5609
+
5610
+
5611
+
5612
+	/**
5613
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5614
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5615
+	 * it would be 'Events'.
5616
+	 *
5617
+	 * @param int $quantity
5618
+	 * @return string
5619
+	 */
5620
+	public function item_name($quantity = 1)
5621
+	{
5622
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5623
+	}
5624
+
5625
+
5626
+
5627
+	/**
5628
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5629
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5630
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5631
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5632
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5633
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5634
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5635
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5636
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5637
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5638
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5639
+	 *        return $previousReturnValue.$returnString;
5640
+	 * }
5641
+	 * require('EEM_Answer.model.php');
5642
+	 * $answer=EEM_Answer::instance();
5643
+	 * echo $answer->my_callback('monkeys',100);
5644
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5645
+	 *
5646
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5647
+	 * @param array  $args       array of original arguments passed to the function
5648
+	 * @throws EE_Error
5649
+	 * @return mixed whatever the plugin which calls add_filter decides
5650
+	 */
5651
+	public function __call($methodName, $args)
5652
+	{
5653
+		$className = get_class($this);
5654
+		$tagName = "FHEE__{$className}__{$methodName}";
5655
+		if (! has_filter($tagName)) {
5656
+			throw new EE_Error(
5657
+				sprintf(
5658
+					__(
5659
+						'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 );',
5660
+						'event_espresso'
5661
+					),
5662
+					$methodName,
5663
+					$className,
5664
+					$tagName,
5665
+					'<br />'
5666
+				)
5667
+			);
5668
+		}
5669
+		return apply_filters($tagName, null, $this, $args);
5670
+	}
5671
+
5672
+
5673
+
5674
+	/**
5675
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5676
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5677
+	 *
5678
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5679
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5680
+	 *                                                       the object's class name
5681
+	 *                                                       or object's ID
5682
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5683
+	 *                                                       exists in the database. If it does not, we add it
5684
+	 * @throws EE_Error
5685
+	 * @return EE_Base_Class
5686
+	 */
5687
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5688
+	{
5689
+		$className = $this->_get_class_name();
5690
+		if ($base_class_obj_or_id instanceof $className) {
5691
+			$model_object = $base_class_obj_or_id;
5692
+		} else {
5693
+			$primary_key_field = $this->get_primary_key_field();
5694
+			if (
5695
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5696
+				&& (
5697
+					is_int($base_class_obj_or_id)
5698
+					|| is_string($base_class_obj_or_id)
5699
+				)
5700
+			) {
5701
+				// assume it's an ID.
5702
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5703
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5704
+			} elseif (
5705
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5706
+				&& is_string($base_class_obj_or_id)
5707
+			) {
5708
+				// assume its a string representation of the object
5709
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5710
+			} else {
5711
+				throw new EE_Error(
5712
+					sprintf(
5713
+						__(
5714
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5715
+							'event_espresso'
5716
+						),
5717
+						$base_class_obj_or_id,
5718
+						$this->_get_class_name(),
5719
+						print_r($base_class_obj_or_id, true)
5720
+					)
5721
+				);
5722
+			}
5723
+		}
5724
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5725
+			$model_object->save();
5726
+		}
5727
+		return $model_object;
5728
+	}
5729
+
5730
+
5731
+
5732
+	/**
5733
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5734
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5735
+	 * returns it ID.
5736
+	 *
5737
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5738
+	 * @return int|string depending on the type of this model object's ID
5739
+	 * @throws EE_Error
5740
+	 */
5741
+	public function ensure_is_ID($base_class_obj_or_id)
5742
+	{
5743
+		$className = $this->_get_class_name();
5744
+		if ($base_class_obj_or_id instanceof $className) {
5745
+			/** @var $base_class_obj_or_id EE_Base_Class */
5746
+			$id = $base_class_obj_or_id->ID();
5747
+		} elseif (is_int($base_class_obj_or_id)) {
5748
+			// assume it's an ID
5749
+			$id = $base_class_obj_or_id;
5750
+		} elseif (is_string($base_class_obj_or_id)) {
5751
+			// assume its a string representation of the object
5752
+			$id = $base_class_obj_or_id;
5753
+		} else {
5754
+			throw new EE_Error(sprintf(
5755
+				__(
5756
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5757
+					'event_espresso'
5758
+				),
5759
+				$base_class_obj_or_id,
5760
+				$this->_get_class_name(),
5761
+				print_r($base_class_obj_or_id, true)
5762
+			));
5763
+		}
5764
+		return $id;
5765
+	}
5766
+
5767
+
5768
+
5769
+	/**
5770
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5771
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5772
+	 * been sanitized and converted into the appropriate domain.
5773
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5774
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5775
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5776
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5777
+	 * $EVT = EEM_Event::instance(); $old_setting =
5778
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5779
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5780
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5781
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5782
+	 *
5783
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5784
+	 * @return void
5785
+	 */
5786
+	public function assume_values_already_prepared_by_model_object(
5787
+		$values_already_prepared = self::not_prepared_by_model_object
5788
+	) {
5789
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5790
+	}
5791
+
5792
+
5793
+
5794
+	/**
5795
+	 * Read comments for assume_values_already_prepared_by_model_object()
5796
+	 *
5797
+	 * @return int
5798
+	 */
5799
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5800
+	{
5801
+		return $this->_values_already_prepared_by_model_object;
5802
+	}
5803
+
5804
+
5805
+
5806
+	/**
5807
+	 * Gets all the indexes on this model
5808
+	 *
5809
+	 * @return EE_Index[]
5810
+	 */
5811
+	public function indexes()
5812
+	{
5813
+		return $this->_indexes;
5814
+	}
5815
+
5816
+
5817
+
5818
+	/**
5819
+	 * Gets all the Unique Indexes on this model
5820
+	 *
5821
+	 * @return EE_Unique_Index[]
5822
+	 */
5823
+	public function unique_indexes()
5824
+	{
5825
+		$unique_indexes = array();
5826
+		foreach ($this->_indexes as $name => $index) {
5827
+			if ($index instanceof EE_Unique_Index) {
5828
+				$unique_indexes [ $name ] = $index;
5829
+			}
5830
+		}
5831
+		return $unique_indexes;
5832
+	}
5833
+
5834
+
5835
+
5836
+	/**
5837
+	 * Gets all the fields which, when combined, make the primary key.
5838
+	 * This is usually just an array with 1 element (the primary key), but in cases
5839
+	 * where there is no primary key, it's a combination of fields as defined
5840
+	 * on a primary index
5841
+	 *
5842
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5843
+	 * @throws EE_Error
5844
+	 */
5845
+	public function get_combined_primary_key_fields()
5846
+	{
5847
+		foreach ($this->indexes() as $index) {
5848
+			if ($index instanceof EE_Primary_Key_Index) {
5849
+				return $index->fields();
5850
+			}
5851
+		}
5852
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5853
+	}
5854
+
5855
+
5856
+
5857
+	/**
5858
+	 * Used to build a primary key string (when the model has no primary key),
5859
+	 * which can be used a unique string to identify this model object.
5860
+	 *
5861
+	 * @param array $fields_n_values keys are field names, values are their values.
5862
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5863
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5864
+	 *                               before passing it to this function (that will convert it from columns-n-values
5865
+	 *                               to field-names-n-values).
5866
+	 * @return string
5867
+	 * @throws EE_Error
5868
+	 */
5869
+	public function get_index_primary_key_string($fields_n_values)
5870
+	{
5871
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5872
+			$fields_n_values,
5873
+			$this->get_combined_primary_key_fields()
5874
+		);
5875
+		return http_build_query($cols_n_values_for_primary_key_index);
5876
+	}
5877
+
5878
+
5879
+
5880
+	/**
5881
+	 * Gets the field values from the primary key string
5882
+	 *
5883
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5884
+	 * @param string $index_primary_key_string
5885
+	 * @return null|array
5886
+	 * @throws EE_Error
5887
+	 */
5888
+	public function parse_index_primary_key_string($index_primary_key_string)
5889
+	{
5890
+		$key_fields = $this->get_combined_primary_key_fields();
5891
+		// check all of them are in the $id
5892
+		$key_vals_in_combined_pk = array();
5893
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5894
+		foreach ($key_fields as $key_field_name => $field_obj) {
5895
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5896
+				return null;
5897
+			}
5898
+		}
5899
+		return $key_vals_in_combined_pk;
5900
+	}
5901
+
5902
+
5903
+
5904
+	/**
5905
+	 * verifies that an array of key-value pairs for model fields has a key
5906
+	 * for each field comprising the primary key index
5907
+	 *
5908
+	 * @param array $key_vals
5909
+	 * @return boolean
5910
+	 * @throws EE_Error
5911
+	 */
5912
+	public function has_all_combined_primary_key_fields($key_vals)
5913
+	{
5914
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5915
+		foreach ($keys_it_should_have as $key) {
5916
+			if (! isset($key_vals[ $key ])) {
5917
+				return false;
5918
+			}
5919
+		}
5920
+		return true;
5921
+	}
5922
+
5923
+
5924
+
5925
+	/**
5926
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5927
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5928
+	 *
5929
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5930
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5931
+	 * @throws EE_Error
5932
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5933
+	 *                                                              indexed)
5934
+	 */
5935
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5936
+	{
5937
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5938
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5939
+		} elseif (is_array($model_object_or_attributes_array)) {
5940
+			$attributes_array = $model_object_or_attributes_array;
5941
+		} else {
5942
+			throw new EE_Error(sprintf(__(
5943
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5944
+				"event_espresso"
5945
+			), $model_object_or_attributes_array));
5946
+		}
5947
+		// even copies obviously won't have the same ID, so remove the primary key
5948
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5949
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5950
+			unset($attributes_array[ $this->primary_key_name() ]);
5951
+		}
5952
+		if (isset($query_params[0])) {
5953
+			$query_params[0] = array_merge($attributes_array, $query_params);
5954
+		} else {
5955
+			$query_params[0] = $attributes_array;
5956
+		}
5957
+		return $this->get_all($query_params);
5958
+	}
5959
+
5960
+
5961
+
5962
+	/**
5963
+	 * Gets the first copy we find. See get_all_copies for more details
5964
+	 *
5965
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5966
+	 * @param array $query_params
5967
+	 * @return EE_Base_Class
5968
+	 * @throws EE_Error
5969
+	 */
5970
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5971
+	{
5972
+		if (! is_array($query_params)) {
5973
+			EE_Error::doing_it_wrong(
5974
+				'EEM_Base::get_one_copy',
5975
+				sprintf(
5976
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5977
+					gettype($query_params)
5978
+				),
5979
+				'4.6.0'
5980
+			);
5981
+			$query_params = array();
5982
+		}
5983
+		$query_params['limit'] = 1;
5984
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5985
+		if (is_array($copies)) {
5986
+			return array_shift($copies);
5987
+		}
5988
+		return null;
5989
+	}
5990
+
5991
+
5992
+
5993
+	/**
5994
+	 * Updates the item with the specified id. Ignores default query parameters because
5995
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5996
+	 *
5997
+	 * @param array      $fields_n_values keys are field names, values are their new values
5998
+	 * @param int|string $id              the value of the primary key to update
5999
+	 * @return int number of rows updated
6000
+	 * @throws EE_Error
6001
+	 */
6002
+	public function update_by_ID($fields_n_values, $id)
6003
+	{
6004
+		$query_params = array(
6005
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
6006
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6007
+		);
6008
+		return $this->update($fields_n_values, $query_params);
6009
+	}
6010
+
6011
+
6012
+
6013
+	/**
6014
+	 * Changes an operator which was supplied to the models into one usable in SQL
6015
+	 *
6016
+	 * @param string $operator_supplied
6017
+	 * @return string an operator which can be used in SQL
6018
+	 * @throws EE_Error
6019
+	 */
6020
+	private function _prepare_operator_for_sql($operator_supplied)
6021
+	{
6022
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6023
+			: null;
6024
+		if ($sql_operator) {
6025
+			return $sql_operator;
6026
+		}
6027
+		throw new EE_Error(
6028
+			sprintf(
6029
+				__(
6030
+					"The operator '%s' is not in the list of valid operators: %s",
6031
+					"event_espresso"
6032
+				),
6033
+				$operator_supplied,
6034
+				implode(",", array_keys($this->_valid_operators))
6035
+			)
6036
+		);
6037
+	}
6038
+
6039
+
6040
+
6041
+	/**
6042
+	 * Gets the valid operators
6043
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6044
+	 */
6045
+	public function valid_operators()
6046
+	{
6047
+		return $this->_valid_operators;
6048
+	}
6049
+
6050
+
6051
+
6052
+	/**
6053
+	 * Gets the between-style operators (take 2 arguments).
6054
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6055
+	 */
6056
+	public function valid_between_style_operators()
6057
+	{
6058
+		return array_intersect(
6059
+			$this->valid_operators(),
6060
+			$this->_between_style_operators
6061
+		);
6062
+	}
6063
+
6064
+	/**
6065
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6066
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6067
+	 */
6068
+	public function valid_like_style_operators()
6069
+	{
6070
+		return array_intersect(
6071
+			$this->valid_operators(),
6072
+			$this->_like_style_operators
6073
+		);
6074
+	}
6075
+
6076
+	/**
6077
+	 * Gets the "in"-style operators
6078
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6079
+	 */
6080
+	public function valid_in_style_operators()
6081
+	{
6082
+		return array_intersect(
6083
+			$this->valid_operators(),
6084
+			$this->_in_style_operators
6085
+		);
6086
+	}
6087
+
6088
+	/**
6089
+	 * Gets the "null"-style operators (accept no arguments)
6090
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6091
+	 */
6092
+	public function valid_null_style_operators()
6093
+	{
6094
+		return array_intersect(
6095
+			$this->valid_operators(),
6096
+			$this->_null_style_operators
6097
+		);
6098
+	}
6099
+
6100
+	/**
6101
+	 * Gets an array where keys are the primary keys and values are their 'names'
6102
+	 * (as determined by the model object's name() function, which is often overridden)
6103
+	 *
6104
+	 * @param array $query_params like get_all's
6105
+	 * @return string[]
6106
+	 * @throws EE_Error
6107
+	 */
6108
+	public function get_all_names($query_params = array())
6109
+	{
6110
+		$objs = $this->get_all($query_params);
6111
+		$names = array();
6112
+		foreach ($objs as $obj) {
6113
+			$names[ $obj->ID() ] = $obj->name();
6114
+		}
6115
+		return $names;
6116
+	}
6117
+
6118
+
6119
+
6120
+	/**
6121
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6122
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6123
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6124
+	 * array_keys() on $model_objects.
6125
+	 *
6126
+	 * @param \EE_Base_Class[] $model_objects
6127
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6128
+	 *                                               in the returned array
6129
+	 * @return array
6130
+	 * @throws EE_Error
6131
+	 */
6132
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6133
+	{
6134
+		if (! $this->has_primary_key_field()) {
6135
+			if (WP_DEBUG) {
6136
+				EE_Error::add_error(
6137
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6138
+					__FILE__,
6139
+					__FUNCTION__,
6140
+					__LINE__
6141
+				);
6142
+			}
6143
+		}
6144
+		$IDs = array();
6145
+		foreach ($model_objects as $model_object) {
6146
+			$id = $model_object->ID();
6147
+			if (! $id) {
6148
+				if ($filter_out_empty_ids) {
6149
+					continue;
6150
+				}
6151
+				if (WP_DEBUG) {
6152
+					EE_Error::add_error(
6153
+						__(
6154
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6155
+							'event_espresso'
6156
+						),
6157
+						__FILE__,
6158
+						__FUNCTION__,
6159
+						__LINE__
6160
+					);
6161
+				}
6162
+			}
6163
+			$IDs[] = $id;
6164
+		}
6165
+		return $IDs;
6166
+	}
6167
+
6168
+
6169
+
6170
+	/**
6171
+	 * Returns the string used in capabilities relating to this model. If there
6172
+	 * are no capabilities that relate to this model returns false
6173
+	 *
6174
+	 * @return string|false
6175
+	 */
6176
+	public function cap_slug()
6177
+	{
6178
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6179
+	}
6180
+
6181
+
6182
+
6183
+	/**
6184
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6185
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6186
+	 * only returns the cap restrictions array in that context (ie, the array
6187
+	 * at that key)
6188
+	 *
6189
+	 * @param string $context
6190
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6191
+	 * @throws EE_Error
6192
+	 */
6193
+	public function cap_restrictions($context = EEM_Base::caps_read)
6194
+	{
6195
+		EEM_Base::verify_is_valid_cap_context($context);
6196
+		// check if we ought to run the restriction generator first
6197
+		if (
6198
+			isset($this->_cap_restriction_generators[ $context ])
6199
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6200
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6201
+		) {
6202
+			$this->_cap_restrictions[ $context ] = array_merge(
6203
+				$this->_cap_restrictions[ $context ],
6204
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6205
+			);
6206
+		}
6207
+		// and make sure we've finalized the construction of each restriction
6208
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6209
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6210
+				$where_conditions_obj->_finalize_construct($this);
6211
+			}
6212
+		}
6213
+		return $this->_cap_restrictions[ $context ];
6214
+	}
6215
+
6216
+
6217
+
6218
+	/**
6219
+	 * Indicating whether or not this model thinks its a wp core model
6220
+	 *
6221
+	 * @return boolean
6222
+	 */
6223
+	public function is_wp_core_model()
6224
+	{
6225
+		return $this->_wp_core_model;
6226
+	}
6227
+
6228
+
6229
+
6230
+	/**
6231
+	 * Gets all the caps that are missing which impose a restriction on
6232
+	 * queries made in this context
6233
+	 *
6234
+	 * @param string $context one of EEM_Base::caps_ constants
6235
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6236
+	 * @throws EE_Error
6237
+	 */
6238
+	public function caps_missing($context = EEM_Base::caps_read)
6239
+	{
6240
+		$missing_caps = array();
6241
+		$cap_restrictions = $this->cap_restrictions($context);
6242
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6243
+			if (
6244
+				! EE_Capabilities::instance()
6245
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6246
+			) {
6247
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6248
+			}
6249
+		}
6250
+		return $missing_caps;
6251
+	}
6252
+
6253
+
6254
+
6255
+	/**
6256
+	 * Gets the mapping from capability contexts to action strings used in capability names
6257
+	 *
6258
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6259
+	 * one of 'read', 'edit', or 'delete'
6260
+	 */
6261
+	public function cap_contexts_to_cap_action_map()
6262
+	{
6263
+		return apply_filters(
6264
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6265
+			$this->_cap_contexts_to_cap_action_map,
6266
+			$this
6267
+		);
6268
+	}
6269
+
6270
+
6271
+
6272
+	/**
6273
+	 * Gets the action string for the specified capability context
6274
+	 *
6275
+	 * @param string $context
6276
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6277
+	 * @throws EE_Error
6278
+	 */
6279
+	public function cap_action_for_context($context)
6280
+	{
6281
+		$mapping = $this->cap_contexts_to_cap_action_map();
6282
+		if (isset($mapping[ $context ])) {
6283
+			return $mapping[ $context ];
6284
+		}
6285
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6286
+			return $action;
6287
+		}
6288
+		throw new EE_Error(
6289
+			sprintf(
6290
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6291
+				$context,
6292
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6293
+			)
6294
+		);
6295
+	}
6296
+
6297
+
6298
+
6299
+	/**
6300
+	 * Returns all the capability contexts which are valid when querying models
6301
+	 *
6302
+	 * @return array
6303
+	 */
6304
+	public static function valid_cap_contexts()
6305
+	{
6306
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6307
+			self::caps_read,
6308
+			self::caps_read_admin,
6309
+			self::caps_edit,
6310
+			self::caps_delete,
6311
+		));
6312
+	}
6313
+
6314
+
6315
+
6316
+	/**
6317
+	 * Returns all valid options for 'default_where_conditions'
6318
+	 *
6319
+	 * @return array
6320
+	 */
6321
+	public static function valid_default_where_conditions()
6322
+	{
6323
+		return array(
6324
+			EEM_Base::default_where_conditions_all,
6325
+			EEM_Base::default_where_conditions_this_only,
6326
+			EEM_Base::default_where_conditions_others_only,
6327
+			EEM_Base::default_where_conditions_minimum_all,
6328
+			EEM_Base::default_where_conditions_minimum_others,
6329
+			EEM_Base::default_where_conditions_none
6330
+		);
6331
+	}
6332
+
6333
+	// public static function default_where_conditions_full
6334
+	/**
6335
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6336
+	 *
6337
+	 * @param string $context
6338
+	 * @return bool
6339
+	 * @throws EE_Error
6340
+	 */
6341
+	public static function verify_is_valid_cap_context($context)
6342
+	{
6343
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6344
+		if (in_array($context, $valid_cap_contexts)) {
6345
+			return true;
6346
+		}
6347
+		throw new EE_Error(
6348
+			sprintf(
6349
+				__(
6350
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6351
+					'event_espresso'
6352
+				),
6353
+				$context,
6354
+				'EEM_Base',
6355
+				implode(',', $valid_cap_contexts)
6356
+			)
6357
+		);
6358
+	}
6359
+
6360
+
6361
+
6362
+	/**
6363
+	 * Clears all the models field caches. This is only useful when a sub-class
6364
+	 * might have added a field or something and these caches might be invalidated
6365
+	 */
6366
+	protected function _invalidate_field_caches()
6367
+	{
6368
+		$this->_cache_foreign_key_to_fields = array();
6369
+		$this->_cached_fields = null;
6370
+		$this->_cached_fields_non_db_only = null;
6371
+	}
6372
+
6373
+
6374
+
6375
+	/**
6376
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6377
+	 * (eg "and", "or", "not").
6378
+	 *
6379
+	 * @return array
6380
+	 */
6381
+	public function logic_query_param_keys()
6382
+	{
6383
+		return $this->_logic_query_param_keys;
6384
+	}
6385
+
6386
+
6387
+
6388
+	/**
6389
+	 * Determines whether or not the where query param array key is for a logic query param.
6390
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6391
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6392
+	 *
6393
+	 * @param $query_param_key
6394
+	 * @return bool
6395
+	 */
6396
+	public function is_logic_query_param_key($query_param_key)
6397
+	{
6398
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6399
+			if (
6400
+				$query_param_key === $logic_query_param_key
6401
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6402
+			) {
6403
+				return true;
6404
+			}
6405
+		}
6406
+		return false;
6407
+	}
6408
+
6409
+	/**
6410
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6411
+	 * @since 4.9.74.p
6412
+	 * @return boolean
6413
+	 */
6414
+	public function hasPassword()
6415
+	{
6416
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6417
+		if ($this->has_password_field === null) {
6418
+			$password_field = $this->getPasswordField();
6419
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6420
+		}
6421
+		return $this->has_password_field;
6422
+	}
6423
+
6424
+	/**
6425
+	 * Returns the password field on this model, if there is one
6426
+	 * @since 4.9.74.p
6427
+	 * @return EE_Password_Field|null
6428
+	 */
6429
+	public function getPasswordField()
6430
+	{
6431
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6432
+		// there's no need to search for it. If we don't know yet, then find out
6433
+		if ($this->has_password_field === null && $this->password_field === null) {
6434
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6435
+		}
6436
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6437
+		return $this->password_field;
6438
+	}
6439
+
6440
+
6441
+	/**
6442
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6443
+	 * @since 4.9.74.p
6444
+	 * @return EE_Model_Field_Base[]
6445
+	 * @throws EE_Error
6446
+	 */
6447
+	public function getPasswordProtectedFields()
6448
+	{
6449
+		$password_field = $this->getPasswordField();
6450
+		$fields = array();
6451
+		if ($password_field instanceof EE_Password_Field) {
6452
+			$field_names = $password_field->protectedFields();
6453
+			foreach ($field_names as $field_name) {
6454
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6455
+			}
6456
+		}
6457
+		return $fields;
6458
+	}
6459
+
6460
+
6461
+	/**
6462
+	 * Checks if the current user can perform the requested action on this model
6463
+	 * @since 4.9.74.p
6464
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6465
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6466
+	 * @return bool
6467
+	 * @throws EE_Error
6468
+	 * @throws InvalidArgumentException
6469
+	 * @throws InvalidDataTypeException
6470
+	 * @throws InvalidInterfaceException
6471
+	 * @throws ReflectionException
6472
+	 * @throws UnexpectedEntityException
6473
+	 */
6474
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6475
+	{
6476
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6477
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6478
+		}
6479
+		if (!is_array($model_obj_or_fields_n_values)) {
6480
+			throw new UnexpectedEntityException(
6481
+				$model_obj_or_fields_n_values,
6482
+				'EE_Base_Class',
6483
+				sprintf(
6484
+					esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6485
+					__FUNCTION__
6486
+				)
6487
+			);
6488
+		}
6489
+		return $this->exists(
6490
+			$this->alter_query_params_to_restrict_by_ID(
6491
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6492
+				array(
6493
+					'default_where_conditions' => 'none',
6494
+					'caps'                     => $cap_to_check,
6495
+				)
6496
+			)
6497
+		);
6498
+	}
6499
+
6500
+	/**
6501
+	 * Returns the query param where conditions key to the password affecting this model.
6502
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6503
+	 * @since 4.9.74.p
6504
+	 * @return null|string
6505
+	 * @throws EE_Error
6506
+	 * @throws InvalidArgumentException
6507
+	 * @throws InvalidDataTypeException
6508
+	 * @throws InvalidInterfaceException
6509
+	 * @throws ModelConfigurationException
6510
+	 * @throws ReflectionException
6511
+	 */
6512
+	public function modelChainAndPassword()
6513
+	{
6514
+		if ($this->model_chain_to_password === null) {
6515
+			throw new ModelConfigurationException(
6516
+				$this,
6517
+				esc_html_x(
6518
+				// @codingStandardsIgnoreStart
6519
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6520
+					// @codingStandardsIgnoreEnd
6521
+					'1: model name',
6522
+					'event_espresso'
6523
+				)
6524
+			);
6525
+		}
6526
+		if ($this->model_chain_to_password === '') {
6527
+			$model_with_password = $this;
6528
+		} else {
6529
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6530
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6531
+			} else {
6532
+				$last_model_in_chain = $this->model_chain_to_password;
6533
+			}
6534
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6535
+		}
6536
+
6537
+		$password_field = $model_with_password->getPasswordField();
6538
+		if ($password_field instanceof EE_Password_Field) {
6539
+			$password_field_name = $password_field->get_name();
6540
+		} else {
6541
+			throw new ModelConfigurationException(
6542
+				$this,
6543
+				sprintf(
6544
+					esc_html_x(
6545
+						'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"',
6546
+						'1: model name, 2: special string',
6547
+						'event_espresso'
6548
+					),
6549
+					$model_with_password->get_this_model_name(),
6550
+					$this->model_chain_to_password
6551
+				)
6552
+			);
6553
+		}
6554
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6555
+	}
6556
+
6557
+	/**
6558
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6559
+	 * or if this model itself has a password affecting access to some of its other fields.
6560
+	 * @since 4.9.74.p
6561
+	 * @return boolean
6562
+	 */
6563
+	public function restrictedByRelatedModelPassword()
6564
+	{
6565
+		return $this->model_chain_to_password !== null;
6566
+	}
6567 6567
 }
Please login to merge, or discard this patch.
Spacing   +228 added lines, -228 removed lines patch added patch discarded remove patch
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
     protected function __construct($timezone = null)
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
                     __(
@@ -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);
@@ -603,10 +603,10 @@  discard block
 block discarded – undo
603 603
          *
604 604
          * @param EE_Model_Field_Base[] $_fields
605 605
          */
606
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
606
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
607 607
         $this->_invalidate_field_caches();
608 608
         foreach ($this->_fields as $table_alias => $fields_for_table) {
609
-            if (! array_key_exists($table_alias, $this->_tables)) {
609
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
610 610
                 throw new EE_Error(sprintf(__(
611 611
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
612 612
                     'event_espresso'
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
          * @param EE_Model_Relation_Base[] $_model_relations
638 638
          */
639 639
         $this->_model_relations = (array) apply_filters(
640
-            'FHEE__' . get_class($this) . '__construct__model_relations',
640
+            'FHEE__'.get_class($this).'__construct__model_relations',
641 641
             $this->_model_relations
642 642
         );
643 643
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -649,12 +649,12 @@  discard block
 block discarded – undo
649 649
         }
650 650
         $this->set_timezone($timezone);
651 651
         // finalize default where condition strategy, or set default
652
-        if (! $this->_default_where_conditions_strategy) {
652
+        if ( ! $this->_default_where_conditions_strategy) {
653 653
             // nothing was set during child constructor, so set default
654 654
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
655 655
         }
656 656
         $this->_default_where_conditions_strategy->_finalize_construct($this);
657
-        if (! $this->_minimum_where_conditions_strategy) {
657
+        if ( ! $this->_minimum_where_conditions_strategy) {
658 658
             // nothing was set during child constructor, so set default
659 659
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
660 660
         }
@@ -667,8 +667,8 @@  discard block
 block discarded – undo
667 667
         // initialize the standard cap restriction generators if none were specified by the child constructor
668 668
         if (is_array($this->_cap_restriction_generators)) {
669 669
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
670
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
671
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
670
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
671
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
672 672
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
673 673
                         new EE_Restriction_Generator_Protected(),
674 674
                         $cap_context,
@@ -680,10 +680,10 @@  discard block
 block discarded – undo
680 680
         // if there are cap restriction generators, use them to make the default cap restrictions
681 681
         if (is_array($this->_cap_restriction_generators)) {
682 682
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
683
-                if (! $generator_object) {
683
+                if ( ! $generator_object) {
684 684
                     continue;
685 685
                 }
686
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
686
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
687 687
                     throw new EE_Error(
688 688
                         sprintf(
689 689
                             __(
@@ -696,12 +696,12 @@  discard block
 block discarded – undo
696 696
                     );
697 697
                 }
698 698
                 $action = $this->cap_action_for_context($context);
699
-                if (! $generator_object->construction_finalized()) {
699
+                if ( ! $generator_object->construction_finalized()) {
700 700
                     $generator_object->_construct_finalize($this, $action);
701 701
                 }
702 702
             }
703 703
         }
704
-        do_action('AHEE__' . get_class($this) . '__construct__end');
704
+        do_action('AHEE__'.get_class($this).'__construct__end');
705 705
     }
706 706
 
707 707
 
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
      */
714 714
     protected static function getLoader(): LoaderInterface
715 715
     {
716
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
716
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
717 717
             EEM_Base::$loader = LoaderFactory::getLoader();
718 718
         }
719 719
         return EEM_Base::$loader;
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
      */
727 727
     private static function getMirror(): Mirror
728 728
     {
729
-        if (! EEM_Base::$mirror instanceof Mirror) {
729
+        if ( ! EEM_Base::$mirror instanceof Mirror) {
730 730
             EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
731 731
         }
732 732
         return EEM_Base::$mirror;
@@ -782,7 +782,7 @@  discard block
 block discarded – undo
782 782
     public static function instance($timezone = null)
783 783
     {
784 784
         // check if instance of Espresso_model already exists
785
-        if (! static::$_instance instanceof static) {
785
+        if ( ! static::$_instance instanceof static) {
786 786
             $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
787 787
             $model = new static(...$arguments);
788 788
             EEM_Base::getLoader()->share(static::class, $model, $arguments);
@@ -812,7 +812,7 @@  discard block
 block discarded – undo
812 812
      */
813 813
     public static function reset($timezone = null)
814 814
     {
815
-        if (! static::$_instance instanceof EEM_Base) {
815
+        if ( ! static::$_instance instanceof EEM_Base) {
816 816
             return null;
817 817
         }
818 818
         // Let's NOT swap out the current instance for a new one
@@ -823,7 +823,7 @@  discard block
 block discarded – undo
823 823
         foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
824 824
             // don't set instance to null like it was originally,
825 825
             // but it's static anyways, and we're ignoring static properties (for now at least)
826
-            if (! isset($static_properties[ $property ])) {
826
+            if ( ! isset($static_properties[$property])) {
827 827
                 static::$_instance->{$property} = $value;
828 828
             }
829 829
         }
@@ -872,7 +872,7 @@  discard block
 block discarded – undo
872 872
      */
873 873
     public function status_array($translated = false)
874 874
     {
875
-        if (! array_key_exists('Status', $this->_model_relations)) {
875
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
876 876
             return array();
877 877
         }
878 878
         $model_name = $this->get_this_model_name();
@@ -880,7 +880,7 @@  discard block
 block discarded – undo
880 880
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
881 881
         $status_array = array();
882 882
         foreach ($stati as $status) {
883
-            $status_array[ $status->ID() ] = $status->get('STS_code');
883
+            $status_array[$status->ID()] = $status->get('STS_code');
884 884
         }
885 885
         return $translated
886 886
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -941,7 +941,7 @@  discard block
 block discarded – undo
941 941
     {
942 942
         $wp_user_field_name = $this->wp_user_field_name();
943 943
         if ($wp_user_field_name) {
944
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
944
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
945 945
         }
946 946
         return $query_params;
947 947
     }
@@ -959,17 +959,17 @@  discard block
 block discarded – undo
959 959
     public function wp_user_field_name()
960 960
     {
961 961
         try {
962
-            if (! empty($this->_model_chain_to_wp_user)) {
962
+            if ( ! empty($this->_model_chain_to_wp_user)) {
963 963
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
964 964
                 $last_model_name = end($models_to_follow_to_wp_users);
965 965
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
966
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
966
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
967 967
             } else {
968 968
                 $model_with_fk_to_wp_users = $this;
969 969
                 $model_chain_to_wp_user = '';
970 970
             }
971 971
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
972
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
972
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
973 973
         } catch (EE_Error $e) {
974 974
             return false;
975 975
         }
@@ -1045,11 +1045,11 @@  discard block
 block discarded – undo
1045 1045
         if ($this->_custom_selections instanceof CustomSelects) {
1046 1046
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1047 1047
             $select_expressions .= $select_expressions
1048
-                ? ', ' . $custom_expressions
1048
+                ? ', '.$custom_expressions
1049 1049
                 : $custom_expressions;
1050 1050
         }
1051 1051
 
1052
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1052
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1053 1053
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1054 1054
     }
1055 1055
 
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
      */
1067 1067
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1068 1068
     {
1069
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1069
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1070 1070
             return null;
1071 1071
         }
1072 1072
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1115,7 +1115,7 @@  discard block
 block discarded – undo
1115 1115
         if (is_array($columns_to_select)) {
1116 1116
             $select_sql_array = array();
1117 1117
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1118
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1118
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1119 1119
                     throw new EE_Error(
1120 1120
                         sprintf(
1121 1121
                             __(
@@ -1127,7 +1127,7 @@  discard block
 block discarded – undo
1127 1127
                         )
1128 1128
                     );
1129 1129
                 }
1130
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1130
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1131 1131
                     throw new EE_Error(
1132 1132
                         sprintf(
1133 1133
                             esc_html__(
@@ -1206,12 +1206,12 @@  discard block
 block discarded – undo
1206 1206
      */
1207 1207
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1208 1208
     {
1209
-        if (! isset($query_params[0])) {
1209
+        if ( ! isset($query_params[0])) {
1210 1210
             $query_params[0] = array();
1211 1211
         }
1212 1212
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1213 1213
         if ($conditions_from_id === null) {
1214
-            $query_params[0][ $this->primary_key_name() ] = $id;
1214
+            $query_params[0][$this->primary_key_name()] = $id;
1215 1215
         } else {
1216 1216
             // no primary key, so the $id must be from the get_index_primary_key_string()
1217 1217
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1231,7 +1231,7 @@  discard block
 block discarded – undo
1231 1231
      */
1232 1232
     public function get_one($query_params = array())
1233 1233
     {
1234
-        if (! is_array($query_params)) {
1234
+        if ( ! is_array($query_params)) {
1235 1235
             EE_Error::doing_it_wrong(
1236 1236
                 'EEM_Base::get_one',
1237 1237
                 sprintf(
@@ -1429,7 +1429,7 @@  discard block
 block discarded – undo
1429 1429
                 return array();
1430 1430
             }
1431 1431
         }
1432
-        if (! is_array($query_params)) {
1432
+        if ( ! is_array($query_params)) {
1433 1433
             EE_Error::doing_it_wrong(
1434 1434
                 'EEM_Base::_get_consecutive',
1435 1435
                 sprintf(
@@ -1441,7 +1441,7 @@  discard block
 block discarded – undo
1441 1441
             $query_params = array();
1442 1442
         }
1443 1443
         // let's add the where query param for consecutive look up.
1444
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1444
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1445 1445
         $query_params['limit'] = $limit;
1446 1446
         // set direction
1447 1447
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1522,7 +1522,7 @@  discard block
 block discarded – undo
1522 1522
     {
1523 1523
         $field_settings = $this->field_settings_for($field_name);
1524 1524
         // if not a valid EE_Datetime_Field then throw error
1525
-        if (! $field_settings instanceof EE_Datetime_Field) {
1525
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1526 1526
             throw new EE_Error(sprintf(__(
1527 1527
                 '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.',
1528 1528
                 'event_espresso'
@@ -1671,7 +1671,7 @@  discard block
 block discarded – undo
1671 1671
      */
1672 1672
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1673 1673
     {
1674
-        if (! is_array($query_params)) {
1674
+        if ( ! is_array($query_params)) {
1675 1675
             EE_Error::doing_it_wrong(
1676 1676
                 'EEM_Base::update',
1677 1677
                 sprintf(
@@ -1719,7 +1719,7 @@  discard block
 block discarded – undo
1719 1719
             $wpdb_result = (array) $wpdb_result;
1720 1720
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1721 1721
             if ($this->has_primary_key_field()) {
1722
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1722
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1723 1723
             } else {
1724 1724
                 // 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)
1725 1725
                 $main_table_pk_value = null;
@@ -1735,7 +1735,7 @@  discard block
 block discarded – undo
1735 1735
                     // in this table, right? so insert a row in the current table, using any fields available
1736 1736
                     if (
1737 1737
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1738
-                           && $wpdb_result[ $this_table_pk_column ])
1738
+                           && $wpdb_result[$this_table_pk_column])
1739 1739
                     ) {
1740 1740
                         $success = $this->_insert_into_specific_table(
1741 1741
                             $table_obj,
@@ -1743,7 +1743,7 @@  discard block
 block discarded – undo
1743 1743
                             $main_table_pk_value
1744 1744
                         );
1745 1745
                         // if we died here, report the error
1746
-                        if (! $success) {
1746
+                        if ( ! $success) {
1747 1747
                             return false;
1748 1748
                         }
1749 1749
                     }
@@ -1771,10 +1771,10 @@  discard block
 block discarded – undo
1771 1771
                 $model_objs_affected_ids = array();
1772 1772
                 foreach ($models_affected_key_columns as $row) {
1773 1773
                     $combined_index_key = $this->get_index_primary_key_string($row);
1774
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1774
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1775 1775
                 }
1776 1776
             }
1777
-            if (! $model_objs_affected_ids) {
1777
+            if ( ! $model_objs_affected_ids) {
1778 1778
                 // wait wait wait- if nothing was affected let's stop here
1779 1779
                 return 0;
1780 1780
             }
@@ -1801,7 +1801,7 @@  discard block
 block discarded – undo
1801 1801
                . $model_query_info->get_full_join_sql()
1802 1802
                . " SET "
1803 1803
                . $this->_construct_update_sql($fields_n_values)
1804
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1804
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1805 1805
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1806 1806
         /**
1807 1807
          * Action called after a model update call has been made.
@@ -1812,7 +1812,7 @@  discard block
 block discarded – undo
1812 1812
          * @param int      $rows_affected
1813 1813
          */
1814 1814
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1815
-        return $rows_affected;// how many supposedly got updated
1815
+        return $rows_affected; // how many supposedly got updated
1816 1816
     }
1817 1817
 
1818 1818
 
@@ -1840,7 +1840,7 @@  discard block
 block discarded – undo
1840 1840
         }
1841 1841
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1842 1842
         $select_expressions = $field->get_qualified_column();
1843
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1843
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1844 1844
         return $this->_do_wpdb_query('get_col', array($SQL));
1845 1845
     }
1846 1846
 
@@ -1858,7 +1858,7 @@  discard block
 block discarded – undo
1858 1858
     {
1859 1859
         $query_params['limit'] = 1;
1860 1860
         $col = $this->get_col($query_params, $field_to_select);
1861
-        if (! empty($col)) {
1861
+        if ( ! empty($col)) {
1862 1862
             return reset($col);
1863 1863
         }
1864 1864
         return null;
@@ -1889,7 +1889,7 @@  discard block
 block discarded – undo
1889 1889
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1890 1890
             $value_sql = $prepared_value === null ? 'NULL'
1891 1891
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1892
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1892
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1893 1893
         }
1894 1894
         return implode(",", $cols_n_values);
1895 1895
     }
@@ -2033,12 +2033,12 @@  discard block
 block discarded – undo
2033 2033
         if (
2034 2034
             $this->has_primary_key_field()
2035 2035
             && $rows_deleted !== false
2036
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2036
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2037 2037
         ) {
2038
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2038
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2039 2039
             foreach ($ids_for_removal as $id) {
2040
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2041
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2040
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2041
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2042 2042
                 }
2043 2043
             }
2044 2044
 
@@ -2075,7 +2075,7 @@  discard block
 block discarded – undo
2075 2075
          * @param int      $rows_deleted
2076 2076
          */
2077 2077
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2078
-        return $rows_deleted;// how many supposedly got deleted
2078
+        return $rows_deleted; // how many supposedly got deleted
2079 2079
     }
2080 2080
 
2081 2081
 
@@ -2169,15 +2169,15 @@  discard block
 block discarded – undo
2169 2169
                 if (
2170 2170
                     $allow_blocking
2171 2171
                     && $this->delete_is_blocked_by_related_models(
2172
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2172
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2173 2173
                     )
2174 2174
                 ) {
2175 2175
                     continue;
2176 2176
                 }
2177 2177
                 // primary table deletes
2178
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2179
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2180
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2178
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2179
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2180
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2181 2181
                 }
2182 2182
             }
2183 2183
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2186,8 +2186,8 @@  discard block
 block discarded – undo
2186 2186
                 $ids_to_delete_indexed_by_column_for_row = array();
2187 2187
                 foreach ($fields as $cpk_field) {
2188 2188
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2189
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2190
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2189
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2190
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2191 2191
                     }
2192 2192
                 }
2193 2193
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2225,7 +2225,7 @@  discard block
 block discarded – undo
2225 2225
         } elseif ($this->has_primary_key_field()) {
2226 2226
             $query = array();
2227 2227
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2228
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2228
+                $query[] = $column.' IN'.$this->_construct_in_value($ids, $this->_primary_key_field);
2229 2229
             }
2230 2230
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2231 2231
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2233,7 +2233,7 @@  discard block
 block discarded – undo
2233 2233
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2234 2234
                 $values_for_each_combined_primary_key_for_a_row = array();
2235 2235
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2236
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2236
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2237 2237
                 }
2238 2238
                 $ways_to_identify_a_row[] = '('
2239 2239
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2305,8 +2305,8 @@  discard block
 block discarded – undo
2305 2305
                 $column_to_count = '*';
2306 2306
             }
2307 2307
         }
2308
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2309
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2308
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2309
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2310 2310
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2311 2311
     }
2312 2312
 
@@ -2329,7 +2329,7 @@  discard block
 block discarded – undo
2329 2329
             $field_obj = $this->get_primary_key_field();
2330 2330
         }
2331 2331
         $column_to_count = $field_obj->get_qualified_column();
2332
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2332
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2333 2333
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2334 2334
         $data_type = $field_obj->get_wpdb_data_type();
2335 2335
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2356,7 +2356,7 @@  discard block
 block discarded – undo
2356 2356
         // if we're in maintenance mode level 2, DON'T run any queries
2357 2357
         // because level 2 indicates the database needs updating and
2358 2358
         // is probably out of sync with the code
2359
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2359
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2360 2360
             throw new EE_Error(sprintf(__(
2361 2361
                 "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.",
2362 2362
                 "event_espresso"
@@ -2364,7 +2364,7 @@  discard block
 block discarded – undo
2364 2364
         }
2365 2365
         /** @type WPDB $wpdb */
2366 2366
         global $wpdb;
2367
-        if (! method_exists($wpdb, $wpdb_method)) {
2367
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2368 2368
             throw new EE_Error(sprintf(__(
2369 2369
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2370 2370
                 'event_espresso'
@@ -2378,7 +2378,7 @@  discard block
 block discarded – undo
2378 2378
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2379 2379
         if (WP_DEBUG) {
2380 2380
             $wpdb->show_errors($old_show_errors_value);
2381
-            if (! empty($wpdb->last_error)) {
2381
+            if ( ! empty($wpdb->last_error)) {
2382 2382
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2383 2383
             }
2384 2384
             if ($result === false) {
@@ -2444,7 +2444,7 @@  discard block
 block discarded – undo
2444 2444
                     return $result;
2445 2445
                     break;
2446 2446
             }
2447
-            if (! empty($error_message)) {
2447
+            if ( ! empty($error_message)) {
2448 2448
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2449 2449
                 trigger_error($error_message);
2450 2450
             }
@@ -2524,11 +2524,11 @@  discard block
 block discarded – undo
2524 2524
      */
2525 2525
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2526 2526
     {
2527
-        return " FROM " . $model_query_info->get_full_join_sql() .
2528
-               $model_query_info->get_where_sql() .
2529
-               $model_query_info->get_group_by_sql() .
2530
-               $model_query_info->get_having_sql() .
2531
-               $model_query_info->get_order_by_sql() .
2527
+        return " FROM ".$model_query_info->get_full_join_sql().
2528
+               $model_query_info->get_where_sql().
2529
+               $model_query_info->get_group_by_sql().
2530
+               $model_query_info->get_having_sql().
2531
+               $model_query_info->get_order_by_sql().
2532 2532
                $model_query_info->get_limit_sql();
2533 2533
     }
2534 2534
 
@@ -2724,12 +2724,12 @@  discard block
 block discarded – undo
2724 2724
         $related_model = $this->get_related_model_obj($model_name);
2725 2725
         // we're just going to use the query params on the related model's normal get_all query,
2726 2726
         // except add a condition to say to match the current mod
2727
-        if (! isset($query_params['default_where_conditions'])) {
2727
+        if ( ! isset($query_params['default_where_conditions'])) {
2728 2728
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2729 2729
         }
2730 2730
         $this_model_name = $this->get_this_model_name();
2731 2731
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2732
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2732
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2733 2733
         return $related_model->count($query_params, $field_to_count, $distinct);
2734 2734
     }
2735 2735
 
@@ -2749,7 +2749,7 @@  discard block
 block discarded – undo
2749 2749
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2750 2750
     {
2751 2751
         $related_model = $this->get_related_model_obj($model_name);
2752
-        if (! is_array($query_params)) {
2752
+        if ( ! is_array($query_params)) {
2753 2753
             EE_Error::doing_it_wrong(
2754 2754
                 'EEM_Base::sum_related',
2755 2755
                 sprintf(
@@ -2762,12 +2762,12 @@  discard block
 block discarded – undo
2762 2762
         }
2763 2763
         // we're just going to use the query params on the related model's normal get_all query,
2764 2764
         // except add a condition to say to match the current mod
2765
-        if (! isset($query_params['default_where_conditions'])) {
2765
+        if ( ! isset($query_params['default_where_conditions'])) {
2766 2766
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2767 2767
         }
2768 2768
         $this_model_name = $this->get_this_model_name();
2769 2769
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2770
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2770
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2771 2771
         return $related_model->sum($query_params, $field_to_sum);
2772 2772
     }
2773 2773
 
@@ -2820,7 +2820,7 @@  discard block
 block discarded – undo
2820 2820
                 $field_with_model_name = $field;
2821 2821
             }
2822 2822
         }
2823
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2823
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2824 2824
             throw new EE_Error(sprintf(
2825 2825
                 __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2826 2826
                 $this->get_this_model_name()
@@ -2957,13 +2957,13 @@  discard block
 block discarded – undo
2957 2957
                 || $this->get_primary_key_field()
2958 2958
                    instanceof
2959 2959
                    EE_Primary_Key_String_Field)
2960
-            && isset($fields_n_values[ $this->primary_key_name() ])
2960
+            && isset($fields_n_values[$this->primary_key_name()])
2961 2961
         ) {
2962
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2962
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2963 2963
         }
2964 2964
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2965 2965
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2966
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2966
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2967 2967
         }
2968 2968
         // if there is nothing to base this search on, then we shouldn't find anything
2969 2969
         if (empty($query_params)) {
@@ -3041,15 +3041,15 @@  discard block
 block discarded – undo
3041 3041
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3042 3042
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3043 3043
             if ($prepared_value !== null) {
3044
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3044
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3045 3045
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3046 3046
             }
3047 3047
         }
3048 3048
         if ($table instanceof EE_Secondary_Table && $new_id) {
3049 3049
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3050 3050
             // so add the fk to the main table as a column
3051
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3052
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3051
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3052
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
3053 3053
         }
3054 3054
         // insert the new entry
3055 3055
         $result = $this->_do_wpdb_query(
@@ -3066,7 +3066,7 @@  discard block
 block discarded – undo
3066 3066
             }
3067 3067
             // it's not an auto-increment primary key, so
3068 3068
             // it must have been supplied
3069
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3069
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3070 3070
         }
3071 3071
         // we can't return a  primary key because there is none. instead return
3072 3072
         // a unique string indicating this model
@@ -3091,14 +3091,14 @@  discard block
 block discarded – undo
3091 3091
         if (
3092 3092
             ! $field_obj->is_nullable()
3093 3093
             && (
3094
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3095
-                || $fields_n_values[ $field_obj->get_name() ] === null
3094
+                ! isset($fields_n_values[$field_obj->get_name()])
3095
+                || $fields_n_values[$field_obj->get_name()] === null
3096 3096
             )
3097 3097
         ) {
3098
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3098
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3099 3099
         }
3100
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3101
-            ? $fields_n_values[ $field_obj->get_name() ]
3100
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3101
+            ? $fields_n_values[$field_obj->get_name()]
3102 3102
             : null;
3103 3103
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3104 3104
     }
@@ -3201,7 +3201,7 @@  discard block
 block discarded – undo
3201 3201
      */
3202 3202
     public function get_table_obj_by_alias($table_alias = '')
3203 3203
     {
3204
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3204
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3205 3205
     }
3206 3206
 
3207 3207
 
@@ -3216,7 +3216,7 @@  discard block
 block discarded – undo
3216 3216
         $other_tables = array();
3217 3217
         foreach ($this->_tables as $table_alias => $table) {
3218 3218
             if ($table instanceof EE_Secondary_Table) {
3219
-                $other_tables[ $table_alias ] = $table;
3219
+                $other_tables[$table_alias] = $table;
3220 3220
             }
3221 3221
         }
3222 3222
         return $other_tables;
@@ -3232,7 +3232,7 @@  discard block
 block discarded – undo
3232 3232
      */
3233 3233
     public function _get_fields_for_table($table_alias)
3234 3234
     {
3235
-        return $this->_fields[ $table_alias ];
3235
+        return $this->_fields[$table_alias];
3236 3236
     }
3237 3237
 
3238 3238
 
@@ -3261,7 +3261,7 @@  discard block
 block discarded – undo
3261 3261
                     $query_info_carrier,
3262 3262
                     'group_by'
3263 3263
                 );
3264
-            } elseif (! empty($query_params['group_by'])) {
3264
+            } elseif ( ! empty($query_params['group_by'])) {
3265 3265
                 $this->_extract_related_model_info_from_query_param(
3266 3266
                     $query_params['group_by'],
3267 3267
                     $query_info_carrier,
@@ -3283,7 +3283,7 @@  discard block
 block discarded – undo
3283 3283
                     $query_info_carrier,
3284 3284
                     'order_by'
3285 3285
                 );
3286
-            } elseif (! empty($query_params['order_by'])) {
3286
+            } elseif ( ! empty($query_params['order_by'])) {
3287 3287
                 $this->_extract_related_model_info_from_query_param(
3288 3288
                     $query_params['order_by'],
3289 3289
                     $query_info_carrier,
@@ -3318,7 +3318,7 @@  discard block
 block discarded – undo
3318 3318
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3319 3319
         $query_param_type
3320 3320
     ) {
3321
-        if (! empty($sub_query_params)) {
3321
+        if ( ! empty($sub_query_params)) {
3322 3322
             $sub_query_params = (array) $sub_query_params;
3323 3323
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3324 3324
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3333,7 +3333,7 @@  discard block
 block discarded – undo
3333 3333
                 // of array('Registration.TXN_ID'=>23)
3334 3334
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3335 3335
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3336
-                    if (! is_array($possibly_array_of_params)) {
3336
+                    if ( ! is_array($possibly_array_of_params)) {
3337 3337
                         throw new EE_Error(sprintf(
3338 3338
                             __(
3339 3339
                                 "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'))",
@@ -3357,7 +3357,7 @@  discard block
 block discarded – undo
3357 3357
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3358 3358
                     // indicating that $possible_array_of_params[1] is actually a field name,
3359 3359
                     // from which we should extract query parameters!
3360
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3360
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3361 3361
                         throw new EE_Error(sprintf(__(
3362 3362
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3363 3363
                             "event_espresso"
@@ -3391,8 +3391,8 @@  discard block
 block discarded – undo
3391 3391
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3392 3392
         $query_param_type
3393 3393
     ) {
3394
-        if (! empty($sub_query_params)) {
3395
-            if (! is_array($sub_query_params)) {
3394
+        if ( ! empty($sub_query_params)) {
3395
+            if ( ! is_array($sub_query_params)) {
3396 3396
                 throw new EE_Error(sprintf(
3397 3397
                     __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3398 3398
                     $sub_query_params
@@ -3426,7 +3426,7 @@  discard block
 block discarded – undo
3426 3426
      */
3427 3427
     public function _create_model_query_info_carrier($query_params)
3428 3428
     {
3429
-        if (! is_array($query_params)) {
3429
+        if ( ! is_array($query_params)) {
3430 3430
             EE_Error::doing_it_wrong(
3431 3431
                 'EEM_Base::_create_model_query_info_carrier',
3432 3432
                 sprintf(
@@ -3457,7 +3457,7 @@  discard block
 block discarded – undo
3457 3457
             // only include if related to a cpt where no password has been set
3458 3458
             $query_params[0]['OR*nopassword'] = array(
3459 3459
                 $where_param_key_for_password => '',
3460
-                $where_param_key_for_password . '*' => array('IS_NULL')
3460
+                $where_param_key_for_password.'*' => array('IS_NULL')
3461 3461
             );
3462 3462
         }
3463 3463
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3511,7 +3511,7 @@  discard block
 block discarded – undo
3511 3511
         // set limit
3512 3512
         if (array_key_exists('limit', $query_params)) {
3513 3513
             if (is_array($query_params['limit'])) {
3514
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3514
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3515 3515
                     $e = sprintf(
3516 3516
                         __(
3517 3517
                             "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)",
@@ -3519,12 +3519,12 @@  discard block
 block discarded – undo
3519 3519
                         ),
3520 3520
                         http_build_query($query_params['limit'])
3521 3521
                     );
3522
-                    throw new EE_Error($e . "|" . $e);
3522
+                    throw new EE_Error($e."|".$e);
3523 3523
                 }
3524 3524
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3525
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3526
-            } elseif (! empty($query_params['limit'])) {
3527
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3525
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3526
+            } elseif ( ! empty($query_params['limit'])) {
3527
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3528 3528
             }
3529 3529
         }
3530 3530
         // set order by
@@ -3556,10 +3556,10 @@  discard block
 block discarded – undo
3556 3556
                 $order_array = array();
3557 3557
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3558 3558
                     $order = $this->_extract_order($order);
3559
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3559
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3560 3560
                 }
3561
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3562
-            } elseif (! empty($query_params['order_by'])) {
3561
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3562
+            } elseif ( ! empty($query_params['order_by'])) {
3563 3563
                 $this->_extract_related_model_info_from_query_param(
3564 3564
                     $query_params['order_by'],
3565 3565
                     $query_object,
@@ -3570,7 +3570,7 @@  discard block
 block discarded – undo
3570 3570
                     ? $this->_extract_order($query_params['order'])
3571 3571
                     : 'DESC';
3572 3572
                 $query_object->set_order_by_sql(
3573
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3573
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3574 3574
                 );
3575 3575
             }
3576 3576
         }
@@ -3582,7 +3582,7 @@  discard block
 block discarded – undo
3582 3582
         ) {
3583 3583
             $pk_field = $this->get_primary_key_field();
3584 3584
             $order = $this->_extract_order($query_params['order']);
3585
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3585
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3586 3586
         }
3587 3587
         // set group by
3588 3588
         if (array_key_exists('group_by', $query_params)) {
@@ -3592,10 +3592,10 @@  discard block
 block discarded – undo
3592 3592
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3593 3593
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3594 3594
                 }
3595
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3596
-            } elseif (! empty($query_params['group_by'])) {
3595
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3596
+            } elseif ( ! empty($query_params['group_by'])) {
3597 3597
                 $query_object->set_group_by_sql(
3598
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3598
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3599 3599
                 );
3600 3600
             }
3601 3601
         }
@@ -3605,7 +3605,7 @@  discard block
 block discarded – undo
3605 3605
         }
3606 3606
         // now, just verify they didn't pass anything wack
3607 3607
         foreach ($query_params as $query_key => $query_value) {
3608
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3608
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3609 3609
                 throw new EE_Error(
3610 3610
                     sprintf(
3611 3611
                         __(
@@ -3713,7 +3713,7 @@  discard block
 block discarded – undo
3713 3713
         $where_query_params = array()
3714 3714
     ) {
3715 3715
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3716
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3716
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3717 3717
             throw new EE_Error(sprintf(
3718 3718
                 __(
3719 3719
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3845,19 +3845,19 @@  discard block
 block discarded – undo
3845 3845
     ) {
3846 3846
         $null_friendly_where_conditions = array();
3847 3847
         $none_overridden = true;
3848
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3848
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3849 3849
         foreach ($default_where_conditions as $key => $val) {
3850
-            if (isset($provided_where_conditions[ $key ])) {
3850
+            if (isset($provided_where_conditions[$key])) {
3851 3851
                 $none_overridden = false;
3852 3852
             } else {
3853
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3853
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3854 3854
             }
3855 3855
         }
3856 3856
         if ($none_overridden && $default_where_conditions) {
3857 3857
             if ($model->has_primary_key_field()) {
3858
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3858
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3859 3859
                                                                                 . "."
3860
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3860
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3861 3861
             }/*else{
3862 3862
                 //@todo NO PK, use other defaults
3863 3863
             }*/
@@ -3962,7 +3962,7 @@  discard block
 block discarded – undo
3962 3962
             foreach ($tables as $table_obj) {
3963 3963
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3964 3964
                                        . $table_obj->get_fully_qualified_pk_column();
3965
-                if (! in_array($qualified_pk_column, $selects)) {
3965
+                if ( ! in_array($qualified_pk_column, $selects)) {
3966 3966
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3967 3967
                 }
3968 3968
             }
@@ -4113,9 +4113,9 @@  discard block
 block discarded – undo
4113 4113
         $query_parameter_type
4114 4114
     ) {
4115 4115
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4116
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4116
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4117 4117
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4118
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4118
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4119 4119
                 if ($possible_join_string === '') {
4120 4120
                     // nothing left to $query_param
4121 4121
                     // we should actually end in a field name, not a model like this!
@@ -4247,7 +4247,7 @@  discard block
 block discarded – undo
4247 4247
     {
4248 4248
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4249 4249
         if ($SQL) {
4250
-            return " WHERE " . $SQL;
4250
+            return " WHERE ".$SQL;
4251 4251
         }
4252 4252
         return '';
4253 4253
     }
@@ -4266,7 +4266,7 @@  discard block
 block discarded – undo
4266 4266
     {
4267 4267
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4268 4268
         if ($SQL) {
4269
-            return " HAVING " . $SQL;
4269
+            return " HAVING ".$SQL;
4270 4270
         }
4271 4271
         return '';
4272 4272
     }
@@ -4319,7 +4319,7 @@  discard block
 block discarded – undo
4319 4319
             } else {
4320 4320
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4321 4321
                 // if it's not a normal field, maybe it's a custom selection?
4322
-                if (! $field_obj) {
4322
+                if ( ! $field_obj) {
4323 4323
                     if ($this->_custom_selections instanceof CustomSelects) {
4324 4324
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4325 4325
                     } else {
@@ -4330,7 +4330,7 @@  discard block
 block discarded – undo
4330 4330
                     }
4331 4331
                 }
4332 4332
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4333
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4333
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4334 4334
             }
4335 4335
         }
4336 4336
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4353,7 +4353,7 @@  discard block
 block discarded – undo
4353 4353
                 $field->get_model_name(),
4354 4354
                 $query_param
4355 4355
             );
4356
-            return $table_alias_prefix . $field->get_qualified_column();
4356
+            return $table_alias_prefix.$field->get_qualified_column();
4357 4357
         }
4358 4358
         if (
4359 4359
             $this->_custom_selections instanceof CustomSelects
@@ -4413,7 +4413,7 @@  discard block
 block discarded – undo
4413 4413
     {
4414 4414
         if (is_array($op_and_value)) {
4415 4415
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4416
-            if (! $operator) {
4416
+            if ( ! $operator) {
4417 4417
                 $php_array_like_string = array();
4418 4418
                 foreach ($op_and_value as $key => $value) {
4419 4419
                     $php_array_like_string[] = "$key=>$value";
@@ -4435,14 +4435,14 @@  discard block
 block discarded – undo
4435 4435
         }
4436 4436
         // check to see if the value is actually another field
4437 4437
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4438
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4438
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4439 4439
         }
4440 4440
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4441 4441
             // in this case, the value should be an array, or at least a comma-separated list
4442 4442
             // it will need to handle a little differently
4443 4443
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4444 4444
             // note: $cleaned_value has already been run through $wpdb->prepare()
4445
-            return $operator . SP . $cleaned_value;
4445
+            return $operator.SP.$cleaned_value;
4446 4446
         }
4447 4447
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4448 4448
             // the value should be an array with count of two.
@@ -4458,7 +4458,7 @@  discard block
 block discarded – undo
4458 4458
                 );
4459 4459
             }
4460 4460
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4461
-            return $operator . SP . $cleaned_value;
4461
+            return $operator.SP.$cleaned_value;
4462 4462
         }
4463 4463
         if (in_array($operator, $this->valid_null_style_operators())) {
4464 4464
             if ($value !== null) {
@@ -4478,10 +4478,10 @@  discard block
 block discarded – undo
4478 4478
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4479 4479
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4480 4480
             // remove other junk. So just treat it as a string.
4481
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4481
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4482 4482
         }
4483
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4484
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4483
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4484
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4485 4485
         }
4486 4486
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4487 4487
             throw new EE_Error(
@@ -4495,7 +4495,7 @@  discard block
 block discarded – undo
4495 4495
                 )
4496 4496
             );
4497 4497
         }
4498
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4498
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4499 4499
             throw new EE_Error(
4500 4500
                 sprintf(
4501 4501
                     __(
@@ -4535,7 +4535,7 @@  discard block
 block discarded – undo
4535 4535
         foreach ($values as $value) {
4536 4536
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4537 4537
         }
4538
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4538
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4539 4539
     }
4540 4540
 
4541 4541
 
@@ -4569,11 +4569,11 @@  discard block
 block discarded – undo
4569 4569
         // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4570 4570
         if (empty($prepped)) {
4571 4571
             $all_fields = $this->field_settings();
4572
-            $first_field    = reset($all_fields);
4572
+            $first_field = reset($all_fields);
4573 4573
             $main_table = $this->_get_main_table();
4574 4574
             $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4575 4575
         }
4576
-        return '(' . implode(',', $prepped) . ')';
4576
+        return '('.implode(',', $prepped).')';
4577 4577
     }
4578 4578
 
4579 4579
 
@@ -4594,7 +4594,7 @@  discard block
 block discarded – undo
4594 4594
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4595 4595
             );
4596 4596
         } //$field_obj should really just be a data type
4597
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4597
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4598 4598
             throw new EE_Error(
4599 4599
                 sprintf(
4600 4600
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4627,14 +4627,14 @@  discard block
 block discarded – undo
4627 4627
             ), $query_param_name));
4628 4628
         }
4629 4629
         $number_of_parts = count($query_param_parts);
4630
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4630
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4631 4631
         if ($number_of_parts === 1) {
4632 4632
             $field_name = $last_query_param_part;
4633 4633
             $model_obj = $this;
4634 4634
         } else {// $number_of_parts >= 2
4635 4635
             // the last part is the column name, and there are only 2parts. therefore...
4636 4636
             $field_name = $last_query_param_part;
4637
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4637
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4638 4638
         }
4639 4639
         try {
4640 4640
             return $model_obj->field_settings_for($field_name);
@@ -4656,7 +4656,7 @@  discard block
 block discarded – undo
4656 4656
     public function _get_qualified_column_for_field($field_name)
4657 4657
     {
4658 4658
         $all_fields = $this->field_settings();
4659
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4659
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4660 4660
         if ($field) {
4661 4661
             return $field->get_qualified_column();
4662 4662
         }
@@ -4727,10 +4727,10 @@  discard block
 block discarded – undo
4727 4727
      */
4728 4728
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4729 4729
     {
4730
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4730
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4731 4731
         $qualified_columns = array();
4732 4732
         foreach ($this->field_settings() as $field_name => $field) {
4733
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4733
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4734 4734
         }
4735 4735
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4736 4736
     }
@@ -4754,11 +4754,11 @@  discard block
 block discarded – undo
4754 4754
             if ($table_obj instanceof EE_Primary_Table) {
4755 4755
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4756 4756
                     ? $table_obj->get_select_join_limit($limit)
4757
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4757
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4758 4758
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4759 4759
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4760 4760
                     ? $table_obj->get_select_join_limit_join($limit)
4761
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4761
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4762 4762
             }
4763 4763
         }
4764 4764
         return $SQL;
@@ -4830,7 +4830,7 @@  discard block
 block discarded – undo
4830 4830
         foreach ($this->field_settings() as $field_obj) {
4831 4831
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4832 4832
             /** @var $field_obj EE_Model_Field_Base */
4833
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4833
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4834 4834
         }
4835 4835
         return $data_types;
4836 4836
     }
@@ -4846,14 +4846,14 @@  discard block
 block discarded – undo
4846 4846
      */
4847 4847
     public function get_related_model_obj($model_name)
4848 4848
     {
4849
-        $model_classname = "EEM_" . $model_name;
4850
-        if (! class_exists($model_classname)) {
4849
+        $model_classname = "EEM_".$model_name;
4850
+        if ( ! class_exists($model_classname)) {
4851 4851
             throw new EE_Error(sprintf(__(
4852 4852
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4853 4853
                 'event_espresso'
4854 4854
             ), $model_name, $model_classname));
4855 4855
         }
4856
-        return call_user_func($model_classname . "::instance");
4856
+        return call_user_func($model_classname."::instance");
4857 4857
     }
4858 4858
 
4859 4859
 
@@ -4882,7 +4882,7 @@  discard block
 block discarded – undo
4882 4882
         $belongs_to_relations = array();
4883 4883
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4884 4884
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4885
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4885
+                $belongs_to_relations[$model_name] = $relation_obj;
4886 4886
             }
4887 4887
         }
4888 4888
         return $belongs_to_relations;
@@ -4900,7 +4900,7 @@  discard block
 block discarded – undo
4900 4900
     public function related_settings_for($relation_name)
4901 4901
     {
4902 4902
         $relatedModels = $this->relation_settings();
4903
-        if (! array_key_exists($relation_name, $relatedModels)) {
4903
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4904 4904
             throw new EE_Error(
4905 4905
                 sprintf(
4906 4906
                     __(
@@ -4913,7 +4913,7 @@  discard block
 block discarded – undo
4913 4913
                 )
4914 4914
             );
4915 4915
         }
4916
-        return $relatedModels[ $relation_name ];
4916
+        return $relatedModels[$relation_name];
4917 4917
     }
4918 4918
 
4919 4919
 
@@ -4930,14 +4930,14 @@  discard block
 block discarded – undo
4930 4930
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4931 4931
     {
4932 4932
         $fieldSettings = $this->field_settings($include_db_only_fields);
4933
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4933
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4934 4934
             throw new EE_Error(sprintf(
4935 4935
                 __("There is no field/column '%s' on '%s'", 'event_espresso'),
4936 4936
                 $fieldName,
4937 4937
                 get_class($this)
4938 4938
             ));
4939 4939
         }
4940
-        return $fieldSettings[ $fieldName ];
4940
+        return $fieldSettings[$fieldName];
4941 4941
     }
4942 4942
 
4943 4943
 
@@ -4951,7 +4951,7 @@  discard block
 block discarded – undo
4951 4951
     public function has_field($fieldName)
4952 4952
     {
4953 4953
         $fieldSettings = $this->field_settings(true);
4954
-        if (isset($fieldSettings[ $fieldName ])) {
4954
+        if (isset($fieldSettings[$fieldName])) {
4955 4955
             return true;
4956 4956
         }
4957 4957
         return false;
@@ -4968,7 +4968,7 @@  discard block
 block discarded – undo
4968 4968
     public function has_relation($relation_name)
4969 4969
     {
4970 4970
         $relations = $this->relation_settings();
4971
-        if (isset($relations[ $relation_name ])) {
4971
+        if (isset($relations[$relation_name])) {
4972 4972
             return true;
4973 4973
         }
4974 4974
         return false;
@@ -5006,7 +5006,7 @@  discard block
 block discarded – undo
5006 5006
                     break;
5007 5007
                 }
5008 5008
             }
5009
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5009
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5010 5010
                 throw new EE_Error(sprintf(
5011 5011
                     __("There is no Primary Key defined on model %s", 'event_espresso'),
5012 5012
                     get_class($this)
@@ -5067,24 +5067,24 @@  discard block
 block discarded – undo
5067 5067
      */
5068 5068
     public function get_foreign_key_to($model_name)
5069 5069
     {
5070
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5070
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5071 5071
             foreach ($this->field_settings() as $field) {
5072 5072
                 if (
5073 5073
                     $field instanceof EE_Foreign_Key_Field_Base
5074 5074
                     && in_array($model_name, $field->get_model_names_pointed_to())
5075 5075
                 ) {
5076
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5076
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5077 5077
                     break;
5078 5078
                 }
5079 5079
             }
5080
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5080
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5081 5081
                 throw new EE_Error(sprintf(__(
5082 5082
                     "There is no foreign key field pointing to model %s on model %s",
5083 5083
                     'event_espresso'
5084 5084
                 ), $model_name, get_class($this)));
5085 5085
             }
5086 5086
         }
5087
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5087
+        return $this->_cache_foreign_key_to_fields[$model_name];
5088 5088
     }
5089 5089
 
5090 5090
 
@@ -5100,7 +5100,7 @@  discard block
 block discarded – undo
5100 5100
     public function get_table_for_alias($table_alias)
5101 5101
     {
5102 5102
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5103
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5103
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5104 5104
     }
5105 5105
 
5106 5106
 
@@ -5119,7 +5119,7 @@  discard block
 block discarded – undo
5119 5119
                 $this->_cached_fields = array();
5120 5120
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5121 5121
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5122
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5122
+                        $this->_cached_fields[$field_name] = $field_obj;
5123 5123
                     }
5124 5124
                 }
5125 5125
             }
@@ -5130,8 +5130,8 @@  discard block
 block discarded – undo
5130 5130
             foreach ($this->_fields as $fields_corresponding_to_table) {
5131 5131
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5132 5132
                     /** @var $field_obj EE_Model_Field_Base */
5133
-                    if (! $field_obj->is_db_only_field()) {
5134
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5133
+                    if ( ! $field_obj->is_db_only_field()) {
5134
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5135 5135
                     }
5136 5136
                 }
5137 5137
             }
@@ -5172,12 +5172,12 @@  discard block
 block discarded – undo
5172 5172
                     $primary_key_field->get_qualified_column(),
5173 5173
                     $primary_key_field->get_table_column()
5174 5174
                 );
5175
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5175
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5176 5176
                     continue;
5177 5177
                 }
5178 5178
             }
5179 5179
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5180
-            if (! $classInstance) {
5180
+            if ( ! $classInstance) {
5181 5181
                 throw new EE_Error(
5182 5182
                     sprintf(
5183 5183
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5190,7 +5190,7 @@  discard block
 block discarded – undo
5190 5190
             $classInstance->set_timezone($this->_timezone);
5191 5191
             // make sure if there is any timezone setting present that we set the timezone for the object
5192 5192
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5193
-            $array_of_objects[ $key ] = $classInstance;
5193
+            $array_of_objects[$key] = $classInstance;
5194 5194
             // also, for all the relations of type BelongsTo, see if we can cache
5195 5195
             // those related models
5196 5196
             // (we could do this for other relations too, but if there are conditions
@@ -5234,9 +5234,9 @@  discard block
 block discarded – undo
5234 5234
         $results = array();
5235 5235
         if ($this->_custom_selections instanceof CustomSelects) {
5236 5236
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5237
-                if (isset($db_results_row[ $alias ])) {
5238
-                    $results[ $alias ] = $this->convertValueToDataType(
5239
-                        $db_results_row[ $alias ],
5237
+                if (isset($db_results_row[$alias])) {
5238
+                    $results[$alias] = $this->convertValueToDataType(
5239
+                        $db_results_row[$alias],
5240 5240
                         $this->_custom_selections->getDataTypeForAlias($alias)
5241 5241
                     );
5242 5242
                 }
@@ -5278,7 +5278,7 @@  discard block
 block discarded – undo
5278 5278
         $this_model_fields_and_values = array();
5279 5279
         // setup the row using default values;
5280 5280
         foreach ($this->field_settings() as $field_name => $field_obj) {
5281
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5281
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5282 5282
         }
5283 5283
         $className = $this->_get_class_name();
5284 5284
         $classInstance = EE_Registry::instance()
@@ -5296,20 +5296,20 @@  discard block
 block discarded – undo
5296 5296
      */
5297 5297
     public function instantiate_class_from_array_or_object($cols_n_values)
5298 5298
     {
5299
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5299
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5300 5300
             $cols_n_values = get_object_vars($cols_n_values);
5301 5301
         }
5302 5302
         $primary_key = null;
5303 5303
         // make sure the array only has keys that are fields/columns on this model
5304 5304
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5305
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5306
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5305
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5306
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5307 5307
         }
5308 5308
         $className = $this->_get_class_name();
5309 5309
         // check we actually found results that we can use to build our model object
5310 5310
         // if not, return null
5311 5311
         if ($this->has_primary_key_field()) {
5312
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5312
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5313 5313
                 return null;
5314 5314
             }
5315 5315
         } elseif ($this->unique_indexes()) {
@@ -5321,7 +5321,7 @@  discard block
 block discarded – undo
5321 5321
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5322 5322
         if ($primary_key) {
5323 5323
             $classInstance = $this->get_from_entity_map($primary_key);
5324
-            if (! $classInstance) {
5324
+            if ( ! $classInstance) {
5325 5325
                 $classInstance = EE_Registry::instance()
5326 5326
                                             ->load_class(
5327 5327
                                                 $className,
@@ -5354,8 +5354,8 @@  discard block
 block discarded – undo
5354 5354
      */
5355 5355
     public function get_from_entity_map($id)
5356 5356
     {
5357
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5358
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5357
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5358
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5359 5359
     }
5360 5360
 
5361 5361
 
@@ -5378,7 +5378,7 @@  discard block
 block discarded – undo
5378 5378
     public function add_to_entity_map(EE_Base_Class $object)
5379 5379
     {
5380 5380
         $className = $this->_get_class_name();
5381
-        if (! $object instanceof $className) {
5381
+        if ( ! $object instanceof $className) {
5382 5382
             throw new EE_Error(sprintf(
5383 5383
                 __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5384 5384
                 is_object($object) ? get_class($object) : $object,
@@ -5386,7 +5386,7 @@  discard block
 block discarded – undo
5386 5386
             ));
5387 5387
         }
5388 5388
         /** @var $object EE_Base_Class */
5389
-        if (! $object->ID()) {
5389
+        if ( ! $object->ID()) {
5390 5390
             throw new EE_Error(sprintf(__(
5391 5391
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5392 5392
                 "event_espresso"
@@ -5397,7 +5397,7 @@  discard block
 block discarded – undo
5397 5397
         if ($classInstance) {
5398 5398
             return $classInstance;
5399 5399
         }
5400
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5400
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5401 5401
         return $object;
5402 5402
     }
5403 5403
 
@@ -5413,11 +5413,11 @@  discard block
 block discarded – undo
5413 5413
     public function clear_entity_map($id = null)
5414 5414
     {
5415 5415
         if (empty($id)) {
5416
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5416
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5417 5417
             return true;
5418 5418
         }
5419
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5420
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5419
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5420
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5421 5421
             return true;
5422 5422
         }
5423 5423
         return false;
@@ -5460,17 +5460,17 @@  discard block
 block discarded – undo
5460 5460
             // there is a primary key on this table and its not set. Use defaults for all its columns
5461 5461
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5462 5462
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5463
-                    if (! $field_obj->is_db_only_field()) {
5463
+                    if ( ! $field_obj->is_db_only_field()) {
5464 5464
                         // prepare field as if its coming from db
5465 5465
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5466
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5466
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5467 5467
                     }
5468 5468
                 }
5469 5469
             } else {
5470 5470
                 // the table's rows existed. Use their values
5471 5471
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5472
-                    if (! $field_obj->is_db_only_field()) {
5473
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5472
+                    if ( ! $field_obj->is_db_only_field()) {
5473
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5474 5474
                             $cols_n_values,
5475 5475
                             $field_obj->get_qualified_column(),
5476 5476
                             $field_obj->get_table_column()
@@ -5497,17 +5497,17 @@  discard block
 block discarded – undo
5497 5497
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5498 5498
         // does the field on the model relate to this column retrieved from the db?
5499 5499
         // or is it a db-only field? (not relating to the model)
5500
-        if (isset($cols_n_values[ $qualified_column ])) {
5501
-            $value = $cols_n_values[ $qualified_column ];
5502
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5503
-            $value = $cols_n_values[ $regular_column ];
5504
-        } elseif (! empty($this->foreign_key_aliases)) {
5500
+        if (isset($cols_n_values[$qualified_column])) {
5501
+            $value = $cols_n_values[$qualified_column];
5502
+        } elseif (isset($cols_n_values[$regular_column])) {
5503
+            $value = $cols_n_values[$regular_column];
5504
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5505 5505
             // no PK?  ok check if there is a foreign key alias set for this table
5506 5506
             // then check if that alias exists in the incoming data
5507 5507
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5508 5508
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5509
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5510
-                    $value = $cols_n_values[ $FK_alias ];
5509
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5510
+                    $value = $cols_n_values[$FK_alias];
5511 5511
                     [$pk_class] = explode('.', $PK_column);
5512 5512
                     $pk_model_name = "EEM_{$pk_class}";
5513 5513
                     /** @var EEM_Base $pk_model */
@@ -5551,7 +5551,7 @@  discard block
 block discarded – undo
5551 5551
                     $obj_in_map->clear_cache($relation_name, null, true);
5552 5552
                 }
5553 5553
             }
5554
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5554
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5555 5555
             return $obj_in_map;
5556 5556
         }
5557 5557
         return $this->get_one_by_ID($id);
@@ -5604,7 +5604,7 @@  discard block
 block discarded – undo
5604 5604
      */
5605 5605
     private function _get_class_name()
5606 5606
     {
5607
-        return "EE_" . $this->get_this_model_name();
5607
+        return "EE_".$this->get_this_model_name();
5608 5608
     }
5609 5609
 
5610 5610
 
@@ -5652,7 +5652,7 @@  discard block
 block discarded – undo
5652 5652
     {
5653 5653
         $className = get_class($this);
5654 5654
         $tagName = "FHEE__{$className}__{$methodName}";
5655
-        if (! has_filter($tagName)) {
5655
+        if ( ! has_filter($tagName)) {
5656 5656
             throw new EE_Error(
5657 5657
                 sprintf(
5658 5658
                     __(
@@ -5825,7 +5825,7 @@  discard block
 block discarded – undo
5825 5825
         $unique_indexes = array();
5826 5826
         foreach ($this->_indexes as $name => $index) {
5827 5827
             if ($index instanceof EE_Unique_Index) {
5828
-                $unique_indexes [ $name ] = $index;
5828
+                $unique_indexes [$name] = $index;
5829 5829
             }
5830 5830
         }
5831 5831
         return $unique_indexes;
@@ -5892,7 +5892,7 @@  discard block
 block discarded – undo
5892 5892
         $key_vals_in_combined_pk = array();
5893 5893
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5894 5894
         foreach ($key_fields as $key_field_name => $field_obj) {
5895
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5895
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5896 5896
                 return null;
5897 5897
             }
5898 5898
         }
@@ -5913,7 +5913,7 @@  discard block
 block discarded – undo
5913 5913
     {
5914 5914
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5915 5915
         foreach ($keys_it_should_have as $key) {
5916
-            if (! isset($key_vals[ $key ])) {
5916
+            if ( ! isset($key_vals[$key])) {
5917 5917
                 return false;
5918 5918
             }
5919 5919
         }
@@ -5946,8 +5946,8 @@  discard block
 block discarded – undo
5946 5946
         }
5947 5947
         // even copies obviously won't have the same ID, so remove the primary key
5948 5948
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5949
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5950
-            unset($attributes_array[ $this->primary_key_name() ]);
5949
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5950
+            unset($attributes_array[$this->primary_key_name()]);
5951 5951
         }
5952 5952
         if (isset($query_params[0])) {
5953 5953
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5969,7 +5969,7 @@  discard block
 block discarded – undo
5969 5969
      */
5970 5970
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5971 5971
     {
5972
-        if (! is_array($query_params)) {
5972
+        if ( ! is_array($query_params)) {
5973 5973
             EE_Error::doing_it_wrong(
5974 5974
                 'EEM_Base::get_one_copy',
5975 5975
                 sprintf(
@@ -6019,7 +6019,7 @@  discard block
 block discarded – undo
6019 6019
      */
6020 6020
     private function _prepare_operator_for_sql($operator_supplied)
6021 6021
     {
6022
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6022
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
6023 6023
             : null;
6024 6024
         if ($sql_operator) {
6025 6025
             return $sql_operator;
@@ -6110,7 +6110,7 @@  discard block
 block discarded – undo
6110 6110
         $objs = $this->get_all($query_params);
6111 6111
         $names = array();
6112 6112
         foreach ($objs as $obj) {
6113
-            $names[ $obj->ID() ] = $obj->name();
6113
+            $names[$obj->ID()] = $obj->name();
6114 6114
         }
6115 6115
         return $names;
6116 6116
     }
@@ -6131,7 +6131,7 @@  discard block
 block discarded – undo
6131 6131
      */
6132 6132
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6133 6133
     {
6134
-        if (! $this->has_primary_key_field()) {
6134
+        if ( ! $this->has_primary_key_field()) {
6135 6135
             if (WP_DEBUG) {
6136 6136
                 EE_Error::add_error(
6137 6137
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6144,7 +6144,7 @@  discard block
 block discarded – undo
6144 6144
         $IDs = array();
6145 6145
         foreach ($model_objects as $model_object) {
6146 6146
             $id = $model_object->ID();
6147
-            if (! $id) {
6147
+            if ( ! $id) {
6148 6148
                 if ($filter_out_empty_ids) {
6149 6149
                     continue;
6150 6150
                 }
@@ -6195,22 +6195,22 @@  discard block
 block discarded – undo
6195 6195
         EEM_Base::verify_is_valid_cap_context($context);
6196 6196
         // check if we ought to run the restriction generator first
6197 6197
         if (
6198
-            isset($this->_cap_restriction_generators[ $context ])
6199
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6200
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6198
+            isset($this->_cap_restriction_generators[$context])
6199
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6200
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6201 6201
         ) {
6202
-            $this->_cap_restrictions[ $context ] = array_merge(
6203
-                $this->_cap_restrictions[ $context ],
6204
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6202
+            $this->_cap_restrictions[$context] = array_merge(
6203
+                $this->_cap_restrictions[$context],
6204
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6205 6205
             );
6206 6206
         }
6207 6207
         // and make sure we've finalized the construction of each restriction
6208
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6208
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6209 6209
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6210 6210
                 $where_conditions_obj->_finalize_construct($this);
6211 6211
             }
6212 6212
         }
6213
-        return $this->_cap_restrictions[ $context ];
6213
+        return $this->_cap_restrictions[$context];
6214 6214
     }
6215 6215
 
6216 6216
 
@@ -6242,9 +6242,9 @@  discard block
 block discarded – undo
6242 6242
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6243 6243
             if (
6244 6244
                 ! EE_Capabilities::instance()
6245
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6245
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6246 6246
             ) {
6247
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6247
+                $missing_caps[$cap] = $restriction_if_no_cap;
6248 6248
             }
6249 6249
         }
6250 6250
         return $missing_caps;
@@ -6279,8 +6279,8 @@  discard block
 block discarded – undo
6279 6279
     public function cap_action_for_context($context)
6280 6280
     {
6281 6281
         $mapping = $this->cap_contexts_to_cap_action_map();
6282
-        if (isset($mapping[ $context ])) {
6283
-            return $mapping[ $context ];
6282
+        if (isset($mapping[$context])) {
6283
+            return $mapping[$context];
6284 6284
         }
6285 6285
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6286 6286
             return $action;
@@ -6398,7 +6398,7 @@  discard block
 block discarded – undo
6398 6398
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6399 6399
             if (
6400 6400
                 $query_param_key === $logic_query_param_key
6401
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6401
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6402 6402
             ) {
6403 6403
                 return true;
6404 6404
             }
@@ -6451,7 +6451,7 @@  discard block
 block discarded – undo
6451 6451
         if ($password_field instanceof EE_Password_Field) {
6452 6452
             $field_names = $password_field->protectedFields();
6453 6453
             foreach ($field_names as $field_name) {
6454
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6454
+                $fields[$field_name] = $this->field_settings_for($field_name);
6455 6455
             }
6456 6456
         }
6457 6457
         return $fields;
@@ -6476,7 +6476,7 @@  discard block
 block discarded – undo
6476 6476
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6477 6477
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6478 6478
         }
6479
-        if (!is_array($model_obj_or_fields_n_values)) {
6479
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6480 6480
             throw new UnexpectedEntityException(
6481 6481
                 $model_obj_or_fields_n_values,
6482 6482
                 'EE_Base_Class',
@@ -6551,7 +6551,7 @@  discard block
 block discarded – undo
6551 6551
                 )
6552 6552
             );
6553 6553
         }
6554
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6554
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6555 6555
     }
6556 6556
 
6557 6557
     /**
Please login to merge, or discard this patch.
core/domain/services/graphql/mutators/FormSectionDelete.php 2 patches
Indentation   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -17,73 +17,73 @@
 block discarded – undo
17 17
 class FormSectionDelete extends EntityMutator
18 18
 {
19 19
 
20
-    /**
21
-     * Defines the mutation data modification closure.
22
-     *
23
-     * @param EEM_Form_Section $model
24
-     * @return callable
25
-     */
26
-    public static function mutateAndGetPayload(EEM_Form_Section $model)
27
-    {
28
-        /**
29
-         * Deletes an entity.
30
-         *
31
-         * @param array       $input   The input for the mutation
32
-         * @param AppContext  $context The AppContext passed down to all resolvers
33
-         * @param ResolveInfo $info    The ResolveInfo passed down to all resolvers
34
-         * @return array
35
-         */
36
-        return static function (array $input, AppContext $context, ResolveInfo $info) use ($model): array {
37
-            try {
38
-                /** @var EE_Form_Section $entity */
39
-                $entity = EntityMutator::getEntityFromInputData($model, $input);
20
+	/**
21
+	 * Defines the mutation data modification closure.
22
+	 *
23
+	 * @param EEM_Form_Section $model
24
+	 * @return callable
25
+	 */
26
+	public static function mutateAndGetPayload(EEM_Form_Section $model)
27
+	{
28
+		/**
29
+		 * Deletes an entity.
30
+		 *
31
+		 * @param array       $input   The input for the mutation
32
+		 * @param AppContext  $context The AppContext passed down to all resolvers
33
+		 * @param ResolveInfo $info    The ResolveInfo passed down to all resolvers
34
+		 * @return array
35
+		 */
36
+		return static function (array $input, AppContext $context, ResolveInfo $info) use ($model): array {
37
+			try {
38
+				/** @var EE_Form_Section $entity */
39
+				$entity = EntityMutator::getEntityFromInputData($model, $input);
40 40
 
41
-                $result = FormSectionDelete::deleteSectionAndRelations($entity);
41
+				$result = FormSectionDelete::deleteSectionAndRelations($entity);
42 42
 
43
-                EntityMutator::validateResults($result);
43
+				EntityMutator::validateResults($result);
44 44
 
45
-                do_action(
46
-                    'AHEE__EventEspresso_core_domain_services_graphql_mutators_form_section_delete',
47
-                    $entity,
48
-                    $input
49
-                );
50
-            } catch (Exception $exception) {
51
-                EntityMutator::handleExceptions(
52
-                    $exception,
53
-                    esc_html__(
54
-                        'The form section could not be deleted because of the following error(s)',
55
-                        'event_espresso'
56
-                    )
57
-                );
58
-            }
45
+				do_action(
46
+					'AHEE__EventEspresso_core_domain_services_graphql_mutators_form_section_delete',
47
+					$entity,
48
+					$input
49
+				);
50
+			} catch (Exception $exception) {
51
+				EntityMutator::handleExceptions(
52
+					$exception,
53
+					esc_html__(
54
+						'The form section could not be deleted because of the following error(s)',
55
+						'event_espresso'
56
+					)
57
+				);
58
+			}
59 59
 
60
-            return [
61
-                'deleted' => $entity,
62
-            ];
63
-        };
64
-    }
60
+			return [
61
+				'deleted' => $entity,
62
+			];
63
+		};
64
+	}
65 65
 
66
-    /**
67
-     * Deletes a form section along with its related form elements.
68
-     *
69
-     * @param EE_Form_Section $entity
70
-     * @return bool | int
71
-     * @throws ReflectionException
72
-     * @throws InvalidArgumentException
73
-     * @throws InvalidInterfaceException
74
-     * @throws InvalidDataTypeException
75
-     * @throws EE_Error
76
-     */
77
-    public static function deleteSectionAndRelations(EE_Form_Section $entity)
78
-    {
79
-        // Remove related non-default form elements
80
-        $entity->delete_related('Form_Element', [
81
-            [
82
-                'FIN_status' => ['NOT IN', [ FormStatus::SHARED, FormStatus::DEFAULT] ]
83
-            ]
84
-        ]);
66
+	/**
67
+	 * Deletes a form section along with its related form elements.
68
+	 *
69
+	 * @param EE_Form_Section $entity
70
+	 * @return bool | int
71
+	 * @throws ReflectionException
72
+	 * @throws InvalidArgumentException
73
+	 * @throws InvalidInterfaceException
74
+	 * @throws InvalidDataTypeException
75
+	 * @throws EE_Error
76
+	 */
77
+	public static function deleteSectionAndRelations(EE_Form_Section $entity)
78
+	{
79
+		// Remove related non-default form elements
80
+		$entity->delete_related('Form_Element', [
81
+			[
82
+				'FIN_status' => ['NOT IN', [ FormStatus::SHARED, FormStatus::DEFAULT] ]
83
+			]
84
+		]);
85 85
 
86
-        // Now delete the form section
87
-        return $entity->delete();
88
-    }
86
+		// Now delete the form section
87
+		return $entity->delete();
88
+	}
89 89
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
          * @param ResolveInfo $info    The ResolveInfo passed down to all resolvers
34 34
          * @return array
35 35
          */
36
-        return static function (array $input, AppContext $context, ResolveInfo $info) use ($model): array {
36
+        return static function(array $input, AppContext $context, ResolveInfo $info) use ($model): array {
37 37
             try {
38 38
                 /** @var EE_Form_Section $entity */
39 39
                 $entity = EntityMutator::getEntityFromInputData($model, $input);
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
         // Remove related non-default form elements
80 80
         $entity->delete_related('Form_Element', [
81 81
             [
82
-                'FIN_status' => ['NOT IN', [ FormStatus::SHARED, FormStatus::DEFAULT] ]
82
+                'FIN_status' => ['NOT IN', [FormStatus::SHARED, FormStatus::DEFAULT]]
83 83
             ]
84 84
         ]);
85 85
 
Please login to merge, or discard this patch.
core/services/form/meta/inputs/Block.php 1 patch
Indentation   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -4,36 +4,36 @@
 block discarded – undo
4 4
 
5 5
 class Block
6 6
 {
7
-    /**
8
-     * indicates that the element is a general HTML block
9
-     */
10
-    public const TYPE_HTML = 'html';
7
+	/**
8
+	 * indicates that the element is a general HTML block
9
+	 */
10
+	public const TYPE_HTML = 'html';
11 11
 
12
-    /**
13
-     * @var array
14
-     */
15
-    private $valid_type_options;
12
+	/**
13
+	 * @var array
14
+	 */
15
+	private $valid_type_options;
16 16
 
17 17
 
18
-    public function __construct()
19
-    {
20
-        $this->valid_type_options = apply_filters(
21
-            'FHEE__EventEspresso_core_services_form_meta_inputs_Block__valid_type_options',
22
-            [
23
-                Block::TYPE_HTML => esc_html__('HTML Block', 'event_espresso'),
24
-            ]
25
-        );
26
-    }
18
+	public function __construct()
19
+	{
20
+		$this->valid_type_options = apply_filters(
21
+			'FHEE__EventEspresso_core_services_form_meta_inputs_Block__valid_type_options',
22
+			[
23
+				Block::TYPE_HTML => esc_html__('HTML Block', 'event_espresso'),
24
+			]
25
+		);
26
+	}
27 27
 
28 28
 
29
-    /**
30
-     * @param bool $constants_only
31
-     * @return array
32
-     */
33
-    public function validTypeOptions(bool $constants_only = false): array
34
-    {
35
-        return $constants_only
36
-            ? array_keys($this->valid_type_options)
37
-            : $this->valid_type_options;
38
-    }
29
+	/**
30
+	 * @param bool $constants_only
31
+	 * @return array
32
+	 */
33
+	public function validTypeOptions(bool $constants_only = false): array
34
+	{
35
+		return $constants_only
36
+			? array_keys($this->valid_type_options)
37
+			: $this->valid_type_options;
38
+	}
39 39
 }
Please login to merge, or discard this patch.
core/services/form/meta/InputOptions.php 2 patches
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -15,106 +15,106 @@
 block discarded – undo
15 15
 class InputOptions implements JsonableInterface
16 16
 {
17 17
 
18
-    /**
19
-     * @var JsonDataHandler
20
-     */
21
-    private $json_data_handler;
22
-
23
-    /**
24
-     * Options for ENUM type inputs like checkboxes, radio buttons, select inputs, etc
25
-     *
26
-     * @var array
27
-     */
28
-    private $options = [];
29
-
30
-
31
-    /**
32
-     * HelpText constructor.
33
-     *
34
-     * @param JsonDataHandler $json_data_handler
35
-     * @param array           $options
36
-     */
37
-    public function __construct(JsonDataHandler $json_data_handler, array $options)
38
-    {
39
-        $this->json_data_handler = $json_data_handler;
40
-        $this->setOptions($options);
41
-    }
42
-
43
-
44
-    /**
45
-     * @param string $json
46
-     * @return InputOptions
47
-     */
48
-    public static function fromJson(string $json): InputOptions
49
-    {
50
-        $json_data_handler = new JsonDataHandler();
51
-        $json_data_handler->configure(JsonDataHandler::DATA_TYPE_ARRAY);
52
-        $data = $json_data_handler->decodeJson($json);
53
-        return new InputOptions($json_data_handler, $data ?? []);
54
-    }
55
-
56
-
57
-    /**
58
-     * @return array
59
-     */
60
-    public function toArray(): array
61
-    {
62
-        return array_values($this->options);
63
-    }
64
-
65
-
66
-    /**
67
-     * @return string
68
-     */
69
-    public function toJson(): string
70
-    {
71
-        return $this->json_data_handler->encodeData($this->toArray());
72
-    }
73
-
74
-
75
-    /**
76
-     * an array where keys are option values and values are option labels
77
-     *
78
-     * @return array
79
-     */
80
-    public function options(): array
81
-    {
82
-        return $this->options;
83
-    }
84
-
85
-
86
-    /**
87
-     * @param array $option
88
-     */
89
-    public function addOption(array $option): void
90
-    {
91
-        if (isset($option['label'], $option['value'])) {
92
-            $label = sanitize_text_field($option['label']);
93
-            $value = sanitize_key($option['value']);
94
-
95
-            // use `value` as key
96
-            $this->options[ $value ] = compact('label', 'value');
97
-        }
98
-    }
99
-
100
-
101
-    /**
102
-     * @param int|float|string $option_value
103
-     */
104
-    public function removeOption(string $option_value): void
105
-    {
106
-        $option_value = sanitize_key($option_value);
107
-        unset($this->options[ $option_value ]);
108
-    }
109
-
110
-
111
-    /**
112
-     * @param array $options an array where keys are option values and values are option labels
113
-     */
114
-    public function setOptions(array $options): void
115
-    {
116
-        foreach ($options as $option) {
117
-            $this->addOption($option);
118
-        }
119
-    }
18
+	/**
19
+	 * @var JsonDataHandler
20
+	 */
21
+	private $json_data_handler;
22
+
23
+	/**
24
+	 * Options for ENUM type inputs like checkboxes, radio buttons, select inputs, etc
25
+	 *
26
+	 * @var array
27
+	 */
28
+	private $options = [];
29
+
30
+
31
+	/**
32
+	 * HelpText constructor.
33
+	 *
34
+	 * @param JsonDataHandler $json_data_handler
35
+	 * @param array           $options
36
+	 */
37
+	public function __construct(JsonDataHandler $json_data_handler, array $options)
38
+	{
39
+		$this->json_data_handler = $json_data_handler;
40
+		$this->setOptions($options);
41
+	}
42
+
43
+
44
+	/**
45
+	 * @param string $json
46
+	 * @return InputOptions
47
+	 */
48
+	public static function fromJson(string $json): InputOptions
49
+	{
50
+		$json_data_handler = new JsonDataHandler();
51
+		$json_data_handler->configure(JsonDataHandler::DATA_TYPE_ARRAY);
52
+		$data = $json_data_handler->decodeJson($json);
53
+		return new InputOptions($json_data_handler, $data ?? []);
54
+	}
55
+
56
+
57
+	/**
58
+	 * @return array
59
+	 */
60
+	public function toArray(): array
61
+	{
62
+		return array_values($this->options);
63
+	}
64
+
65
+
66
+	/**
67
+	 * @return string
68
+	 */
69
+	public function toJson(): string
70
+	{
71
+		return $this->json_data_handler->encodeData($this->toArray());
72
+	}
73
+
74
+
75
+	/**
76
+	 * an array where keys are option values and values are option labels
77
+	 *
78
+	 * @return array
79
+	 */
80
+	public function options(): array
81
+	{
82
+		return $this->options;
83
+	}
84
+
85
+
86
+	/**
87
+	 * @param array $option
88
+	 */
89
+	public function addOption(array $option): void
90
+	{
91
+		if (isset($option['label'], $option['value'])) {
92
+			$label = sanitize_text_field($option['label']);
93
+			$value = sanitize_key($option['value']);
94
+
95
+			// use `value` as key
96
+			$this->options[ $value ] = compact('label', 'value');
97
+		}
98
+	}
99
+
100
+
101
+	/**
102
+	 * @param int|float|string $option_value
103
+	 */
104
+	public function removeOption(string $option_value): void
105
+	{
106
+		$option_value = sanitize_key($option_value);
107
+		unset($this->options[ $option_value ]);
108
+	}
109
+
110
+
111
+	/**
112
+	 * @param array $options an array where keys are option values and values are option labels
113
+	 */
114
+	public function setOptions(array $options): void
115
+	{
116
+		foreach ($options as $option) {
117
+			$this->addOption($option);
118
+		}
119
+	}
120 120
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
             $value = sanitize_key($option['value']);
94 94
 
95 95
             // use `value` as key
96
-            $this->options[ $value ] = compact('label', 'value');
96
+            $this->options[$value] = compact('label', 'value');
97 97
         }
98 98
     }
99 99
 
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
     public function removeOption(string $option_value): void
105 105
     {
106 106
         $option_value = sanitize_key($option_value);
107
-        unset($this->options[ $option_value ]);
107
+        unset($this->options[$option_value]);
108 108
     }
109 109
 
110 110
 
Please login to merge, or discard this patch.
core/db_models/fields/EE_JSON_Field.php 1 patch
Indentation   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -5,76 +5,76 @@
 block discarded – undo
5 5
 class EE_JSON_Field extends EE_Model_Field_Base
6 6
 {
7 7
 
8
-    /**
9
-     * @var JsonDataHandler
10
-     */
11
-    private $json_data_handler;
8
+	/**
9
+	 * @var JsonDataHandler
10
+	 */
11
+	private $json_data_handler;
12 12
 
13 13
 
14
-    /**
15
-     * @param string $table_column
16
-     * @param string $nicename
17
-     * @param bool   $nullable
18
-     * @param null   $default_value
19
-     */
20
-    public function __construct(
21
-        $table_column,
22
-        $nicename,
23
-        $nullable,
24
-        $default_value = null
25
-    ) {
26
-        $this->json_data_handler = new JsonDataHandler();
27
-        $this->json_data_handler->configure(
28
-            JsonDataHandler::DATA_TYPE_OBJECT
29
-        );
30
-        parent::__construct($table_column, $nicename, $nullable, $default_value);
31
-    }
14
+	/**
15
+	 * @param string $table_column
16
+	 * @param string $nicename
17
+	 * @param bool   $nullable
18
+	 * @param null   $default_value
19
+	 */
20
+	public function __construct(
21
+		$table_column,
22
+		$nicename,
23
+		$nullable,
24
+		$default_value = null
25
+	) {
26
+		$this->json_data_handler = new JsonDataHandler();
27
+		$this->json_data_handler->configure(
28
+			JsonDataHandler::DATA_TYPE_OBJECT
29
+		);
30
+		parent::__construct($table_column, $nicename, $nullable, $default_value);
31
+	}
32 32
 
33 33
 
34
-    // /**
35
-    //  * When get() is called on a model object (eg EE_Event), before returning its value,
36
-    //  * call this function on it, allowing us to customize the returned value based on
37
-    //  * the field's type. Eg, we may want to unserialize it, strip tags, etc. By default,
38
-    //  * we simply return it.
39
-    //  *
40
-    //  * @param mixed $value_of_field_on_model_object
41
-    //  * @return mixed
42
-    //  */
43
-    // public function prepare_for_get($value_of_field_on_model_object)
44
-    // {
45
-    //     // return $this->json_data_handler->decodeJson($value_of_field_on_model_object);
46
-    //     return $value_of_field_on_model_object;
47
-    // }
34
+	// /**
35
+	//  * When get() is called on a model object (eg EE_Event), before returning its value,
36
+	//  * call this function on it, allowing us to customize the returned value based on
37
+	//  * the field's type. Eg, we may want to unserialize it, strip tags, etc. By default,
38
+	//  * we simply return it.
39
+	//  *
40
+	//  * @param mixed $value_of_field_on_model_object
41
+	//  * @return mixed
42
+	//  */
43
+	// public function prepare_for_get($value_of_field_on_model_object)
44
+	// {
45
+	//     // return $this->json_data_handler->decodeJson($value_of_field_on_model_object);
46
+	//     return $value_of_field_on_model_object;
47
+	// }
48 48
 
49 49
 
50
-    /**
51
-     * When creating a brand-new model object, or setting a particular value for one of its fields, this function
52
-     * is called before setting it on the model object. We may want to strip slashes, unserialize the value, etc.
53
-     * By default, we do nothing.
54
-     *
55
-     * If the model field is going to perform any validation on the input, this is where it should be done
56
-     * (once the value is on the model object, it may be used in other ways besides putting it into the DB
57
-     * so it's best to validate it right away).
58
-     *
59
-     * @param mixed $value_inputted_for_field_on_model_object
60
-     * @return string
61
-     */
62
-    public function prepare_for_set($value_inputted_for_field_on_model_object)
63
-    {
64
-        return $this->json_data_handler->encodeData($value_inputted_for_field_on_model_object);
65
-    }
50
+	/**
51
+	 * When creating a brand-new model object, or setting a particular value for one of its fields, this function
52
+	 * is called before setting it on the model object. We may want to strip slashes, unserialize the value, etc.
53
+	 * By default, we do nothing.
54
+	 *
55
+	 * If the model field is going to perform any validation on the input, this is where it should be done
56
+	 * (once the value is on the model object, it may be used in other ways besides putting it into the DB
57
+	 * so it's best to validate it right away).
58
+	 *
59
+	 * @param mixed $value_inputted_for_field_on_model_object
60
+	 * @return string
61
+	 */
62
+	public function prepare_for_set($value_inputted_for_field_on_model_object)
63
+	{
64
+		return $this->json_data_handler->encodeData($value_inputted_for_field_on_model_object);
65
+	}
66 66
 
67 67
 
68
-    /**
69
-     * When inserting or updating a field on a model object, run this function on each
70
-     * value to prepare it for insertion into the db. Generally this converts
71
-     * the validated input on the model object into the format used in the DB.
72
-     *
73
-     * @param mixed $value_of_field_on_model_object
74
-     * @return string
75
-     */
76
-    public function prepare_for_use_in_db($value_of_field_on_model_object)
77
-    {
78
-        return $this->json_data_handler->encodeData($value_of_field_on_model_object);
79
-    }
68
+	/**
69
+	 * When inserting or updating a field on a model object, run this function on each
70
+	 * value to prepare it for insertion into the db. Generally this converts
71
+	 * the validated input on the model object into the format used in the DB.
72
+	 *
73
+	 * @param mixed $value_of_field_on_model_object
74
+	 * @return string
75
+	 */
76
+	public function prepare_for_use_in_db($value_of_field_on_model_object)
77
+	{
78
+		return $this->json_data_handler->encodeData($value_of_field_on_model_object);
79
+	}
80 80
 }
Please login to merge, or discard this patch.
core/db_models/fields/EE_Foreign_Key_String_Field.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -2,41 +2,41 @@
 block discarded – undo
2 2
 
3 3
 class EE_Foreign_Key_String_Field extends EE_Foreign_Key_Field_Base
4 4
 {
5
-    /**
6
-     * Whether the value should be converted to uppercase on insertion.
7
-     *
8
-     * @var boolean
9
-     */
10
-    protected $is_uppercase;
5
+	/**
6
+	 * Whether the value should be converted to uppercase on insertion.
7
+	 *
8
+	 * @var boolean
9
+	 */
10
+	protected $is_uppercase;
11 11
 
12 12
 
13
-    /**
14
-     * @param string          $table_column  name of column for field
15
-     * @param string          $nicename      should be internationalized with __('blah','event_espresso')
16
-     * @param boolean         $nullable
17
-     * @param int|string      $default_value data type should match field type
18
-     * @param string|string[] $model_name    eg 'Event','Answer','Term', etc.
19
-     *                                       Basically its the model class's name without the "EEM_"
20
-     * @param boolean         $is_uppercase  Whether the value should be converted to uppercase on insertion.
21
-     */
22
-    public function __construct($table_column, $nicename, $nullable, $default_value, $model_name, $is_uppercase = true)
23
-    {
24
-        $this->is_uppercase = $is_uppercase;
25
-        parent::__construct($table_column, $nicename, $nullable, $default_value, $model_name);
26
-    }
13
+	/**
14
+	 * @param string          $table_column  name of column for field
15
+	 * @param string          $nicename      should be internationalized with __('blah','event_espresso')
16
+	 * @param boolean         $nullable
17
+	 * @param int|string      $default_value data type should match field type
18
+	 * @param string|string[] $model_name    eg 'Event','Answer','Term', etc.
19
+	 *                                       Basically its the model class's name without the "EEM_"
20
+	 * @param boolean         $is_uppercase  Whether the value should be converted to uppercase on insertion.
21
+	 */
22
+	public function __construct($table_column, $nicename, $nullable, $default_value, $model_name, $is_uppercase = true)
23
+	{
24
+		$this->is_uppercase = $is_uppercase;
25
+		parent::__construct($table_column, $nicename, $nullable, $default_value, $model_name);
26
+	}
27 27
 
28
-    /**
29
-     * removes all tags when setting
30
-     *
31
-     * @param string $value_inputted_for_field_on_model_object
32
-     * @return string
33
-     */
34
-    public function prepare_for_set($value_inputted_for_field_on_model_object)
35
-    {
36
-        if ($this->is_model_obj_of_type_pointed_to($value_inputted_for_field_on_model_object)) {
37
-            $value_inputted_for_field_on_model_object = $value_inputted_for_field_on_model_object->ID();
38
-        }
39
-        $clean_value = wp_strip_all_tags($value_inputted_for_field_on_model_object);
40
-        return $this->is_uppercase ? strtoupper($clean_value) : $clean_value;
41
-    }
28
+	/**
29
+	 * removes all tags when setting
30
+	 *
31
+	 * @param string $value_inputted_for_field_on_model_object
32
+	 * @return string
33
+	 */
34
+	public function prepare_for_set($value_inputted_for_field_on_model_object)
35
+	{
36
+		if ($this->is_model_obj_of_type_pointed_to($value_inputted_for_field_on_model_object)) {
37
+			$value_inputted_for_field_on_model_object = $value_inputted_for_field_on_model_object->ID();
38
+		}
39
+		$clean_value = wp_strip_all_tags($value_inputted_for_field_on_model_object);
40
+		return $this->is_uppercase ? strtoupper($clean_value) : $clean_value;
41
+	}
42 42
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Form_Element.class.php 2 patches
Indentation   +467 added lines, -467 removed lines patch added patch discarded remove patch
@@ -29,471 +29,471 @@
 block discarded – undo
29 29
 class EE_Form_Element extends EE_Base_Class
30 30
 {
31 31
 
32
-    /**
33
-     * @var Attributes
34
-     */
35
-    private $attributes;
36
-
37
-    /**
38
-     * @var FormLabel
39
-     */
40
-    private $label;
41
-
42
-    /**
43
-     * @var HelpText
44
-     */
45
-    private $helpText;
46
-
47
-    /**
48
-     * @var InputOptions
49
-     */
50
-    private $options;
51
-
52
-    /**
53
-     * @var Required
54
-     */
55
-    private $required;
56
-
57
-
58
-    /**
59
-     * @param array $props_n_values
60
-     * @return EE_Form_Element
61
-     * @throws EE_Error
62
-     * @throws ReflectionException
63
-     */
64
-    public static function new_instance(array $props_n_values = []): EE_Form_Element
65
-    {
66
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
67
-        return $has_object ?: new self($props_n_values);
68
-    }
69
-
70
-
71
-    /**
72
-     * @param array $props_n_values
73
-     * @return EE_Form_Element
74
-     * @throws EE_Error
75
-     * @throws ReflectionException
76
-     */
77
-    public static function new_instance_from_db(array $props_n_values = []): EE_Form_Element
78
-    {
79
-        return new self($props_n_values);
80
-    }
81
-
82
-
83
-    /**
84
-     * Form Element UUID (universally unique identifier)
85
-     *
86
-     * @return string
87
-     * @throws EE_Error
88
-     * @throws ReflectionException
89
-     */
90
-    public function UUID(): string
91
-    {
92
-        return $this->get('FIN_UUID');
93
-    }
94
-
95
-
96
-    /**
97
-     * @param string $UUID
98
-     * @throws EE_Error
99
-     * @throws ReflectionException
100
-     */
101
-    public function setUUID(string $UUID)
102
-    {
103
-        $this->set('FIN_UUID', $UUID);
104
-    }
105
-
106
-
107
-    /**
108
-     * Whether or not input is only displayed in the admin. If false, input will appear in public forms
109
-     *
110
-     * @return bool
111
-     * @throws EE_Error
112
-     * @throws ReflectionException
113
-     */
114
-    public function adminOnly(): ?bool
115
-    {
116
-        return $this->get('FIN_adminOnly');
117
-    }
118
-
119
-
120
-    /**
121
-     * @param bool $admin_only
122
-     * @throws EE_Error
123
-     * @throws ReflectionException
124
-     */
125
-    public function setAdminOnly(bool $admin_only)
126
-    {
127
-        $this->set('FIN_adminOnly', $admin_only);
128
-    }
129
-
130
-
131
-    /**
132
-     * JSON string of HTML attributes such as class, max, min, placeholder, type, etc.
133
-     *
134
-     * @return Attributes
135
-     * @throws EE_Error
136
-     * @throws ReflectionException
137
-     */
138
-    public function attributes(): ?Attributes
139
-    {
140
-        if (! $this->attributes instanceof Attributes) {
141
-            $this->attributes = Attributes::fromJson($this->get('FIN_attributes'));
142
-        }
143
-        return $this->attributes;
144
-    }
145
-
146
-
147
-    /**
148
-     * @param Attributes $attributes
149
-     * @throws EE_Error
150
-     * @throws ReflectionException
151
-     */
152
-    public function setAttributes(Attributes $attributes)
153
-    {
154
-        // set local object
155
-        $this->attributes = $attributes;
156
-        // then pass to model as an array which will get converted to JSON by the model field
157
-        $this->set('FIN_attributes', $attributes->toArray());
158
-    }
159
-
160
-
161
-    /**
162
-     * UUID of parent form section this form input belongs to.
163
-     *
164
-     * @return string
165
-     * @throws EE_Error
166
-     * @throws ReflectionException
167
-     */
168
-    public function belongsTo(): string
169
-    {
170
-        return $this->get('FSC_UUID');
171
-    }
172
-
173
-
174
-    /**
175
-     * @param string $relation_UUID
176
-     * @throws EE_Error
177
-     * @throws ReflectionException
178
-     */
179
-    public function setBelongsTo(string $relation_UUID)
180
-    {
181
-        $this->set('FSC_UUID', $relation_UUID);
182
-    }
183
-
184
-
185
-    /**
186
-     * returns a HelpText object for managing input help text
187
-     *
188
-     * @return HelpText
189
-     * @throws EE_Error
190
-     * @throws ReflectionException
191
-     */
192
-    public function helpText(): ?HelpText
193
-    {
194
-        if (! $this->helpText instanceof HelpText) {
195
-            $this->helpText = HelpText::fromJson($this->get('FIN_helpText'));
196
-        }
197
-        return $this->helpText;
198
-    }
199
-
200
-
201
-    /**
202
-     * @param HelpText $helpText
203
-     * @throws EE_Error
204
-     * @throws ReflectionException
205
-     */
206
-    public function setHelpText(HelpText $helpText)
207
-    {
208
-        // set local object
209
-        $this->helpText = $helpText;
210
-        // then pass to model as an array which will get converted to JSON by the model field
211
-        $this->set('FIN_helpText', $helpText->toArray());
212
-    }
213
-
214
-
215
-    /**
216
-     * returns a FormLabel object for managing input labels
217
-     *
218
-     * @return FormLabel
219
-     * @throws EE_Error
220
-     * @throws ReflectionException
221
-     */
222
-    public function label(): ?FormLabel
223
-    {
224
-        if (! $this->label instanceof FormLabel) {
225
-            $this->label = FormLabel::fromJson($this->get('FIN_label'));
226
-        }
227
-        return $this->label;
228
-    }
229
-
230
-
231
-    /**
232
-     * @param FormLabel $label
233
-     * @throws EE_Error
234
-     * @throws ReflectionException
235
-     */
236
-    public function setLabel(FormLabel $label)
237
-    {
238
-        // set local object
239
-        $this->label = $label;
240
-        // then pass to model as an array which will get converted to JSON by the model field
241
-        $this->set('FIN_label', $label->toArray());
242
-    }
243
-
244
-
245
-    /**
246
-     * Model and Fields name that this input maps to; ex: Attendee.email
247
-     *
248
-     * @return string
249
-     * @throws EE_Error
250
-     * @throws ReflectionException
251
-     */
252
-    public function mapsTo(): ?string
253
-    {
254
-        return $this->get('FIN_mapsTo');
255
-    }
256
-
257
-
258
-    /**
259
-     * @param string $model ex: Attendee
260
-     * @param string $field ex: email
261
-     * @throws EE_Error
262
-     * @throws ReflectionException
263
-     */
264
-    public function setMapsTo(string $model, string $field)
265
-    {
266
-        $model_name = strpos($model, 'EEM_') !== 0 ? "EEM_$model" : $model;
267
-        if (! class_exists($model_name)) {
268
-            throw new DomainException(
269
-                sprintf(
270
-                    esc_html__(
271
-                        'The %1$s model does not exist or can not be located. Please verify the spelling and whether it is loaded.',
272
-                        'event_espresso'
273
-                    ),
274
-                    $model_name
275
-                )
276
-            );
277
-        }
278
-        $this->set('FIN_mapsTo', "{$model}.{$field}");
279
-    }
280
-
281
-
282
-    /**
283
-     * Options for ENUM type inputs like checkboxes, radio buttons, select inputs, etc
284
-     *
285
-     * @return InputOptions
286
-     * @throws EE_Error
287
-     * @throws ReflectionException
288
-     */
289
-    public function options(): ?InputOptions
290
-    {
291
-        if (! $this->options instanceof InputOptions) {
292
-            $this->options = InputOptions::fromJson($this->get('FIN_options'));
293
-        }
294
-        return $this->options;
295
-    }
296
-
297
-
298
-    /**
299
-     * @param InputOptions $options
300
-     * @throws EE_Error
301
-     * @throws ReflectionException
302
-     */
303
-    public function setOptions(InputOptions $options)
304
-    {
305
-        // set local object
306
-        $this->options = $options;
307
-        // then pass to model as an array which will get converted to JSON by the model field
308
-        $this->set('FIN_options', $options->toArray());
309
-    }
310
-
311
-
312
-
313
-    /**
314
-     * Order in which form input appears in a form.
315
-     *
316
-     * @return int
317
-     * @throws EE_Error
318
-     * @throws ReflectionException
319
-     */
320
-    public function order(): int
321
-    {
322
-        return $this->get('FIN_order');
323
-    }
324
-
325
-
326
-    /**
327
-     * @param int $order
328
-     * @throws EE_Error
329
-     * @throws ReflectionException
330
-     */
331
-    public function setOrder(int $order)
332
-    {
333
-        $this->set('FIN_order', $order);
334
-    }
335
-
336
-
337
-    /**
338
-     * Example text displayed within an input to assist users with completing the form.
339
-     *
340
-     * @return string
341
-     * @throws EE_Error
342
-     * @throws ReflectionException
343
-     */
344
-    public function placeholder(): ?string
345
-    {
346
-        return $this->get('FIN_placeholder');
347
-    }
348
-
349
-
350
-    /**
351
-     * @param string $placeholder
352
-     * @throws EE_Error
353
-     * @throws ReflectionException
354
-     */
355
-    public function setPlaceholder(string $placeholder)
356
-    {
357
-        $this->set('FIN_placeholder', $placeholder);
358
-    }
359
-
360
-
361
-    /**
362
-     * Whether or not the input must be supplied with a value in order to complete the form.
363
-     *
364
-     * @return Required
365
-     * @throws EE_Error
366
-     * @throws ReflectionException
367
-     */
368
-    public function required(): ?Required
369
-    {
370
-        if (! $this->required instanceof Required) {
371
-            $this->required = Required::fromJson($this->get('FIN_required'));
372
-        }
373
-        return $this->required;
374
-    }
375
-
376
-
377
-    /**
378
-     * @param Required $required
379
-     * @throws EE_Error
380
-     * @throws ReflectionException
381
-     */
382
-    public function setRequired(Required $required)
383
-    {
384
-        // set local object
385
-        $this->required = $required;
386
-        // then pass to model as an array which will get converted to JSON by the model field
387
-        $this->set('FIN_required', $required->toArray());
388
-    }
389
-
390
-
391
-    /**
392
-     * version of public label for use in identifiers
393
-     *
394
-     * @return string
395
-     * @throws EE_Error
396
-     * @throws ReflectionException
397
-     */
398
-    public function slug(): ?string
399
-    {
400
-        return sanitize_title($this->label()->publicLabel());
401
-    }
402
-
403
-
404
-    /**
405
-     * Whether form input is active, archived, trashed, or used as a default on new forms.
406
-     * Values correspond to the EEM_Form_Element::STATUS_* constants.
407
-     *
408
-     * @return string
409
-     * @throws EE_Error
410
-     * @throws ReflectionException
411
-     */
412
-    public function status(): string
413
-    {
414
-        return $this->get('FIN_status');
415
-    }
416
-
417
-
418
-    /**
419
-     * Whether form input is active, archived, trashed, or used as a default on new forms.
420
-     * Values correspond to the EEM_Form_Element::STATUS_* constants.
421
-     *
422
-     * @param string $status
423
-     * @throws EE_Error
424
-     * @throws ReflectionException
425
-     */
426
-    public function setStatus(string $status)
427
-    {
428
-        $this->set('FIN_status', $status);
429
-    }
430
-
431
-
432
-    /**
433
-     * Form input type.
434
-     * Values correspond to the EventEspresso\core\domain\entities\form\Input::TYPE_* constants.
435
-     *
436
-     * @return string
437
-     * @throws EE_Error
438
-     * @throws ReflectionException
439
-     */
440
-    public function type(): ?string
441
-    {
442
-        return $this->get('FIN_type');
443
-    }
444
-
445
-
446
-    /**
447
-     * @param string $type
448
-     * @throws EE_Error
449
-     * @throws ReflectionException
450
-     */
451
-    public function setType(string $type)
452
-    {
453
-        $this->set('FIN_type', $type);
454
-    }
455
-
456
-
457
-    /**
458
-     * ID of the WP User that created this form input.
459
-     *
460
-     * @return int
461
-     * @throws EE_Error
462
-     * @throws ReflectionException
463
-     */
464
-    public function wp_user(): int
465
-    {
466
-        return $this->get('FIN_wpUser');
467
-    }
468
-
469
-
470
-    /**
471
-     * returns the id the wordpress user who created this question
472
-     *
473
-     * @param int $wp_user
474
-     * @throws EE_Error
475
-     * @throws ReflectionException
476
-     */
477
-    public function setWpUser(int $wp_user)
478
-    {
479
-        $this->set('FIN_wpUser', $wp_user);
480
-    }
481
-
482
-
483
-    /**
484
-     * @param array $set_cols_n_values
485
-     * @return bool|int|string
486
-     * @throws EE_Error
487
-     * @throws ReflectionException
488
-     */
489
-    public function save($set_cols_n_values = [])
490
-    {
491
-        // make sure internal versions for all composite objects are updated
492
-        $this->set('FIN_attributes', $this->attributes()->toArray());
493
-        $this->set('FIN_helpText', $this->helpText()->toArray());
494
-        $this->set('FIN_label', $this->label()->toArray());
495
-        $this->set('FIN_options', $this->options()->toArray());
496
-        $this->set('FIN_required', $this->required()->toArray());
497
-        return parent::save($set_cols_n_values);
498
-    }
32
+	/**
33
+	 * @var Attributes
34
+	 */
35
+	private $attributes;
36
+
37
+	/**
38
+	 * @var FormLabel
39
+	 */
40
+	private $label;
41
+
42
+	/**
43
+	 * @var HelpText
44
+	 */
45
+	private $helpText;
46
+
47
+	/**
48
+	 * @var InputOptions
49
+	 */
50
+	private $options;
51
+
52
+	/**
53
+	 * @var Required
54
+	 */
55
+	private $required;
56
+
57
+
58
+	/**
59
+	 * @param array $props_n_values
60
+	 * @return EE_Form_Element
61
+	 * @throws EE_Error
62
+	 * @throws ReflectionException
63
+	 */
64
+	public static function new_instance(array $props_n_values = []): EE_Form_Element
65
+	{
66
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
67
+		return $has_object ?: new self($props_n_values);
68
+	}
69
+
70
+
71
+	/**
72
+	 * @param array $props_n_values
73
+	 * @return EE_Form_Element
74
+	 * @throws EE_Error
75
+	 * @throws ReflectionException
76
+	 */
77
+	public static function new_instance_from_db(array $props_n_values = []): EE_Form_Element
78
+	{
79
+		return new self($props_n_values);
80
+	}
81
+
82
+
83
+	/**
84
+	 * Form Element UUID (universally unique identifier)
85
+	 *
86
+	 * @return string
87
+	 * @throws EE_Error
88
+	 * @throws ReflectionException
89
+	 */
90
+	public function UUID(): string
91
+	{
92
+		return $this->get('FIN_UUID');
93
+	}
94
+
95
+
96
+	/**
97
+	 * @param string $UUID
98
+	 * @throws EE_Error
99
+	 * @throws ReflectionException
100
+	 */
101
+	public function setUUID(string $UUID)
102
+	{
103
+		$this->set('FIN_UUID', $UUID);
104
+	}
105
+
106
+
107
+	/**
108
+	 * Whether or not input is only displayed in the admin. If false, input will appear in public forms
109
+	 *
110
+	 * @return bool
111
+	 * @throws EE_Error
112
+	 * @throws ReflectionException
113
+	 */
114
+	public function adminOnly(): ?bool
115
+	{
116
+		return $this->get('FIN_adminOnly');
117
+	}
118
+
119
+
120
+	/**
121
+	 * @param bool $admin_only
122
+	 * @throws EE_Error
123
+	 * @throws ReflectionException
124
+	 */
125
+	public function setAdminOnly(bool $admin_only)
126
+	{
127
+		$this->set('FIN_adminOnly', $admin_only);
128
+	}
129
+
130
+
131
+	/**
132
+	 * JSON string of HTML attributes such as class, max, min, placeholder, type, etc.
133
+	 *
134
+	 * @return Attributes
135
+	 * @throws EE_Error
136
+	 * @throws ReflectionException
137
+	 */
138
+	public function attributes(): ?Attributes
139
+	{
140
+		if (! $this->attributes instanceof Attributes) {
141
+			$this->attributes = Attributes::fromJson($this->get('FIN_attributes'));
142
+		}
143
+		return $this->attributes;
144
+	}
145
+
146
+
147
+	/**
148
+	 * @param Attributes $attributes
149
+	 * @throws EE_Error
150
+	 * @throws ReflectionException
151
+	 */
152
+	public function setAttributes(Attributes $attributes)
153
+	{
154
+		// set local object
155
+		$this->attributes = $attributes;
156
+		// then pass to model as an array which will get converted to JSON by the model field
157
+		$this->set('FIN_attributes', $attributes->toArray());
158
+	}
159
+
160
+
161
+	/**
162
+	 * UUID of parent form section this form input belongs to.
163
+	 *
164
+	 * @return string
165
+	 * @throws EE_Error
166
+	 * @throws ReflectionException
167
+	 */
168
+	public function belongsTo(): string
169
+	{
170
+		return $this->get('FSC_UUID');
171
+	}
172
+
173
+
174
+	/**
175
+	 * @param string $relation_UUID
176
+	 * @throws EE_Error
177
+	 * @throws ReflectionException
178
+	 */
179
+	public function setBelongsTo(string $relation_UUID)
180
+	{
181
+		$this->set('FSC_UUID', $relation_UUID);
182
+	}
183
+
184
+
185
+	/**
186
+	 * returns a HelpText object for managing input help text
187
+	 *
188
+	 * @return HelpText
189
+	 * @throws EE_Error
190
+	 * @throws ReflectionException
191
+	 */
192
+	public function helpText(): ?HelpText
193
+	{
194
+		if (! $this->helpText instanceof HelpText) {
195
+			$this->helpText = HelpText::fromJson($this->get('FIN_helpText'));
196
+		}
197
+		return $this->helpText;
198
+	}
199
+
200
+
201
+	/**
202
+	 * @param HelpText $helpText
203
+	 * @throws EE_Error
204
+	 * @throws ReflectionException
205
+	 */
206
+	public function setHelpText(HelpText $helpText)
207
+	{
208
+		// set local object
209
+		$this->helpText = $helpText;
210
+		// then pass to model as an array which will get converted to JSON by the model field
211
+		$this->set('FIN_helpText', $helpText->toArray());
212
+	}
213
+
214
+
215
+	/**
216
+	 * returns a FormLabel object for managing input labels
217
+	 *
218
+	 * @return FormLabel
219
+	 * @throws EE_Error
220
+	 * @throws ReflectionException
221
+	 */
222
+	public function label(): ?FormLabel
223
+	{
224
+		if (! $this->label instanceof FormLabel) {
225
+			$this->label = FormLabel::fromJson($this->get('FIN_label'));
226
+		}
227
+		return $this->label;
228
+	}
229
+
230
+
231
+	/**
232
+	 * @param FormLabel $label
233
+	 * @throws EE_Error
234
+	 * @throws ReflectionException
235
+	 */
236
+	public function setLabel(FormLabel $label)
237
+	{
238
+		// set local object
239
+		$this->label = $label;
240
+		// then pass to model as an array which will get converted to JSON by the model field
241
+		$this->set('FIN_label', $label->toArray());
242
+	}
243
+
244
+
245
+	/**
246
+	 * Model and Fields name that this input maps to; ex: Attendee.email
247
+	 *
248
+	 * @return string
249
+	 * @throws EE_Error
250
+	 * @throws ReflectionException
251
+	 */
252
+	public function mapsTo(): ?string
253
+	{
254
+		return $this->get('FIN_mapsTo');
255
+	}
256
+
257
+
258
+	/**
259
+	 * @param string $model ex: Attendee
260
+	 * @param string $field ex: email
261
+	 * @throws EE_Error
262
+	 * @throws ReflectionException
263
+	 */
264
+	public function setMapsTo(string $model, string $field)
265
+	{
266
+		$model_name = strpos($model, 'EEM_') !== 0 ? "EEM_$model" : $model;
267
+		if (! class_exists($model_name)) {
268
+			throw new DomainException(
269
+				sprintf(
270
+					esc_html__(
271
+						'The %1$s model does not exist or can not be located. Please verify the spelling and whether it is loaded.',
272
+						'event_espresso'
273
+					),
274
+					$model_name
275
+				)
276
+			);
277
+		}
278
+		$this->set('FIN_mapsTo', "{$model}.{$field}");
279
+	}
280
+
281
+
282
+	/**
283
+	 * Options for ENUM type inputs like checkboxes, radio buttons, select inputs, etc
284
+	 *
285
+	 * @return InputOptions
286
+	 * @throws EE_Error
287
+	 * @throws ReflectionException
288
+	 */
289
+	public function options(): ?InputOptions
290
+	{
291
+		if (! $this->options instanceof InputOptions) {
292
+			$this->options = InputOptions::fromJson($this->get('FIN_options'));
293
+		}
294
+		return $this->options;
295
+	}
296
+
297
+
298
+	/**
299
+	 * @param InputOptions $options
300
+	 * @throws EE_Error
301
+	 * @throws ReflectionException
302
+	 */
303
+	public function setOptions(InputOptions $options)
304
+	{
305
+		// set local object
306
+		$this->options = $options;
307
+		// then pass to model as an array which will get converted to JSON by the model field
308
+		$this->set('FIN_options', $options->toArray());
309
+	}
310
+
311
+
312
+
313
+	/**
314
+	 * Order in which form input appears in a form.
315
+	 *
316
+	 * @return int
317
+	 * @throws EE_Error
318
+	 * @throws ReflectionException
319
+	 */
320
+	public function order(): int
321
+	{
322
+		return $this->get('FIN_order');
323
+	}
324
+
325
+
326
+	/**
327
+	 * @param int $order
328
+	 * @throws EE_Error
329
+	 * @throws ReflectionException
330
+	 */
331
+	public function setOrder(int $order)
332
+	{
333
+		$this->set('FIN_order', $order);
334
+	}
335
+
336
+
337
+	/**
338
+	 * Example text displayed within an input to assist users with completing the form.
339
+	 *
340
+	 * @return string
341
+	 * @throws EE_Error
342
+	 * @throws ReflectionException
343
+	 */
344
+	public function placeholder(): ?string
345
+	{
346
+		return $this->get('FIN_placeholder');
347
+	}
348
+
349
+
350
+	/**
351
+	 * @param string $placeholder
352
+	 * @throws EE_Error
353
+	 * @throws ReflectionException
354
+	 */
355
+	public function setPlaceholder(string $placeholder)
356
+	{
357
+		$this->set('FIN_placeholder', $placeholder);
358
+	}
359
+
360
+
361
+	/**
362
+	 * Whether or not the input must be supplied with a value in order to complete the form.
363
+	 *
364
+	 * @return Required
365
+	 * @throws EE_Error
366
+	 * @throws ReflectionException
367
+	 */
368
+	public function required(): ?Required
369
+	{
370
+		if (! $this->required instanceof Required) {
371
+			$this->required = Required::fromJson($this->get('FIN_required'));
372
+		}
373
+		return $this->required;
374
+	}
375
+
376
+
377
+	/**
378
+	 * @param Required $required
379
+	 * @throws EE_Error
380
+	 * @throws ReflectionException
381
+	 */
382
+	public function setRequired(Required $required)
383
+	{
384
+		// set local object
385
+		$this->required = $required;
386
+		// then pass to model as an array which will get converted to JSON by the model field
387
+		$this->set('FIN_required', $required->toArray());
388
+	}
389
+
390
+
391
+	/**
392
+	 * version of public label for use in identifiers
393
+	 *
394
+	 * @return string
395
+	 * @throws EE_Error
396
+	 * @throws ReflectionException
397
+	 */
398
+	public function slug(): ?string
399
+	{
400
+		return sanitize_title($this->label()->publicLabel());
401
+	}
402
+
403
+
404
+	/**
405
+	 * Whether form input is active, archived, trashed, or used as a default on new forms.
406
+	 * Values correspond to the EEM_Form_Element::STATUS_* constants.
407
+	 *
408
+	 * @return string
409
+	 * @throws EE_Error
410
+	 * @throws ReflectionException
411
+	 */
412
+	public function status(): string
413
+	{
414
+		return $this->get('FIN_status');
415
+	}
416
+
417
+
418
+	/**
419
+	 * Whether form input is active, archived, trashed, or used as a default on new forms.
420
+	 * Values correspond to the EEM_Form_Element::STATUS_* constants.
421
+	 *
422
+	 * @param string $status
423
+	 * @throws EE_Error
424
+	 * @throws ReflectionException
425
+	 */
426
+	public function setStatus(string $status)
427
+	{
428
+		$this->set('FIN_status', $status);
429
+	}
430
+
431
+
432
+	/**
433
+	 * Form input type.
434
+	 * Values correspond to the EventEspresso\core\domain\entities\form\Input::TYPE_* constants.
435
+	 *
436
+	 * @return string
437
+	 * @throws EE_Error
438
+	 * @throws ReflectionException
439
+	 */
440
+	public function type(): ?string
441
+	{
442
+		return $this->get('FIN_type');
443
+	}
444
+
445
+
446
+	/**
447
+	 * @param string $type
448
+	 * @throws EE_Error
449
+	 * @throws ReflectionException
450
+	 */
451
+	public function setType(string $type)
452
+	{
453
+		$this->set('FIN_type', $type);
454
+	}
455
+
456
+
457
+	/**
458
+	 * ID of the WP User that created this form input.
459
+	 *
460
+	 * @return int
461
+	 * @throws EE_Error
462
+	 * @throws ReflectionException
463
+	 */
464
+	public function wp_user(): int
465
+	{
466
+		return $this->get('FIN_wpUser');
467
+	}
468
+
469
+
470
+	/**
471
+	 * returns the id the wordpress user who created this question
472
+	 *
473
+	 * @param int $wp_user
474
+	 * @throws EE_Error
475
+	 * @throws ReflectionException
476
+	 */
477
+	public function setWpUser(int $wp_user)
478
+	{
479
+		$this->set('FIN_wpUser', $wp_user);
480
+	}
481
+
482
+
483
+	/**
484
+	 * @param array $set_cols_n_values
485
+	 * @return bool|int|string
486
+	 * @throws EE_Error
487
+	 * @throws ReflectionException
488
+	 */
489
+	public function save($set_cols_n_values = [])
490
+	{
491
+		// make sure internal versions for all composite objects are updated
492
+		$this->set('FIN_attributes', $this->attributes()->toArray());
493
+		$this->set('FIN_helpText', $this->helpText()->toArray());
494
+		$this->set('FIN_label', $this->label()->toArray());
495
+		$this->set('FIN_options', $this->options()->toArray());
496
+		$this->set('FIN_required', $this->required()->toArray());
497
+		return parent::save($set_cols_n_values);
498
+	}
499 499
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
      */
138 138
     public function attributes(): ?Attributes
139 139
     {
140
-        if (! $this->attributes instanceof Attributes) {
140
+        if ( ! $this->attributes instanceof Attributes) {
141 141
             $this->attributes = Attributes::fromJson($this->get('FIN_attributes'));
142 142
         }
143 143
         return $this->attributes;
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
      */
192 192
     public function helpText(): ?HelpText
193 193
     {
194
-        if (! $this->helpText instanceof HelpText) {
194
+        if ( ! $this->helpText instanceof HelpText) {
195 195
             $this->helpText = HelpText::fromJson($this->get('FIN_helpText'));
196 196
         }
197 197
         return $this->helpText;
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
      */
222 222
     public function label(): ?FormLabel
223 223
     {
224
-        if (! $this->label instanceof FormLabel) {
224
+        if ( ! $this->label instanceof FormLabel) {
225 225
             $this->label = FormLabel::fromJson($this->get('FIN_label'));
226 226
         }
227 227
         return $this->label;
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
     public function setMapsTo(string $model, string $field)
265 265
     {
266 266
         $model_name = strpos($model, 'EEM_') !== 0 ? "EEM_$model" : $model;
267
-        if (! class_exists($model_name)) {
267
+        if ( ! class_exists($model_name)) {
268 268
             throw new DomainException(
269 269
                 sprintf(
270 270
                     esc_html__(
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
      */
289 289
     public function options(): ?InputOptions
290 290
     {
291
-        if (! $this->options instanceof InputOptions) {
291
+        if ( ! $this->options instanceof InputOptions) {
292 292
             $this->options = InputOptions::fromJson($this->get('FIN_options'));
293 293
         }
294 294
         return $this->options;
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
      */
368 368
     public function required(): ?Required
369 369
     {
370
-        if (! $this->required instanceof Required) {
370
+        if ( ! $this->required instanceof Required) {
371 371
             $this->required = Required::fromJson($this->get('FIN_required'));
372 372
         }
373 373
         return $this->required;
Please login to merge, or discard this patch.